是否有可能以评估字符串comparions一个布尔前pression? [英] Is it possible to evaluate a boolean expression for String comparions?

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

问题描述

我会像

('abc' != 'xyz' AND 'thy' = 'thy') OR ('ujy' = 'ujy')

该字符串可以,因为它希望有尽可能多的AND组。这里会不会是和组内的任何嵌套组。所有组将始终由或者serparated。

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.

我就可以切换出和&放大器;&安培; 和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.

时那里有什么可以做这件事?

Is there anything out there that can do this?

推荐答案

您可以使用内置的Javascript引擎与JDK1.6来评估包含数学EX pressions字符串。

You can use the built-in Javascript engine coming with the JDK1.6 to evaluate string containing math expressions.

您一个给查找在这里:的ScriptEngine

You an give a lookup here: 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' with '&&',
'OR' with '||',
'=' must be '=='

,否则它不会接受你的前pression并会抛出一个 javax.script.ScriptException

Otherwise it will not accept your expression and will throws a javax.script.ScriptException

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

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