Arithmetic Expression Validate
Validate a string arithemetic expression
Source
Public static class Validator
{
static Regex ArithmeticExpression = new Regex(@"(?x)
^
(?> (?<p> \( )* (?>-?\d+(?:\.\d+)?) (?<-p> \) )* )
(?>(?:
[-+*/]
(?> (?<p> \( )* (?>-?\d+(?:\.\d+)?) (?<-p> \) )* )
)*)
(?(p)(?!))
$
");
public static bool ValidateArithmeticExpression(this string expression)
{
if (string.IsNullOrEmpty(expression))
return false;
return ArithmeticExpression.IsMatch(expression);
}
}
Example
string s = "(2+5)/3*(1*6)";
s.ValidateArithmeticExpression();