1

I'm going to validate simple math expressions such these:

a = 1 + 2
b = 2.2
a = b + 5.5
a = b - -5.5
a = -1 + 2
a = -2.4
a = 3.5 / 0.2 + 1
a = 3 * -2.1

NOTE: Operator precedence is not important!

I try following expressions but i got nothing!!!

for digits: ^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$
for operators: [-]|[+]|[*]|[/]
for variables: [a-z]+|[A-Z]+

I put these expressions in C# string variables and used .net Regex.Matches(...) to find matches. But i got nothing!

Jalal
  • 6,594
  • 9
  • 63
  • 100

3 Answers3

3

This is not a great job for regular expressions. IF you want to evaluate the true mathematical expression you will not be able to come up with a regex that can handle all cases. As Carl Norum said it is a similar discussion as to why you can't parse html with regex.

Community
  • 1
  • 1
rerun
  • 25,014
  • 6
  • 48
  • 78
1

Try:

for digits: ((-[0-9]|[0-9])(\.[0-9])|[0-9])
for operators: (-|\+|\*|\/)
for variables: ([a-z]|[A-Z])

These looked fine when tested in Regulator.

EDIT

First one might be a little 'sloppy', I ran out of lunch time to mess with it :P

Tony Abrams
  • 4,505
  • 3
  • 25
  • 32
0

Writing good regular expressions for even simple things is harder than it seems. Start with proven expressions and modify as needed:

http://regexlib.com

If you can't find an example, they have a forum dedicated to exactly this kind of question.

ErnieL
  • 5,773
  • 1
  • 23
  • 27