I want to validate a string in C# that contains a Boolean expression with brackets.
The string should only contain numbers 1-9, round brackets, “OR” , “AND”.
Examples of good strings:
“1 AND 2”
“2 OR 4”
“4 AND (3 OR 5)”
“2”
And so on…
I am not sure if Regular Expression are flexible enough for this task.
Is there a nice short way of achieving this in C# ?
It’s probably simpler to do this with a simple parser. But you can do this with .NET regex by using balancing groups and realizing that if the brackets are removed from the string you always have a string matched by a simple expression like
^\d+(?:\s+(?:AND|OR)\s+\d+)*\z.So all you have to do is use balancing groups to make sure that the brackets are balanced (and are in the right place in the right form).
Rewriting the expression above a bit:
(
(?x)makes the regex engine ignore all whitespace and comments in the pattern, so it can be made more readable.)Where
OPENINGmatches any number (0 included) of opening brackets:CLOSINGmatches any number of closing brackets also making sure that the balancing group is balanced:and
BALANCEDperforms a balancing check, failing if there are more open brackets then closed:Giving the expression:
If you do not want to allow random spaces remove every
\s*.Example
See demo at IdeOne. Output: