开发中有时会遇到需要截取一个字符串中某个变量后面带的值,并对这个值做简单运算的情况,比如“tom, age 23, come fron us”, 这里想判断年龄是否大于30岁,实现如下:
1 String inputstr = "tom, age 23, come fron us"; 2 String matchString = "age 变量1"; // 需要截取的变量正则表达式 3 String ruleString = "变量1 > 30"; // 比较的公式 4 5 // 1、使用正则表达式截取年龄值 6 String paramRegex = "(变量[0-9]{1,})"; 7 Pattern patternFetchParams = Pattern.compile(paramRegex); 8 Matcher matcherFetchParams = patternFetchParams.matcher(matchString); 9 10 String paramName = null; // 获取变量名:变量1 11 if(matcherFetchParams.find()) { 12 paramName = matcherFetchParams.group(1); 13 } 14 System.out.println("paramName: " + paramName); // paramName: 变量1 15 16 String ruleRegex = matchString.replaceAll("(变量[0-9]{1,})", "(\\S*)"); 17 Pattern pattern = Pattern.compile(ruleRegex); 18 Matcher matcher = pattern.matcher(inputstr); 19 String paramValue = null; // 获取变量值:23 20 if(matcher.find()) { 21 paramValue = matcher.group(1); 22 paramValue = paramValue.replace(",", ""); 23 } 24 System.out.println("paramValue: " + paramValue); // paramValue: 23 25 26 // 1、使用javascript引擎判断是否满足公式 27 ScriptEngineManager manager = new ScriptEngineManager(); 28 ScriptEngine engine = manager.getEngineByName("javascript"); 29 engine.put(paramName, paramValue); 30 31 boolean result = (Boolean) engine.eval(ruleString); 32 System.out.println("result: " + result); // result: false