是否可以评估字符串比较的布尔表达式?

2022-01-19 00:00:00 string boolean java

我会有一个类似的字符串

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

相关文章