I need a comparator in java which has the same semantics as the sql \'like\' operator. For example:
myComparator.like(\"digital\",\"%ital%\");
myComparator.l
Yes, this could be done with a regular expression. Keep in mind that Java's regular expressions have different syntax from SQL's "like". Instead of "%", you would have ".*", and instead of "?", you would have ".".
What makes it somewhat tricky is that you would also have to escape any characters that Java treats as special. Since you're trying to make this analogous to SQL, I'm guessing that ^$[]{}\ shouldn't appear in the regex string. But you will have to replace "." with "\\." before doing any other replacements. (Edit: Pattern.quote(String) escapes everything by surrounding the string with "\Q" and "\E", which will cause everything in the expression to be treated as a literal (no wildcards at all). So you definitely don't want to use it.)
Furthermore, as Dave Webb says, you also need to ignore case.
With that in mind, here's a sample of what it might look like:
public static boolean like(String str, String expr) {
expr = expr.toLowerCase(); // ignoring locale for now
expr = expr.replace(".", "\\."); // "\\" is escaped to "\" (thanks, Alan M)
// ... escape any other potentially problematic characters here
expr = expr.replace("?", ".");
expr = expr.replace("%", ".*");
str = str.toLowerCase();
return str.matches(expr);
}