簡體   English   中英

表達式解析器的高效算法(Java)

[英]Efficient algorithm for expression parser (Java)

我正在嘗試設計一種可以解析字符串形式的表達式的算法。 我希望能夠從給定的表達式中提取操作數和操作。 另外,我希望算法能夠識別括號平衡。 不需要操作的優先級,因為如果有超過 1 個二進制操作,算法的輸入將包含括號。 對於一元運算,如果括號前出現“-”,則表示相應括號內的整個表達式為操作數。 例子:

-parsing "a+b" gives "a" and "b" as operands and "+" as operation.
-parsing "(a/b) - (c*v)" gives "a/b" and "c*v" as operands and "-" as operation.
-parsing "((a/(b))) - (((c)*v))" gives the same result as above
-parsing "-a" gives operand as "a" and operation as "-"
-parsing "a + (-c/v)" gives "a" and "-c/v" as operands and "+" as operation
-parsing "-(c)" gives "c" is operand and "-" as operands
-parsing "(-(c))" gives same result as above

謝謝

嘗試這個。

record Node(String name, Node left, Node right) {
    @Override
    public String toString() {
        return "Node[" + name
            + (left != null ? ", " + left : "")
            + (right != null ? ", " + right : "") + "]";
    }
}

static Node parse(String input) {
    return new Object() {
        int index = 0;

        int ch() { return index < input.length() ? input.charAt(index) : -1; }

        boolean eat(char expected) {
            while (Character.isWhitespace(ch())) ++index;
            if (ch() == expected) {
                ++index;
                return true;
            }
            return false;
        }

        Node factor() {
            Node node;
            boolean minus = eat('-');
            if (eat('(')) {
                node = expression();
                if (!eat(')'))
                    throw new RuntimeException("')' expected");
            } else if (Character.isAlphabetic(ch())) {
                node = new Node(Character.toString(ch()), null, null);
                ++index;
            } else
                throw new RuntimeException("unknown char '" + (char)ch() + "'");
            if (minus) node = new Node("-", node, null);
            return node;
        }

        Node expression() {
            Node node = factor();
            while (true)
                if (eat('*')) node = new Node("*", node, factor());
                else if (eat('/')) node = new Node("/", node, factor());
                else if (eat('+')) node = new Node("+", node, factor());
                else if (eat('-')) node = new Node("-", node, factor());
                else break;
            return node;
        }
    }.expression();
}

測試:

static void testParse(String input) {
    System.out.printf("%-22s -> %s%n", input, parse(input));
}

public static void main(String[] args) {
    testParse("a+b");
    testParse("(a/b) - (c*v)");
    testParse("((a/(b))) - (((c)*v))");
    testParse("-a");
    testParse("-a + (-c/v)");
    testParse("-(c)");
    testParse("(-(c))");
}

output:

a+b                    -> Node[+, Node[a], Node[b]]
(a/b) - (c*v)          -> Node[-, Node[/, Node[a], Node[b]], Node[*, Node[c], Node[v]]]
((a/(b))) - (((c)*v))  -> Node[-, Node[/, Node[a], Node[b]], Node[*, Node[c], Node[v]]]
-a                     -> Node[-, Node[a]]
-a + (-c/v)            -> Node[+, Node[-, Node[a]], Node[/, Node[-, Node[c]], Node[v]]]
-(c)                   -> Node[-, Node[c]]
(-(c))                 -> Node[-, Node[c]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM