简体   繁体   English

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

[英]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. 我在C#中建立了一个动态条件验证器,可以验证文本框输入中写入的条件是true还是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: 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. 整个地方的\\s*都是为了容忍多余的空格。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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