Regular expression to match digits and basic math operators

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>)?

Leave a Comment