The basic arithmetic regular expression does not match a single positive / negative number

I use the following RegEx to basically filter out any text and accept the numeric + operators.

([-+]?[0-9]*\.?[0-9]+[\/\+\-\*])+([-+]?[0-9]*\.?[0-9]+)

Thus, it captures 1 + 1, 1-1, 2 * 2, 10/2, etc. Since the solution that I write does not just evaluate the expression in the string, but also sums up all the calculated strings in total, I need to allow users to put separate positive / negative numbers, which will affect the total number (500, -500, +500 (check fool)).

Here is the test that I performed. I need to be able to match +500, -500 and 500 in test cases, still excluding any text. I am absolutely terrible with RegEx, so any help is greatly appreciated!

+4
source share
2 answers

Your regex requires both groups to be present at least once. You can make the first group an option by changing +to *to require the second group to match and make it a little shorter like this.

(?:[-+]?\d*\.?\d+[\/*+-])*(?:[+-]?\d*\.?\d+)

See demo at regex101

+1
source

If I understand your purpose well, you can simply replace +in the middle with *:

([-+]?[0-9]*\.?[0-9]+[\/\+\-\*])*([-+]?[0-9]*\.?[0-9]+)
+1
source

Source: https://habr.com/ru/post/1615273/


All Articles