javascript - 如何验证 JavaScript 中的中缀表示法?

标签 javascript validation expression comparison-operators infix-notation

我有一个中缀表达式:((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 参数必须是字符串。

编辑

我注意到一些细节并稍微更改了代码:

  1. 添加了您也需要正则表达式来匹配的运算符。
  2. 删除了空格以消除正则表达式垃圾。
  3. 检查表达式是否有空括号。
  4. 检查表达式是否有多个比较运算符。
  5. 将此 \+?\-? 更改为此 [\+\-]?
  6. 已更改 string match method通过 regex test method尽可能。
  7. 由于第一个匹配,因此将 [a-zA-Z0-9] 更改为 (\d+|[a-zA-Z_]\w*)错误的标识符,如 53abc
  8. 为了更好地理解和清晰起见,将正则表达式片段提取到单独的变量中,并根据这些变量构建最终的变量。

希望现在对您来说没问题:)

关于javascript - 如何验证 JavaScript 中的中缀表示法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20833880/

相关文章:

javascript - 渲染时 Handlebars 部分打印 [Object object]

java - 使用自定义 validator 手动验证,无需默认构造函数

c++ - 使用 cin.fail 进行 CIN 验证

c# - 检查表达式是否有自由参数

c# - 在 SQL Server 上筛选 Entity Framework 结果

javascript - 在 Facebook Graph API 查询中使用 with=location 时出现 "Uncaught (in promise) undefined"错误

javascript - 将计数 javascript 程序设置为小数点后两位

javascript - Firefox 上的 jQuery URL 获取错误

javascript - 客户端自定义验证未执行

javascript - Angularjs 使用表达式进行验证