Access Access - 1 year ago 82
Java Question

Parse parenthesized Boolean String Expressions with Java

I need to evaluate a parenthesized boolean expression I receive in a String. Since I need to deal with variable expression i need to find a way to parse it into a boolean expression to evaluate it in java. An example for an String expression is:

String boolexpr1 = "(!(true||false)&&!((true)^(true)))"

The possible operators are parentheses, AND, OR, XOR, NOT. Since this is already a Java-processable expression I thought it should be easy to parse it, but couldn't think of a elegant solution. I also found some code online, but it either deals with other/less operators, without parentheses or is still too complex.

Answer Source

I found a solution using JavaScript:

String boolexpr1 = "(!(true||false)&&!((true)^(true)))"
boolean result = (Boolean) new ScriptEngineManager().getEngineByName("javascript").eval(boolexpr1);

Didn't expect it could be that simple.