是否可以评估字符串比较的布尔表达式? [英] Is it possible to evaluate a boolean expression for String comparions?

查看:23
本文介绍了是否可以评估字符串比较的布尔表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我会有一个类似的字符串

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

这篇关于是否可以评估字符串比较的布尔表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆