在javascript正则表达式中使用方括号验证布尔表达式 [英] Validate a Boolean expression with brackets in javascript regex

查看:139
本文介绍了在javascript正则表达式中使用方括号验证布尔表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在javascript中验证一个字符串,该字符串包含带有方括号的布尔表达式.该字符串应仅包含数字1-9()ORAND.

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.

好的字符串示例:

"1和2"

"1 AND 2"

"2或4"

"4 AND(3或5)"

"4 AND (3 OR 5)"

我不确定正则表达式是否足够灵活地完成此任务.有没有一种很好的简短方法可以在javascript中实现这一目标?

I am not sure if Regular Expression are flexible enough for this task. Is there a nice short way of achieving this in javascript ?

推荐答案

在JavaScript中,您可以使用以下内容.
使用eval对其进行评估.

In JavaScript, you can use the following.
replace 'AND/OR/NOT' with '&&/||/!'.
use eval to evaluate it.

谨慎,因为eval是强大的功能

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));
}

这篇关于在javascript正则表达式中使用方括号验证布尔表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆