如何解析作为字符串给出的数学表达式并返回一个数字? [英] How to parse a mathematical expression given as a string and return a number?
问题描述
String code =5 + 4 * (7-15);
另一方面,解析算术表达式的最佳方式是什么?
您可以将其传递给 BeanShell bsh.Interpreter
,如下所示:
口译翻译=新翻译();
interpreter.eval(result = 5 + 4 *(7-15));
System.out.println(interpreter.get(result));
您需要确保评估的字符串来自受信任的来源和通常的注意事项,否则它将直接工作。
如果你想要一个更复杂(但更安全)的方法,你可以使用 ANTLR (我怀疑以数学语法为起点),实际上是自己编译/解释这个陈述。
Is there a way in Java to get the result from this mathematical expression:
String code = "5+4*(7-15)";
In other hand what's the best way to parse an arithmetic expression?
You can pass it to a BeanShell bsh.Interpreter
, something like this:
Interpreter interpreter = new Interpreter();
interpreter.eval("result = 5+4*(7-15)");
System.out.println(interpreter.get("result"));
You'll want to ensure the string you evaluate is from a trusted source and the usual precautions but otherwise it'll work straight off.
If you want to go a more complicated (but safer) approach you could use ANTLR (that I suspect has a math grammar as a starting point) and actually compile/interpret the statement yourself.
这篇关于如何解析作为字符串给出的数学表达式并返回一个数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!