是的,这可以通过正则表达式来完成。请记住,Java的正则表达式与SQL的“like”具有不同的语法。而不是“”,你会有“”,而不是“”,你会有“”。%
.*
?
.
让它有点棘手的是,你还必须转义Java视为特殊字符的任何字符。由于您试图将其与SQL相似,因此我猜这不应该出现在正则表达式字符串中。但是,在执行任何其他替换之前,您必须将“”替换为“”。(编辑:Pattern.quote(String)
通过用“”和“”将字符串括起来来转义所有内容,这将导致表达式中的所有内容都被视为文本(根本没有通配符)。所以你绝对不想使用它。^$[]{}\
.
\\.
\Q
\E
此外,正如戴夫·韦伯(Dave Webb)所说,你还需要忽略案例。
考虑到这一点,以下是它可能看起来像什么的示例:
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);
}