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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With