Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to match digits and basic math operators

Tags:

regex

I need a regular expression that will match 0-9, (,),+,-,* and /.

like image 671
DNB5brims Avatar asked Oct 27 '09 15:10

DNB5brims


1 Answers

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>)?
like image 98
ndnenkov Avatar answered Oct 12 '22 06:10

ndnenkov