如何在java中的unicode Basic Multilingual Plane外部匹配字符(有意删除它们)?
答案 0 :(得分:20)
要删除所有非BMP字符,以下内容应该有效:
String sanitizedString = inputString.replaceAll("[^\u0000-\uFFFF]", "");
答案 1 :(得分:4)
您是否在寻找BMP以外的特定字符或所有字符?
如果是前者,您可以使用StringBuilder
构建一个包含更高层的代码点的字符串,并且正则表达式将按预期工作:
String test = new StringBuilder().append("test").appendCodePoint(0x10300).append("test").toString();
Pattern regex = Pattern.compile(new StringBuilder().appendCodePoint(0x10300).toString());
Matcher matcher = regex.matcher(test);
matcher.find();
System.out.println(matcher.start());
如果您要从字符串中删除所有非BMP字符,那么我会直接使用StringBuilder
而不是正则表达式:
StringBuilder sb = new StringBuilder(test.length());
for (int ii = 0 ; ii < test.length() ; )
{
int codePoint = test.codePointAt(ii);
if (codePoint > 0xFFFF)
{
ii += Character.charCount(codePoint);
}
else
{
sb.appendCodePoint(codePoint);
ii++;
}
}