如何解析作为字符串给出的数学表达式并返回一个数字? [英] How to parse a mathematical expression given as a string and return a number?

查看:358
本文介绍了如何解析作为字符串给出的数学表达式并返回一个数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆