gpt4 book ai didi

java - 验证表达式

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:51:36 24 4
gpt4 key购买 nike

给定一个包含运算符、函数和操作数的表达式,例如:

2 + sin ( max ( 2, 3 ) / 3 * 3.1415 )

如何以编程方式验证表达式,以便任何函数都必须具有正确数量的参数?例如 abs、sin、cos 必须恰好有 1 个参数,而 sum、avg、max、min 有 2 个或更多。

鉴于每个参数本身可以是一个非常复杂的表达式,以编程方式确定它似乎并不简单。我已经编写了一个词法分词器 (lexer),并且已经设法将表达式转换为后缀/RPN。 (即:2 3 max 3/3.1415 * sin 2 +)。我离解决方案还差得很远。

我希望能有一些代码或伪代码指导我从头开始编写一些东西。 Java 会很棒。

下面是我的词法分析器代码:

    public static List<Token> shunt(List<Token> tokens) throws Exception {
List<Token> rpn = new ArrayList<Token>();
Iterator<Token> it = tokens.iterator();
Stack<Token> stack = new Stack<Token>();
while (it.hasNext()) {
Token token = it.next();
if (Type.NUMBER.equals(token.type))
rpn.add(token);
if (Type.FUNCTION.equals(token.type) || Type.LPAREN.equals(token.type))
stack.push(token);
if (Type.COMMA.equals(token.type)) {
while (!stack.isEmpty() && !Type.LPAREN.equals(stack.peek().type))
rpn.add(stack.pop());
if (stack.isEmpty())
throw new Exception("Missing left parenthesis!");
}
if (Type.OPERATOR.equals(token.type)) {
while (!stack.isEmpty() && Type.OPERATOR.equals(stack.peek().type))
rpn.add(stack.pop());
stack.add(token);
}
if (Type.RPAREN.equals(token.type)) {
while (!stack.isEmpty() && !Type.LPAREN.equals(stack.peek().type))
rpn.add(stack.pop());
if (stack.isEmpty())
throw new Exception("Missing left parenthesis!");
stack.pop();
if (!stack.isEmpty() && Type.FUNCTION.equals(stack.peek().type))
rpn.add(stack.pop());
}
}
while (!stack.isEmpty()) {
if (Type.LPAREN.equals(stack.peek().type) || Type.RPAREN.equals(stack.peek().type))
throw new Exception("Mismatched parenthesis!");
rpn.add(stack.pop());
}

return rpn;
}

最佳答案

你想要做的是实现一个精确的解析器,它知道你的语言的确切语法(包括“一个函数有多少个运算符”)。

为表达式编写这样的解析器很容易。参见 https://stackoverflow.com/a/2336769/120163

关于java - 验证表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41476847/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com