1

I am trying to validate a string which can contain some conditions and logical operators. For example, My input expression could be something like this:

(var1==var2 AND var2==var4) OR (someothervar!=5) AND (somemorevar=<4 OR var5<10)

Later, I would be converting this string to a java readable expression,

(var1==var2 && var2==var4) || (someothervar!=5) && (somemorevar=<4 || var5<10)

The input string is captured at runtime, and it can be anything. My concern is to validate the input string to be a valid expression, so later only AND and OR could be replaced with && and || to evaluate.

Pramod
  • 93
  • 1
  • 5
  • I have found this [Calling scripts from Java](http://www.beanshell.org/examples/callscript.html). If you go to the home page it seems to be a lib to parse java code and evulate it at runtime. Try searching for `java evaluate at runtime` on google you could find better. – Lynch Jul 05 '11 at 05:15
  • Also there is an other thread with a similar question here: [convert-string-to-code-in-java](http://stackoverflow.com/questions/935175/convert-string-to-code-in-java). – Lynch Jul 05 '11 at 05:17

4 Answers4

0

It looks like you want to build an syntactic tree. Take a look at JavaCC ant ANTLR

Maurice Perry
  • 32,610
  • 9
  • 70
  • 97
0

Why are you allowing "AND" and "OR", if you need to already validate the input and you are still going to replace the words "AND" and "OR" anyways? Just simply require || and && as part of the validation of the input and skip the step of allowing "AND" and "OR".

A thought on validation would be to perform a regular expression on the input string. I am not very savvy at Regex, but my guess is there would be someone out there that could get you a Regex that would make sure the open parenthesis match the ending and that there are at least two "=" signs, etc. Just some thoughts.

cabanaboy
  • 71
  • 4
  • The input is bound to come in AND/OR forms itself. I can not alter it due to some restrictions. – Pramod Jul 05 '11 at 05:23
0

It sounds like you are building a rules engine/parser and passing in rules in a more human-readable format?

If that is the case, you should look at existing rules engines like Drools. The rules syntax is in an easily readable format, and the rules engine is very powerful you way do so much more with it if your rules get more complex.

Moe Matar
  • 2,026
  • 13
  • 7
0

Try out JEP.

Emil
  • 13,577
  • 18
  • 69
  • 108