Reputation: 51
I'm developing in Java a system to check the occurrence of a combination of keywords in a text.
For example, I have the following expression to check: ( yellow || red ) && sofa
.
I divided the job into two steps. The first one is to detect individual words in the text.
The second one is to use the result for checking the boolean expression.
After a short web search I choose 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);
In the above example, I use simple words in the boolean expression. With ASCII and non-composite words I've no problems. I've problems with non-ASCII and composite keywords inside the boolean expression because I can't use those as variables names.
// 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";
How can I solve? Is it right my way?
Sorry for my bad English :)
Upvotes: 2
Views: 2566
Reputation: 424
Try to replace space with some other character like underscore (_).
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);
}
}
Upvotes: 1