boolean expression parser in java

javamonkey79 picture javamonkey79 · Aug 30, 2012 · Viewed 29.1k times · Source

Are there any java libraries or techniques to parsing boolean expressions piecemeal?

What I mean is given an expression like this:

T && ( F || ( F && T ) )

It could be broken down into a expression tree to show which token caused the 'F' value, like so (maybe something like this):

T &&               <- rhs false
    ( F ||         <- rhs false
        ( F && T ) <- eval, false
    )

I am trying to communicate boolean expression evaluations to non-programmers. I have poked around with Anlr, but I couldn't get it to do much (it seems to have a bit of a learning curve).

I'm not opposed to writing it myself, but I'd rather not reinvent the wheel.

Answer

Dev picture Dev · Aug 30, 2012

You could do this with MVEL or JUEL. Both are expression language libraries, examples below are using MVEL.

Example:

System.out.println(MVEL.eval("true && ( false || ( false && true ) )"));

Prints: false

If you literally want to use 'T' and 'F' you can do this:

Map<String, Object> context = new java.util.HashMap<String, Object>();
context.put("T", true);
context.put("F", false);
System.out.println(MVEL.eval("T && ( F || ( F && T ) )", context));

Prints: false