我想从Java中的String中检测并删除高级ASCII字符,如®,©,™.有没有可以做到这一点的开源库?
axt*_*avt 31
如果您需要删除所有非US-ASCII(即外部0x0-0x7F)字符,您可以执行以下操作:
s = s.replaceAll("[^\\x00-\\x7f]", "");
Run Code Online (Sandbox Code Playgroud)
如果需要过滤许多字符串,最好使用预编译模式:
private static final Pattern nonASCII = Pattern.compile("[^\\x00-\\x7f]");
...
s = nonASCII.matcher(s).replaceAll();
Run Code Online (Sandbox Code Playgroud)
如果它真的对性能至关重要,也许Alex Nikolaenkov的建议会更好.
Ale*_*kov 16
我认为您可以轻松地手动过滤字符串并检查特定字符的代码.如果它符合您的要求,则将其添加到a StringBuilder并toString()最终完成.
public static String filter(String str) {
StringBuilder filtered = new StringBuilder(str.length());
for (int i = 0; i < str.length(); i++) {
char current = str.charAt(i);
if (current >= 0x20 && current <= 0x7e) {
filtered.append(current);
}
}
return filtered.toString();
}
Run Code Online (Sandbox Code Playgroud)
一个很好的方法是使用Google Guava CharMatcher:
String newString = CharMatcher.ASCII.retainFrom(string);
Run Code Online (Sandbox Code Playgroud)
newString 将仅包含原始字符串中的ASCII字符(代码点<128).
这比正则表达式更自然地读取.正则表达式可以花费更多精力来理解代码的后续读者.
我知道您需要删除: \xc3\xa7,\xc3\xa3,\xc3\x83 ,但对于需要转换 \xc3\xa7,\xc3\xa3,\xc3\x83 ---> c, a,A 请看一下这段代码:
\n\n示例代码:
\n\nfinal String input = "T\xc4\xa5\xc3\xaf\xc5\x9d \xc4\xa9\xc5\xa1 \xc3\xa2 f\xc5\xaf\xc5\x88\xc4\xb7\xc5\xb7 \xc5\xa0\xc5\xa5\xc5\x95\xc4\xad\xc5\x84\xc4\xa1";\nSystem.out.println(\n Normalizer\n .normalize(input, Normalizer.Form.NFD)\n .replaceAll("[^\\\\p{ASCII}]", "")\n);\nRun Code Online (Sandbox Code Playgroud)\n\n输出:
\n\n这是一个时髦的字符串
\n| 归档时间: |
|
| 查看次数: |
30710 次 |
| 最近记录: |