我有一个中缀表达式:((attribute1*attribute2)/attribute3+attribute4)
它可能会根据用户输入而变化。我想检查表达式是否有效。
有效示例:((attribute1*attribute2)/attribute3+attribute4)
无效示例:(attrribute1*attribute2+*(attribute3)
第二个没有右括号;还有*
不需要运算符(operator)。如何在 JavaScript 中执行此类验证?
现在这是我的正则表达式:
/ *\+? *\-? *[a-zA-Z0-9]+ *( *[\+\-\*\/\=\<\>\!\&\|\%] *\+? *\-? *[a-zA-Z0-9]+ *)*/
我需要一个用于比较运算符的正则表达式,例如 <=
, >=
, !=
, ==
等等。我该如何实现这个?
最佳答案
你可以尝试这样的事情:
function validateInfix(infix) {
var balance = 0;
// remove white spaces to simplify regex
infix = infix.replace(/\s/g, '');
// if it has empty parenthesis then is not valid
if (/\(\)/.test(infix)) {
return false;
}
// valid values: integers and identifiers
var value = '(\\d+|[a-zA-Z_]\\w*)';
// the unary '+' and '-'
var unaryOper = '[\\+\\-]?';
// the arithmetic operators
var arithOper = '[\\+\\-\\*\\/]';
// the comparison operators
var compOper = '(\\<\\=?|\\>\\=?|\\=\\=|\\!\\=)';
// if it has more than one comparison operator then is not valid
if (infix.match(new RegExp(compOper, 'g')).length > 1) {
return false;
}
// the combined final regex: /[\+\-]?(\d+|[a-zA-Z_]\w*)(([\+\-\*\/]|(\<\=?|\>\=?|\=\=|\!\=))[\+\-]?(\d+|[a-zA-Z_]\w*))*/
var regex = new RegExp(unaryOper + value + '((' + arithOper + '|' + compOper + ')' + unaryOper + value + ')*');
// validate parenthesis balance
for (var i = 0; i < infix.length; i++) {
if (infix[i] == '(') {
balance++;
}
else if (infix[i] == ')') {
balance--;
}
if (balance < 0) {
return false;
}
}
if (balance > 0) {
return false;
}
// remove all the parenthesis
infix = infix.replace(/[\(\)]/g, '');
return regex.test(infix);
}
这个想法是首先检查括号平衡,然后将它们全部删除,因为我们只想验证而不是评估,然后将剩余的表达式与正则表达式匹配(这可能不完美,我不是正则表达式专家)。并且...以防万一:infix
参数必须是字符串。
编辑
我注意到一些细节并稍微更改了代码:
- 添加了您也需要正则表达式来匹配的运算符。
- 删除了空格以消除正则表达式垃圾。
- 检查表达式是否有空括号。
- 检查表达式是否有多个比较运算符。
- 将此
\+?\-?
更改为此[\+\-]?
。 - 已更改 string
match
method通过 regextest
method尽可能。 - 由于第一个匹配,因此将
[a-zA-Z0-9]
更改为(\d+|[a-zA-Z_]\w*)
错误的标识符,如53abc
。 - 为了更好地理解和清晰起见,将正则表达式片段提取到单独的变量中,并根据这些变量构建最终的变量。
希望现在对您来说没问题:)
关于javascript - 如何验证 JavaScript 中的中缀表示法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20833880/