How can tokenize this string in java?

后端 未结 9 1072
你的背包
你的背包 2021-01-14 17:32

How can I split these simple mathematical expressions into seperate strings?

I know that I basically want to use the regular expression: \"[0-9]+|[*+-^()]\"

9条回答
  •  别那么骄傲
    2021-01-14 17:54

    Going at this laterally, and assuming your intention is ultimately to evaluate the String mathematically, you might be better off using the ScriptEngine

    import javax.script.ScriptEngine;
    import javax.script.ScriptEngineManager;
    import javax.script.ScriptException;
    
    public class Evaluator {
    private ScriptEngineManager sm = new ScriptEngineManager();
    private ScriptEngine sEngine = sm.getEngineByName("js");
    
    public double stringEval(String expr)
    {
    Object res = "";
            try {
               res = sEngine.eval(expr);
              }
             catch(ScriptException se) {
                se.printStackTrace();
            }
            return Double.parseDouble( res.toString());
    }
    
    }
    

    Which you can then call as follows:

    Evaluator evr = new Evaluator();  
    String sTest = "+1+9*(2 * 5)";  
    double dd = evr.stringEval(sTest);  
    System.out.println(dd); 
    

    I went down this road when working on evaluating Strings mathematically and it's not so much the operators that will kill you in regexps but complex nested bracketed expressions. Not reinventing the wheel is a) safer b) faster and c) means less complex and nested code to maintain.

提交回复
热议问题