Validate A Boolean Expression With Brackets In Javascript Regex
Solution 1:
In JavaScript, you can use the following.
replace 'AND/OR/NOT' with '&&/||/!'.
use eval
to evaluate it.
Careful because eval is a powerful function
var string = "0 AND 2";
var string1 = "0 OR 2";
var string2 = "NOT 0";
evaluate(string);
evaluate(string1);
evaluate(string2);
functionevaluate(string){
string=string.replace(/AND/g,'&&');
string=string.replace(/OR/g,'||');
string=string.replace(/NOT/g,'!');
console.log(eval(string));
}
Solution 2:
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)
or X AND/OR Y
or X
(where X
and Y
are digits). We replace all occurrences of this pattern with 1
(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.
functionvalidate(expression){
const pattern = /\(\d\)|\d (?:AND|OR) \d|\d/g;
while (true){
const replaced = expression.replace(pattern, "1");
// if the expression has been reduced to "1", it's validif (replaced == "1") returntrue;
// if the pattern didn't match, it's invalidif (replaced == expression) returnfalse;
// otherwise, continue replacing
expression = replaced;
}
}
Note that the regex doesn't allow for extra spaces.
Post a Comment for "Validate A Boolean Expression With Brackets In Javascript Regex"