0

I have a condition check resulting in a string value of

String example = "( (true and true) or (true and false) );"

I need to convert this string into a boolean value, in this case the result should be true or in another example;

String example = "( (true and true) and (true and false) );" this should return false.

Is there any utility method that I can use to achieve this? Or any other ideas?

Shahe
  • 964
  • 2
  • 13
  • 34
  • 7
    Nope. You need to write a parser from scratch here. – Joe C Nov 26 '18 at 08:44
  • 1
    I don't know of any library that does this, since I doubt anyone to ever have needed this .. – Stultuske Nov 26 '18 at 08:44
  • 1
    that being said you have selected a topic where writing a parser luckily is not that difficult, just 2 to 3 operators, a fixed set of values plus parenthesis. – luk2302 Nov 26 '18 at 08:47
  • Usually you need something more flexible than just evaluating constant boolean expressions, i. e. the input usually contains variables. Existing solutions probably provide more complexity than you need. – Hulk Nov 26 '18 at 08:51
  • 1
    A dirty trick is to use the JavaScript support in the JVM to do that: you just need to replace and and or by && and ||. – JB Nizet Nov 26 '18 at 08:53
  • @JBNizet Thanks buddy! I did it using the JavaScript `ScriptEngine` that you suggested! You can post an answer if you want. – Shahe Nov 26 '18 at 08:58
  • Related: [Execute Java code that is stored in the database](https://stackoverflow.com/questions/26217266/execute-java-code-that-is-stored-in-the-database) – LuCio Nov 26 '18 at 12:30

1 Answers1

1

You could have a look at JEval, though its latest release was a decade ago, and it's a bit sparse in documentation.

Jeroen Steenbeeke
  • 3,884
  • 5
  • 17
  • 26