Regular expression to match digits and basic math operators
I need a regular expression that will match
0
-9
, (
,)
,+
,-
,*
and /
.
Solution 1:
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>)?
Solution 2:
It looks like you might be trying to match numeric expressions like 5+7-3.
This should match them :
([-+]?[0-9]*\.?[0-9]+[\/\+\-\*])+([-+]?[0-9]*\.?[0-9]+)
Solution 3:
[\d\(\)\+\-\*\/\.]