package net.riking.util; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class TestUtil { static ScriptEngine jse = new ScriptEngineManager().getEngineByName("JavaScript"); public static void main(String[] args) { String logicValue = "A1+B3-B4"; // 根据运算符切割 String[] cells = logicValue.split("[\+\-\*\/]"); for (String str : cells) { System.out.println(str); } // 按顺序提取运算符 String[] strs = matchData(logicValue); for (String str : strs) { System.out.println(str); } StringBuffer sb = new StringBuffer(); for (int i = 0; i < cells.length; i++) { sb.append(cells[i]); if (i < strs.length) { sb.append(strs[i]); } } System.out.println(sb); // 通过解析提取,用值替换单元格,计算如:20+11-13 try { Object obj = jse.eval("20+11-13"); System.out.println("20+11-13=" + obj); } catch (ScriptException e) { e.printStackTrace(); } } public static String[] matchData(String logicValue){ List<String> list=new ArrayList<>(); Pattern p; Matcher m; p = Pattern.compile("\+|\-|\*|\/|\(|\)"); m = p.matcher(logicValue); while(m.find()){ list.add(m.group()); } return list.stream().toArray(String[]::new); } }
运行结果: