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.
You could use a third party libray like Flee to evaluate your expressions.
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.
^\d+\s*(>=|<|>|<=|=|==|!=|<>)\s*\d+$
精彩评论