regex for simple math equation

后端 未结 2 1567
无人共我
无人共我 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: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
    )
    

提交回复
热议问题