3

In Java, if I have a string:

String abc = "(5)*(2+2)/(2)";

How could I get the result of abc = 10?

halfer
  • 19,471
  • 17
  • 87
  • 173
olidev
  • 18,940
  • 49
  • 129
  • 194

2 Answers2

8
import javax.script.*;
public class EvalScript {
    public static void main(String[] args) throws Exception {
        // create a script engine manager
        ScriptEngineManager factory = new ScriptEngineManager();
        // create a JavaScript engine
        ScriptEngine engine = factory.getEngineByName("JavaScript");
        // evaluate JavaScript code from String
        Number number = (Number)engine.eval("(5)*(2+2)/(2)");
        System.out.println("abc = " + number);
    }
}
Boris Pavlović
  • 60,971
  • 26
  • 119
  • 144
  • 1
    Shouldn't it be more like `Number number = (Number)engine.eval("(5)*(2+2)/(2)");` instead of using the `print` statement? – Harry Lime May 17 '11 at 08:15
  • Great solution though and by the way this is only available for Java 6.0 onwards. – Harry Lime May 17 '11 at 08:15
  • 1
    This is a bad solution. It's risky with respect to general security. There are many incidents in which use of a wide open eval tool has been used to compromise systems. Malicious hackers see this kind of code and jump for joy. It's wide open to command injection. – John Feb 16 '13 at 00:32
  • Not all software is published in open. For quick prototyping this may be a perfect application. – Boris Pavlović Feb 17 '13 at 19:16
1

It's not straightforward. You should

  • have a grammar for arithmetic expressions
  • build a lexer/parser from the grammar
  • parse your string with the parser, and have the parser perform the semantic actions corresponding to the arithmetic operators of your grammar.

You can find a simple example in ANTLR documentation: section 2.1 Create a simple grammar, has a Java example with a grammar for basic arithmetic expressions.

MarcoS
  • 13,110
  • 6
  • 39
  • 62
  • I agree. Techniques based on any eval mechanism are usually open to injection attacks. Reference: https://www.owasp.org/index.php/Top_10_2010-A1-Injection. An example of a commercial tool built for this job is at formula4j.com. – John Apr 14 '13 at 14:46