Reputation: 1269
I have a little functionality where I need to determine whether a rule that a user is creating is syntactically valid.
That being said the structure of what I'm building are like the following:
These expressions are saved in a string variable, e.g:
String expression = "";
while(items.hasNext())
{
String currentItem = items.next();
expression += currentItem.value();
}
//Check if the expression is valid
VALID EXPRESSIONS
Valid expressions are the ones that have a logic operator (<, <=, ==, =>, >) and the output would be true or false (doesn't matter which)
INVALID EXPRESSIONS
Invalid expressions are the ones that doesn't have the proper structure in order to determine whether that expression is true or false.
NOTE
I've tried using
Boolean.valueOf(String)
Boolean.parse(String)
Other types of Boolean methods
Upvotes: 4
Views: 1880
Reputation: 456
EDIT Will now not allow any expression to be success.
EDIT2 Examples of what evaluates.
import javax.script.ScriptEngineManager;
import javax.script.*;
public class HelloWorld{
public static void main(String[] args)
{
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
String expression = "1+2"; // evaluates to Failure: 3
String expression = "1+a"; // evaluates to Failure:
String expression = "1==1"; // evaluates to Success: true
String expression = "1==2"; // evaluates to Failure: false
try
{
Object result = engine.eval(expression);
if(result instanceof Boolean)
{
System.out.print("Success: ");
System.out.println(result);
}
else
{
System.out.print("Failure: ");
System.out.println(result);
}
}
catch(ScriptException e)
{
// handle
System.out.println("Failure");
}
}
}
https://docs.oracle.com/javase/7/docs/api/javax/script/ScriptEngine.html
https://docs.oracle.com/javase/7/docs/api/javax/script/ScriptEngineManager.html
Upvotes: 4