mitao
2024-03-27 789b5b823440d174a198a35fd033ca975cb54f4a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.ruoyi.common.utils;
 
import org.apache.commons.jexl3.*;
 
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
/**
 * @author mitao
 * @date 2024/3/27
 */
public class CalculateUtil {
    public static Map<String,Integer> getFieldsAndValue(String rule) {
        // 正则表达式模式,匹配形如 "fieldName:value" 的字符串
        Pattern pattern = Pattern.compile("\\b(\\w+)_(\\d+)\\b");
        Matcher matcher = pattern.matcher(rule);
        Map<String, Integer> map = new HashMap<>();
        // 循环匹配并输出字段名和值
        while (matcher.find()) {
            String fieldName = matcher.group(1);
            int value = Integer.parseInt(matcher.group(2));
            map.put(fieldName+"_"+value, value);
        }
        return map;
    }
    public static double calculate(String expression,Map<String,Object> value) {
        expression = formatExpression(expression);
        // 创建 JEXL 引擎
        JexlEngine jexl = new JexlBuilder().create();
 
        // 创建表达式对象
        JexlExpression exp = jexl.createExpression(expression);
        // 创建上下文
        JexlContext context = new MapContext();
        for (Map.Entry<String, Object> stringObjectEntry : value.entrySet()) {
            context.set(stringObjectEntry.getKey(),stringObjectEntry.getValue());
        }
        // 执行计算
        Object result = exp.evaluate(context);
 
        // 输出结果
        System.out.println("Result: " + result);
        return Double.parseDouble(result.toString());
    }
 
    public static String formatExpression(String expression) {
        return expression
                .replaceAll("×", "*")
                .replaceAll("÷", "/")
                .replaceAll("(", "(")
                .replaceAll(")", ")")
                .replaceAll("+","+")
                .replaceAll("-", "-");
    }
}