Regular expression to match digits and basic math operators

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]+)

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

Tags:

Regex