regex for simple math equation

后端 未结 2 1566
无人共我
无人共我 2020-12-12 02:16

I want to recognize integers or decimals and the four simple operations, broken into tokens I can\'t get the decimal to work, can you please help?

My reg is

相关标签:
2条回答
  • 2020-12-12 02:34

    It may works for you:

    expression = "2.7 + 3 * (1 + 2)";
    String expRegString = "\\d+(\\.\\d+)*|\\(\\d+(\\.\\d+)*[\\+\\-\\*\\/]\\d+(\\.\\d+)*\\)";
    
    0 讨论(0)
  • 2020-12-12 02:35

    You can try removing all spaces and then split your data on every place that is before or after characters - + * / ( ).

    This should do the trick

    String expression = "2.7 + 3 * (1 + 2)";
    String[] tokens = expression.replaceAll("\\s+", "").split("(?<=[-+*/()])|(?=[-+*/()])");
    
    for (String token : tokens)
        System.out.println(token);
    

    Output

    2.7
    +
    3
    *
    (
    1
    +
    2
    )
    
    0 讨论(0)
提交回复
热议问题