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')
字符串将能够拥有任意数量的AND"组.AND 组中不会有任何嵌套组.所有组将始终由 OR 分隔.
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.
我可以把 &&
的 AND 和 ||
的 OR 换掉.
I can just switch out the AND for &&
and OR for ||
.
我想要的是将此字符串传递给某种类型的 eval 方法并输出 TRUE 或 FALSE.
What I would like is to pass this String into some type of eval method and output TRUE or FALSE.
有什么可以做到的吗?
推荐答案
你可以使用JDK1.6自带的内置Javascript引擎来计算包含数学表达式的字符串.
You can use the built-in Javascript engine coming with the JDK1.6 to evaluate string containing math expressions.
您可以在这里查找:ScriptEngine
这里是一个例子:
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' 与 '&&',
'OR' 与 '||',
'=' 必须是 '=='
'AND' with '&&',
'OR' with '||',
'=' must be '=='
否则它将不接受您的表达式并抛出 javax.script.ScriptException
Otherwise it will not accept your expression and will throws a javax.script.ScriptException
这篇关于是否可以评估字符串比较的布尔表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否可以评估字符串比较的布尔表达式?


基础教程推荐
- 验证是否调用了所有 getter 方法 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- Java Swing计时器未清除 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01