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 ?
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 ?
Share Improve this question edited Mar 1, 2017 at 10:21 Lelio Faieta 6,6969 gold badges48 silver badges84 bronze badges asked Mar 1, 2017 at 10:07 Tommy1209Tommy1209 1993 silver badges13 bronze badges 4- .NET regex is quite powerful and can match balanced constructs, too. What have you tried? Why do you say you are writing it in C# but tagged the question with a JS tag? – Wiktor Stribiżew Commented Mar 1, 2017 at 10:08
- title says in JavaScript and content says in C#. – Sagar V Commented Mar 1, 2017 at 10:08
- sorry, i edited content of question – Tommy1209 Commented Mar 1, 2017 at 10:20
- validate -> whether the syntax is correct or not. evaluate -> whether the result is true or not. which one you want? – Sagar V Commented Mar 1, 2017 at 10:37
2 Answers
Reset to default 4While 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.
function validate(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 valid
if (replaced == "1") return true;
// if the pattern didn't match, it's invalid
if (replaced == expression) return false;
// otherwise, continue replacing
expression = replaced;
}
}
Note that the regex doesn't allow for extra spaces.
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);
function evaluate(string){
string=string.replace(/AND/g,'&&');
string=string.replace(/OR/g,'||');
string=string.replace(/NOT/g,'!');
console.log(eval(string));
}