Validate a Boolean expression with brackets in javascript regex

廉价感情. 提交于 2019-12-24 05:45:16

问题


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 ?


回答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);
function evaluate(string){
  string=string.replace(/AND/g,'&&');
  string=string.replace(/OR/g,'||');
  string=string.replace(/NOT/g,'!');
  console.log(eval(string));
}



回答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.

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.



来源:https://stackoverflow.com/questions/42528748/validate-a-boolean-expression-with-brackets-in-javascript-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!