The sequence is given (-1.2 + 3.0) + 2-8 / 6.
It is necessary to break the string into characters and numbers.
How do I edit this template? I need the minus number in front of it to be considered negative only if it is first in the expression. Now it turns out -1.2 and -8 (and not - and 8).

^-?\\d+\\.?\\d*|[-+*/()] 
  • Regular expressions are not suitable for the correct analysis of arithmetic expressions. Write a normal parser. - avp

1 answer 1

What answer is desirable for 3+(-1 + 2) : -1 or - , 1 ? I think -1 , even if -1 not "first in expression". If parentheses restrict "expression", i.e. (-1) always interpreted as -1 , and not ( - , 1 ), then formally it is no longer possible to recognize an expression using a "regular expression" if brackets can be nested an arbitrary number of times, for example: 4 + (-3 + (-1 + 2)) . Although in fact many regex libraries support recursive syntax, here is an example of how to recognize expressions in nested brackets .

There are many examples of how mathematical expressions can be parsed, for example, the hoc calculator described in the book "Unix. Software environment" Rob Pike, Brian Kernighan .