4

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.

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
Access
  • 241
  • 1
  • 2
  • 10

2 Answers2

4

If you're using Spring you can use the SpEL, which supports the same boolean expression like this and:

  • it's typically way faster (in my rough tests, it's 20-22 times faster) than the JS engine;
  • the parser instance is thread safe;
  • it's simple to use, just like the JS engine;
  • it's far less resources intensive than the JS engine (in production, the CPU usage jumped from 5% to 60% with the JS engine. It remained the same with SpEL).

Example of usage:

ExpressionParser ep = new SpelExpressionParser();
Expression exp = ep.parseExpression("(!(true||false)&&!((true) != (true)))");
exp.getValue(Boolean.class);

The XOR operator (^) for booleans works exactly like the Not Equal operator (!=), so you can map it to that.

Clashsoft
  • 11,553
  • 5
  • 40
  • 79
reallynice
  • 1,289
  • 2
  • 21
  • 41
1

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.

Access
  • 241
  • 1
  • 2
  • 10