tags:

views:

112

answers:

3

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!

+3  A: 

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.

rerun
It's completely different by HTML! it's just a simple assignment expressions...!
Jalal Amini
If its not true math expression and you limit your input then sure.
rerun
I need validate some simple assignment expression!
Jalal Amini
+1  A: 

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
thank you!!! :D
Jalal Amini
A: 

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