Skip to content
Advertisement

Nested Boolean Expression Parser using ANTLR

I’m trying to parse a Nested Boolean Expression and get the individual conditions within the expression separately. For e.g., if the input string is:

(A = a OR B = b OR C = c AND ((D = d AND E = e) OR (F = f AND G = g)))

I would like to get the conditions with the correct order. i.e.,

D =d AND E = e OR F = f AND G = g AND A = a OR B = b OR C = c

I’m using ANTLR 4 to parse the input text and here’s my grammar:

JavaScript

And here’s the Java Code that I’m using to parse it:

JavaScript

The output is:

JavaScript

I’m looking for help on how to parse this tree to get the conditions in the correct order? In ANTLR 3, we could specify ^ and ! to decide how the tree is built(refer this thread), but I learnt that this is not supported in ANTLR 4.

Can someone suggest how I can parse the String in the correct order in Java using the ParseTree created by ANTLR?

Advertisement

Answer

I’d just wrap all the expressions into a single expression rule. Be sure to define the comparator expressions alternative before your binary expression alternative to make sure comparator operators bind more tightly than OR and AND:

JavaScript

To test the grammar above, use the following quick-and-dirty test classes:

JavaScript

Running the Main class will result in the following output:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement