I need a comparator in java which has the same semantics as the sql \'like\' operator. For example:
myComparator.like(\"digital\",\"%ital%\");
myComparator.l
.* will match any characters in regular expressions
I think the java syntax would be
"digital".matches(".*ital.*");
And for the single character match just use a single dot.
"digital".matches(".*gi.a.*");
And to match an actual dot, escape it as slash dot
\.
Regular expressions are the most versatile. However, some LIKE functions can be formed without regular expressions. e.g.
String text = "digital";
text.startsWith("dig"); // like "dig%"
text.endsWith("tal"); // like "%tal"
text.contains("gita"); // like "%gita%"
public static boolean like(String toBeCompare, String by){
if(by != null){
if(toBeCompare != null){
if(by.startsWith("%") && by.endsWith("%")){
int index = toBeCompare.toLowerCase().indexOf(by.replace("%", "").toLowerCase());
if(index < 0){
return false;
} else {
return true;
}
} else if(by.startsWith("%")){
return toBeCompare.endsWith(by.replace("%", ""));
} else if(by.endsWith("%")){
return toBeCompare.startsWith(by.replace("%", ""));
} else {
return toBeCompare.equals(by.replace("%", ""));
}
} else {
return false;
}
} else {
return false;
}
}
may be help you