我想存储 String
的规范化版本,以便能够对其进行 like 'xxxx%'
搜索。
我正在寻找一款对用户搜索高效且友好的好产品。
我最初的想法是转换为小写,删除非字母字符,重音符号和多余的空格,但不知道是否有一个好的已经研究和实现并准备好。
PD:该字符串将包含位置名称。
最佳答案
最后我以自定义解决方案结束。它可能会更高效,但对我来说表现良好:
public static normalize(String string) {
string = string.toLowerCase();
//Remove/change all special characters --> àaç is converted to aac
String temp = Normalizer.normalize(string, Normalizer.Form.NFD);
string = pattern.matcher(temp).replaceAll("");
//Remove extra spaces
string = StringUtils.normalizeSpace(string);
}
StringUtils.normalizeSpace
来自Commons Lang 。您可以轻松get the code如果您不想引入依赖项,请从函数中调用:
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("(?: \\s|[\\s&&[^ ]])\\s*");
public static String normalizeSpace(final String str) {
if (str == null) {
return null;
}
return WHITESPACE_PATTERN.matcher(trim(str)).replaceAll(SPACE);
}
关于java - 标准化索引/搜索的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14592247/