I have an arithmetic expression
string exp = "((2+3.1)/2)*4.456";
I want to validate by using regular expression. The expression can only have integers, floating point numbers, operands and parenthesis.
How can i generate regular expression to validate please help or suggest any other way to validate that string.
Using Perl/PCRE we could verify such simple arithmetic expressions with help of a pattern structured like:
Where
numandopdefined as required. For example:Which would give us the following working expression:
But such expressions could not be used with .NET regex as it does not support (recursive) suppatern calls
(?&name).Instead .NET regex lib offers us its special feature: balancing groups.
With balancing groups we could rewrite the required recursive call used in
pnum, and use a structure like this instead:What we’ve done here is to allow any number of optional opening and closing paranthesis before and after every number, counting the total number of open parentheses
(?<p> \( ), subtracting closing parentheses from that number(?<-p> \) )and at the end of the expression make sure that the number of open parentheses is 0(?(p)(?!)).(I believe this is equivalent to the original structure, altho I haven’t made any formal proof.)
Resulting in the following .NET pattern:
C# Example:
Output: