如何解析以字符串形式给出的数学表达式并返回一个数字? [英] How to parse a mathematical expression given as a string and return a number?
问题描述
Java 中有没有办法从这个数学表达式中得到结果:
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?
推荐答案
您可以将其传递给 BeanShellbsh.Interpreter
,类似这样:
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.
如果您想采用更复杂(但更安全)的方法,您可以使用 ANTLR(我怀疑以数学语法为起点)并实际编译/解释语句.
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屋!