I want to validate a string in javascript that contains a Boolean expression with brackets. The string should only contain numbers 1-9
, ()
, OR
, AND
.
Examples of good strings:
"1 AND 2"
"2 OR 4"
"4 AND (3 OR 5)"
I am not sure if Regular Expression are flexible enough for this task. Is there a nice short way of achieving this in javascript ?
In JavaScript, you can use the following.
replace 'AND/OR/NOT' with '&&/||/!'.
use
eval
to evaluate it.Careful because eval is a powerful function
While regex alone isn't powerful enough for this task (because JS regex can't handle nested braces), it's an easy task with a little help from Javascript.
Since we can't deal with nested braces, we'll deal with the braces one at a time until none are left. The pattern
\(\d\)|\d (?:AND|OR) \d|\d
will match an expression of the form(X)
orX AND/OR Y
orX
(whereX
andY
are digits). We replace all occurrences of this pattern with1
(or any other valid expression in your boolean language), until the pattern no longer matches. If after all replacements are done the string is"1"
, then it was a valid expression.Note that the regex doesn't allow for extra spaces.