2

我正在用 Java 开发一个系统来检查文本中关键字组合的出现。例如,我有以下表达式要检查:( yellow || red ) && sofa. 我把工作分为两个步骤。第一个是检测文本中的单个单词。第二种是使用结果来检查布尔表达式。经过简短的网络搜索后,我选择了 Apache JEXL。

// My web app contains a set of preconfigured keywords inserted by administrator: 
List<String> system_occurence =new ArrayList<String>() {{
    add("yellow");
    add("brown");
    add("red");
    add("kitchen");
    add("sofa");        
}}; 


// The method below check if some of system keywords are in the text
List<String> occurence = getOccurenceKeywordsInTheText();
for ( String word :occurrence){
    jexlContext.set(word,true);
}

// Set to false system keywords not in the text
system_occurence.removeAll(occurence);
for ( String word :system_occurence){
    jexlContext.set(word,false);
}


// Value the boolean expression
String jexlExp ="( yellow || red ) && sofa"; 
JexlExpression e = jexl.createExpression( jexlExp_ws_keyword_matching );

Boolean o = (Boolean) e.evaluate(jexlContext);

在上面的例子中,我在布尔表达式中使用了简单的词。使用 ASCII 和非复合词我没有问题。我在布尔表达式中遇到了非 ASCII 和复合关键字的问题,因为我不能将它们用作变量名称。

// The below example fails, JEXL launch Exception
String jexlExp ="( Lebron James || red ) && sofa"; 

// The below example fails, JEXL launch Exception
String jexlExp ="( òsdà || red ) && sofa";

我该如何解决?我的方式对吗?

对不起,我的英语不好 :)

4

1 回答 1

1

尝试用下划线 (_) 等其他字符替换空格。

package jexl;



   import org.apache.commons.jexl3.*;

    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;

    public class Test2 {

    private static final JexlEngine JEXL_ENGINE = new JexlBuilder().cache(512).strict(false).silent(false).create();
    public static void main(String[] args) {
        // My web app contains a set of preconfigured keywords inserted by administrator:
        List<String> system_occurence =new ArrayList<String>() {{
            add("yellow");
            add("brown");
            add("red");
            add("kitchen");
            add("sofa");
        }};

        JexlContext jexlContext = new MapContext();

// The method below check if some of system keywords are in the text
        List<String> occurence = Arrays.asList("kitchen");
        for ( String word :occurence){
            jexlContext.set(word,true);
        }

// Set to false system keywords not in the text
        system_occurence.removeAll(occurence);
        for ( String word :system_occurence){
            jexlContext.set(word,false);
        }


// Value the boolean expression
        String jexlExp ="( Lebron_James || red ) && sofa";
        JexlExpression e = JEXL_ENGINE.createExpression( jexlExp );

        Boolean o = (Boolean) e.evaluate(jexlContext);

        System.out.println(o);
    }

}
于 2017-04-01T09:10:41.017 回答