ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

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();

Author: Muhammed Haris K

Submitted on: 2 jun. 2015

Language: C#

Type: System.String

Views: 3980