最近接触spring的表达式计算很好用,但是解析表达式参数赋值还需要一些算法,自己写了一个。
代码:
- import com.alibaba.fastjson.JSONObject;
- import org.springframework.expression.EvaluationContext;
- import org.springframework.expression.Expression;
- import org.springframework.expression.ExpressionParser;
- import org.springframework.expression.spel.standard.SpelExpressionParser;
- import org.springframework.expression.spel.support.StandardEvaluationContext;
-
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Map;
-
- public class ElUtil {
-
- public static Integer pareser(String el, Map<String,String> map){
-
- ExpressionParser parser = new SpelExpressionParser();
- Expression expression = parser.parseExpression(el);
- EvaluationContext context = new StandardEvaluationContext();
- for (String m: map.keySet()
- ) {
- context.setVariable(m, Integer.valueOf(map.get(m)));
- }
- return expression.getValue(context,Integer.class);
-
- }
-
- public static void pick(String el){
-
- List list = new ArrayList<>();
-
- el = el.trim();
-
- for(int i=0;i<el.length();i++)
-
- if(el.charAt(i)=='#'){
-
- int j=i+1;
-
- while(j<el.length()) {
-
- if (el.charAt(j) == '+' || el.charAt(j) == '-' || el.charAt(j) == '*' || el.charAt(j) == '/' || el.charAt(j) == '(' || el.charAt(j) == ')') {
-
- String field = el.substring(i + 1, j);
- list.add(field);
-
-
- i = j;
- break;
- }
- if(j+1==el.length()){
-
- String field = el.substring(i + 1);
- list.add(field);
- break;
- }
- j++;
-
- }
-
- }
-
- System.out.println(JSONObject.toJSONString(list));
-
- }
-
- public static void main(String[] args) {
-
- pick("(#a+#b)/(#c+#d)*(#e+#f)");
- }
- }
输出
["a","b","c","d","e","f"]
这样就可以传个map,然后计算了