Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to evaluate a boolean expression for String comparions?

I will have a String like

('abc' != 'xyz' AND 'thy' = 'thy') OR ('ujy' = 'ujy')

The String will be able to have as many "AND" groups as it wants. There will not be any nested groups within the AND groups. All groups will ALWAYS be serparated by an OR.

I can just switch out the AND for && and OR for ||.

What I would like is to pass this String into some type of eval method and output TRUE or FALSE.

Is there anything out there that can do this?

like image 739
Envin Avatar asked Oct 15 '13 14:10

Envin


People also ask

What are the rules for evaluating Boolean expressions?

A Boolean expression will be evaluated to either true or false if all of its variables have been substituted with their actual values. For example, a Boolean variable x is a Boolean expression, and it can be evaluated to true or false subject to its actual value.

Can you use == for Boolean in Java?

Typically, you use == and != with primitives such as int and boolean, not with objects like String and Color. With objects, it is most common to use the equals() method to test if two objects represent the same value.

What is the boolean of a String?

There is no formal definition for the expression “Boolean Strings.” Recruiters and Researchers use the term “Boolean Strings” as a shortcut to advanced Google search strings (i.e., using operators) and, sometimes, searches on LinkedIn or other sites that allow a logical combination of terms.

What possible values can a Boolean expression have?

A variable of the primitive data type boolean can have two values: true and false (Boolean literals). or off. Boolean expressions use relational and logical operators. The result of a Boolean expression is either true or false.


1 Answers

You can use the built-in Javascript engine coming with the JDK1.6 to evaluate string containing math expressions.

You an give a lookup here: ScriptEngine

Here an example:

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class Myclass {
    public static void main(String[] args) {

        try {

            ScriptEngineManager sem = new ScriptEngineManager();
            ScriptEngine se = sem.getEngineByName("JavaScript");
            String myExpression = "('abc' == 'xyz' && 'thy' == 'thy') || ('ujy' == 'ujy')";
            System.out.println(se.eval(myExpression));

        } catch (ScriptException e) {

            System.out.println("Invalid Expression");
            e.printStackTrace();

        }
    }
}

Just remember to replace the following:

'AND' with '&&',
'OR' with '||',
'=' must be '=='

Otherwise it will not accept your expression and will throws a javax.script.ScriptException

like image 83
Cirou Avatar answered Sep 21 '22 11:09

Cirou