简体   繁体   中英

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.

你可以使用一个第三方libray像回避率来评估你的表情。

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM