I need a regular expression that will match
0
-9
, (
,)
,+
,-
,*
and /
.
The accepted answer can't handle a lot of basic cases. This should do the job:
^([-+]? ?(\d+|\(\g<1>\))( ?[-+*\/] ?\g<1>)?)$
Explaination:
We want to match the entire string:
^...$
Expressions can have a sign:
[-+]? ?
An expression consists of multiple digits or another valid expression, surrounded by brackets:
(\d+|\(\g<1>\))
A valid expression can be followed by an operation and another valid expression and is still a valid expression:
( ?[-+*\/] ?\g<1>)?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With