Click here to Skip to main content
15,895,142 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Hi, We are working on a program where we need to validate string within if (string )
Such that string is always a condition which needs to be evaluate.

Example :
C#
1) if (" 5 > 4 && 8/2 >= 3" ) -- In programming world condition within if () is true.
2) if (" 5 > 4 && > 8/2 >= 3" ) -- In programming world condition within if () is false.


Any suggestion / recommendation how to validate such strings within if ( ) will be of great help.

Regards
Posted
Updated 15-Apr-15 7:42am
v2
Comments
Thomas Daniels 15-Apr-15 13:38pm    
Your question is tagged both C# and Java; which language do you use?
Matt T Heffron 15-Apr-15 13:50pm    
Are you asking for a RegEx that will evaluate the condition? Or merely to indicate if it is "well formed"?
What are the constraints on the form of the conditions?
Both And and Or? Nested (in parentheses)?
This is almost certainly beyond a RegEx even to determine if well formed; and there's no way RegEx will evaluate it.
You need an expression parser.
There are many articles here on CodeProject on parsing.
ankurparikh 15-Apr-15 14:32pm    
Hi Matt, looking to indicate if it is "well formed"
Sergey Alexandrovich Kryukov 15-Apr-15 14:00pm    
This is not how RegEx works. You probably can get help if you specify exactly what you want to achieve.
—SA
ankurparikh 15-Apr-15 14:33pm    
Hi Sergey, want to check / validate if condition within "if ( ) " are well formed.


Regular expressions are text matching tools: they do not evaluate strings , and they are very poor at syntactical analysis.

Basically, you can't do it with a regex - or if you can it'll be so silly that you can't maintain or probably even properly test it.

Instead, look at something like this: The expression evaluator revisited (Eval function in 100% managed .NET)[^] - which is designed to do that.
 
Share this answer
 
Please see my comment to the question: this is not how Regular Expressions work.

Just one idea: you could use your language using Regex, Java or C#, whatever you are really using, to do the branching based on some condition. And then, you could have to different Regex objects, one for one branch, another for another. Isn't this simple? Could be more readable and maintainable, too. :-)

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900