| | |
| | | * @date 2024/3/27 |
| | | */ |
| | | public class CalculateUtil { |
| | | public static Map<String,Integer> getFieldsAndValue(String rule) { |
| | | public static Map<String, Integer> getFieldsAndValue(String rule) { |
| | | // 正则表达式模式,匹配形如 "fieldName:value" 的字符串 |
| | | Pattern pattern = Pattern.compile("\\b(\\w+)_(\\d+)\\b"); |
| | | Matcher matcher = pattern.matcher(rule); |
| | |
| | | while (matcher.find()) { |
| | | String fieldName = matcher.group(1); |
| | | int value = Integer.parseInt(matcher.group(2)); |
| | | map.put(fieldName+"_"+value, value); |
| | | map.put(fieldName + "_" + value, value); |
| | | } |
| | | return map; |
| | | } |
| | | public static double calculate(String expression,Map<String,Object> value) { |
| | | |
| | | public static double calculate(String expression, Map<String, Object> value) { |
| | | expression = formatExpression(expression); |
| | | // 创建 JEXL 引擎 |
| | | JexlEngine jexl = new JexlBuilder().create(); |
| | |
| | | // 创建上下文 |
| | | JexlContext context = new MapContext(); |
| | | for (Map.Entry<String, Object> stringObjectEntry : value.entrySet()) { |
| | | context.set(stringObjectEntry.getKey(),stringObjectEntry.getValue()); |
| | | context.set(stringObjectEntry.getKey(), stringObjectEntry.getValue()); |
| | | } |
| | | // 执行计算 |
| | | Object result = exp.evaluate(context); |
| | |
| | | .replaceAll("÷", "/") |
| | | .replaceAll("(", "(") |
| | | .replaceAll(")", ")") |
| | | .replaceAll("+","+") |
| | | .replaceAll("+", "+") |
| | | .replaceAll("-", "-"); |
| | | } |
| | | } |