Parsing Mathematical Expressions as Strings in Java
Given a mathematical expression represented as a string, such as "5 4*(7-15)", is it possible to evaluate and return the numeric result in Java? Additionally, what methods offer the most efficient parsing of arithmetic expressions?
Solution:
One approach to evaluating mathematical expressions as strings is to leverage the BeanShell bsh.Interpreter class. The following code demonstrates this technique:
Interpreter interpreter = new Interpreter(); interpreter.eval("result = 5+4*(7-15)"); System.out.println(interpreter.get("result"));
This approach safeguards against potential security risks by ensuring that the string to be evaluated originates from a reliable source.
Alternatively, a more complex yet secure option is to employ ANTLR (ANother Tool for Language Recognition). ANTLR constitutes a grammar-based parser generator, capable of handling mathematical expressions as a starting point.
The above is the detailed content of How Can Java Efficiently Parse and Evaluate Mathematical Expressions Given as Strings?. For more information, please follow other related articles on the PHP Chinese website!