Search code examples
javaparsingbooleanboolean-expression

How to convert boolean expression strings to objects?


How could I best evaluate user-given boolean expression strings like:

A & B | (C & !D)

What do I need this for? Example: Imagine we have a set of people, and the user has an input field where he can connect two (and more) of these peoples with boolean expressions written as String like:

Peter & Klaus | (Peter & Clair | !Klaus)

(I know this expression does not make any sence, just as an example).

I then want to split this boolean string somehow using boolean grammer. Later, if a person is renamed (eg. Peter -> John), I want the expression the user gave to also be auto-renamed with the new names. So that the user sees an update on his saved expression with the new names.

Therefore I probably have to store the boolean expression using the id's representing the objects behind the names. Therefore having to look up each name from the expression in the db, therefore having to split the string by boolean grammer.

Questions:

  • How could I best split this string?

  • How could I store this expression using object values, so that this string can be revaluated when names change?


Solution

  • One solution would be to parse the information into a tree of Nodes where a Node can store either Name, an operator or an expression. You can use an id on each node to allow you to replace the Name or whatever later.

    To do the parsing itself, the basics are pretty straight forward. it all depends on how complex these expressions are/can become. To do a proper and complete grammer of boolean expressions, I would recommend a parser tool like antlr.