解析函数表达式

1.

public static final Pattern PATTERN_PARAM = Pattern.compile("^([\\w.]+)\\W*\\((.*)\\)$", Pattern.CASE_INSENSITIVE);


    public static Pair<String, Object[]> getFunctionParams(String expression) {
        if (StringUtils.isBlank(expression)) {
            return null;
        }

        Matcher matcher = PATTERN_PARAM.matcher(expression);
        List<String> arguments = new ArrayList<>();
        String functionName = null;
        if (matcher.find()) {
            functionName = matcher.group(1);
            String argumentsString = matcher.group(2);
            if (StringUtils.isNotBlank(argumentsString)) {
                int startIndex = 0;
                boolean inQuote = false;
                for (int i = 0; i < argumentsString.length(); i++) {
                    char c = argumentsString.charAt(i);
                    if (c == '\"') {
                        inQuote = !inQuote;
                    } else if (c == ',' && !inQuote) {
                        arguments.add(argumentsString.substring(startIndex, i));
                        startIndex = i + 1;
                    }
                }
                arguments.add(argumentsString.substring(startIndex));
            }
            System.out.println(arguments);
        }

        if (arguments.size() == 0) {
            return new Pair<>(functionName, new Object[0]);
        }
        Object[] objects = new Object[arguments.size()];
        for (int i = 0; i < arguments.size(); i++) {
            String param = arguments.get(i);
            if (param.contains("'")) {
                objects[i] = param.substring(param.indexOf("'") + 1, param.lastIndexOf("'"));
            } else if (param.contains("\"")) {
                objects[i] = param.substring(param.indexOf("\"") + 1, param.lastIndexOf("\""));
            } else if (param.contains(".")) {
                objects[i] = Double.parseDouble(param);
            } else {
                objects[i] = Long.parseLong(param);
            }
        }
        return new Pair<>(functionName, objects);
    }

2.

 String function = "encrypt(\"1234\",\"{\"a\":123,\"b\":\"123\"}\")  ";
        Pair<String, Object[]> params = getFunctionParams(function.trim());
        System.out.println(params);

        function = "random()  ";
        params = getFunctionParams(function.trim());
        System.out.println(params);

        function = "random(1,100)  ";
        params = getFunctionParams(function.trim());
        System.out.println(params);

 

posted @ 2023-07-11 10:20  zslm___  阅读(11)  评论(0编辑  收藏  举报