1

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?

Matt Busche
  • 14,216
  • 5
  • 36
  • 61
membersound
  • 81,582
  • 193
  • 585
  • 1,120
  • Probably my question title was not right: I do not really want to evalute the expression to `true` or `false`, but want to parse/split/make references according to this boolean expr. – membersound Mar 18 '13 at 10:52
  • Are you looking for a way to "represent" such expressions and the, eventually and only optionally, evaluate the boolean value of it? Conceptually something like building this? http://en.wikipedia.org/wiki/Binary_expression_tree If so, you might want to look at something like ANTLR and similar....that is pretty much their reason for existence: lexical and syntactical parsing... – mdm Mar 18 '13 at 11:00
  • I thing "represent" or "store" is the right word. I want to save this expression and represent it with the objects (person objects) laying behind in the db. Then if any person gets renamed, the expression should be auto-updated. Or moreover: the expression once saved should be displayed using the saved reference of objects, and the do something like `object.getName()` to build the visual representation of the expression. – membersound Mar 18 '13 at 11:03

1 Answers1

1

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.

WPrecht
  • 1,340
  • 1
  • 17
  • 29