udaikp
udaikp

Reputation: 33

How to convert a string to boolean expression

I have a string like ((TRUE && TRUE) || (TRUE && FALSE)) which I want to convert to boolean. How can I achieve this?

I tried using Boolean.parseBoolean(String) and Boolean.valueOf(String) but I think it works only if the string is as expected like 'True' only

Upvotes: 1

Views: 3039

Answers (2)

Joop Eggen
Joop Eggen

Reputation: 109547

You can "abuse" the similarity with JavaScript and use a standard available scripting engine:

    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine engine = mgr.getEngineByName("JavaScript"); 
    String expr = "((TRUE && TRUE) || (TRUE && FALSE))".toLowerCase();
    boolean result = Boolean.valueOf(engine.eval(expr));

Not sure whether lowercase and valueOf is right. Maybe a (Boolean) case will do.

Upvotes: 3

Roberto Attias
Roberto Attias

Reputation: 1903

you need to build an expression parser. First of all, you need to decide on what the syntax of what your allowed epressions are. From your syntax above it looks like C. You should be able to find abundant examples of parser for C expressions by just Googling. Of course, you can also decide to write one by hand. when parsing a language you can chose to use a generator such as ANTLR or the more traditional LEX + YACC, in which case you will provide a grammar-based description of your language and code generators will spit out the program that parses such language. You will then incorporate such generated code in your program. For well known languages such as C and JAVA those solutions already have pre-cooked grammars, although you might have to extract just the expression part of it.

If the expression is in a traditionally interpreted language such as Python or Javascript, you can opt to incorporate an interpreter in your java program and feed it the expression instead.

Finally, if your expressions are in Java syntax and you're flexible to use an early version of Java 9, you may be able to tap into the new Java Shell feature.

Upvotes: 1

Related Questions