Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

regex that matches simple arithmetic expressions

i have a solution, but the only problem is that for example "7=7=7" is matched and that should not be the case.

^[+-]?\d+([/*+-]\d+)*([/*+-]*=(?:[+-]?\d+([/*+-]\d+)*)+)*$

see below of what is matched and not

these are matched and that is correct

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

456+5
0
0+0
5=0
1589+232
55+2
5+55
545454545
-12*53+1-2/5
+1+2+3=-5*2/3
000=0
18=+17/25
0-0
0*0
0/0
1/1
5/5
6*6
55/55
1/22
+55
5+5+5+5+5+5+5+5+5+5+5+5+5+5+5+5+5+5*5*5*5/5/5/5*5*5*5=5*5*5*5*5*5*5*5*5*5*5*5*5*5/5+5/5-6/5555/6
0*0*0*0*0*0*0+0=00000000*0*0
003+3*2

these shouldnt be matched which all of them except "7=7=7" does.

0=
5654*45=
*23
55++55
55+
7=7=7
18/-35
5*x
3.14159265358

how can i fix that the equal sign can only be there once, while also having a must that if a equal sign is there then there has to be a number after that

the answer must a regex

>Solution :

You could replace the final * with ?: that way it can only occur once at the most:

^[+-]?\d+([/*+-]\d+)*([/*+-]*=(?:[+-]?\d+([/*+-]\d+)*)+)?$

Be aware that your regex also allows this:

1+1++++++++=1

That doesn’t seem right. I’m not sure why you have that [/*+-]* sitting before =.

You could avoid some repetition by using a negative look ahead assertion:

^(?!.*=.*=)[+-]?\d+(([/*+-]|=[+-]?)\d+)*$
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading