2016-07-06 102 views
1

我正在用Java開發一個系統來檢查文本中關鍵字組合的出現。例如,我有以下表達式來檢查:(yellow || red) && sofa。 我把這項工作分爲兩個步驟。第一個是檢測文本中的單詞。 第二個是使用結果來檢查布爾表達式。 經過簡短的網頁搜索之後,我選擇了Apache JEXL。Java 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"; 

我該如何解決?我的方式是否正確?

對不起,我的英語不好:)

回答

0

嘗試一些其他的角色就像下劃線來代替空格(_)。

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); 
    } 

}