• Java中类似单元格之间的计算公式解析,如A1+B3-B4


    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);
        }
    }
    

      运行结果:

  • 相关阅读:
    各种知识点
    链表
    滑动窗口
    数组

    【转】无重复字符的最长子串
    【转】荷兰国旗问题 三指针排序
    【转】回溯思想团灭排列、组合、子集问题
    【LeetCode】45. 跳跃游戏 II
    动态分配内存初始化二维数组
  • 原文地址:https://www.cnblogs.com/Big-Boss/p/10653053.html
Copyright © 2020-2023  润新知