如何实现纯 JavaScript 代码来验证带有变量、and、or 的逻辑表达式字符串

问题描述 投票:0回答:1

我一直在四处寻找,但还没有找到任何好的解决方案,所以我想做的是我有以下输入字符串 (a&b|c)&d a&(b|c) (a&b)|(c&d) 所以基本上我想验证输入字符串是否是有效的逻辑表达式,并且下面的输入应该返回 false; a(b&c) a(&b|c) (a&b 那么想知道是否有标准方法可以做到这一点?

我试过这个代码 https://www.interviewkickstart.com/problems/valid-parentheses 但这并不能涵盖所有情况 (a(&b&c)) 将失败

expression
1个回答
0
投票

所以我实际上写了一些这样的代码

class Validator {
    #currentIndex;
    #expression;
    validate(expression) {
        this.#currentIndex = 0;
        this.#expression = expression;
        return this.#is_valid(false);
    }
    #is_valid(expectEndParenthese) {

        var preIsStartingOrOperator = true;
        while (this.#currentIndex < this.#expression.length) {

            const currentCharacter = this.#expression[this.#currentIndex];
            debugger;
            // variable or (...) can eventually evulated to true or False, so let's call it Evaluatable, so it can only be pre by an operator or starting
            if (this.#isDigit(currentCharacter) || currentCharacter === '(') {
                if (!preIsStartingOrOperator) {
                    return false;
                }
                preIsStartingOrOperator = false;
                if (currentCharacter === '(') {
                    this.#currentIndex++;
                    if (!this.#is_valid(true)) {
                        return false;
                    } else {
                        this.#currentIndex++;
                    }
                } else {
                    this.#currentIndex++;
                }
            } else if (this.#isOperator(currentCharacter)) {
                // operators can not be at the start of the expression or after another operator
                if (preIsStartingOrOperator) {
                    return false;
                }
                preIsStartingOrOperator = true;
                this.#currentIndex++;
            } else {
                // close parenthese can only after Evaluatable and there must be a start parenthese.
                return !preIsStartingOrOperator && expectEndParenthese;
            }
        }
        return !expectEndParenthese;
    }
    /*checks if the given character is a digit.*/
    #isDigit(c) {
        if (c >= '0' && c <= '9') {
            return true;
        }
        return false;
    }

    #isOperator(c) {
        if (c === '&' || c === '|') {
            return true;
        }
        return false;
    }
}

const validator = new Validator();
console.log(validator.validate("1&(2|(5|6|(7|0|8))&4)&3"));

它可以进行验证,所以我的理想是我将数字和左括号都视为可评估的,最终应该评估为真或假,并且这个

Evaluatable
只能添加在运算符的开头或后面,对于运算符来说,它只能添加在
Value
之后,并且对于每个 is_valid 递归,我们需要知道它是否expectEndparentheses

© www.soinside.com 2019 - 2024. All rights reserved.