Regex validation of operators in conditional statements

I've built a dynamic conditional validator in C# that can validate if a condition written in a textbox input is true or false.

string a = "25 > 20";
bool aResult = ValidateInput(a); // Will generate true

string b = "10 != 10";
bool bResult = ValidateInput(b); // Will generate false

Now im stuck at validating the input which comes from a textbox, Im thinking regex but dont know where to start really.

The valid conditionals are

=   ==   <   >   <=   >=   !=

Any advice is highly appreciated

Thanks.


你可以像Flee一样使用第三方库文件来评估你的表达式。


Assuming you only allow integers on each side of the conditional, something like this should work:

^s*d+s*(?:==?|<=?|>=?|!=)s*d+s*$

The s* all over the place is to make this very tolerant of extra whitespace.


Or you can split the string based on your operators and then perform the validation.

A quick and dirty code sample in LinqPad:

void Main()
{
    string a = "25 > 20";

    string b = "10 != 10";


    var splits = a.Split(new string[]{}, StringSplitOptions.RemoveEmptyEntries);

    splits.Dump();


    var result = Validate(splits);
    result.Dump();

    splits = b.Split(new string[]{}, StringSplitOptions.RemoveEmptyEntries);

    splits.Dump();
    result = Validate (splits);

    result.Dump();
}

// Define other methods and classes here

bool Validate(string[] input)
{
var op = input[1];
switch(op)
    {
    case ">":
    return int.Parse(input[0]) > int.Parse(input[2]);
    case "!=":
    return int.Parse(input[0]) != int.Parse(input[2]);
    }
    return false;
}

You can easily customize this a lot if you want to.

链接地址: http://www.djcxy.com/p/77008.html

上一篇: Javascript RegEx部分匹配

下一篇: 条件语句中运算符的正则表达式验证