Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a mathematical expression given as a string and return a number? [duplicate]

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?

like image 628
Martijn Courteaux Avatar asked Sep 16 '09 10:09

Martijn Courteaux


2 Answers

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.

like image 55
Nick Holt Avatar answered Sep 30 '22 08:09

Nick Holt


i recently developed a expression parser and released it under the apache license. you can grab it at http://projects.congrace.de/exp4j/index.html

hope that helped

like image 36
fasseg Avatar answered Sep 30 '22 09:09

fasseg