我有一些功能需要确定用户创建的规则在语法上是否有效.
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:
- 1 == 1
- 1 +1 == 1
- 1 +1 == 1或1 == 1
- 以上示例的更多组合
这些表达式保存在字符串变量中,例如:
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有效表达
有效表达式是具有逻辑运算符(<,< =,==,=>,>)的表达式,并且输出将为true或false(无关紧要)
Valid expressions are the ones that have a logic operator (<, <=, ==, =>, >) and the output would be true or false (doesn't matter which)
- 1 == 1
- 1< 2
- 1 == 1或1< 4
- 4 == 9或9 == 3
无效的表达
无效的表达式是没有正确结构才能确定该表达式为true或false的表达式.
Invalid expressions are the ones that doesn't have the proper structure in order to determine whether that expression is true or false.
- 1
- 1 + 1
- 1 ===
- == 1
- 1
- 11(即数字然后为数字)
注意
我尝试使用
Boolean.valueOf(String)
Boolean.valueOf(String)
Boolean.parse(String)
Boolean.parse(String)
其他类型的布尔方法
推荐答案
EDIT 现在将不允许任何表达式成功.
EDIT Will now not allow any expression to be success.
EDIT2 评估示例.
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"); } } }docs.oracle/javase/7/docs/api/javax/script/ScriptEngine.html
docs.oracle/javase/7/docs/api/javax/script/ScriptEngineManager.html
更多推荐
Java:构建逻辑表达式,然后对其进行验证
发布评论