How can tokenize this string in java?

后端 未结 9 1074
你的背包
你的背包 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.

    0 讨论(0)
  • 2021-01-14 17:58

    You could use StringTokenizer(String str, String delim, boolean returnDelims), with the operators as delimiters. This way, at least get each token individually (including the delimiters). You could then determine what kind of token you're looking at.

    0 讨论(0)
  • 2021-01-14 18:00

    You only put the delimiters in the split statement. Also, the - mean range and has to be escaped.

    "578+223-5^2".split("[*+\\-^()]")
    
    0 讨论(0)
提交回复
热议问题