我有一个程序可以从 twitter 流 api 实时解析推文。在存储它们之前,我将它们编码为 utf8。某些字符最终会以 ?、?? 或 ??? 的形式出现在字符串中。而不是它们各自的 unicode 代码并导致问题。经过进一步调查,我发现有问题的字符来自“表情符号”块U+1F600 - U+1F64F 和“杂项符号和象形文字”块U+1F300 - U+1F5FF。我尝试删除,但没有成功,因为匹配器最终替换了字符串中的几乎每个字符,而不仅仅是我想要的 unicode 范围。
String utf8tweet = "";
try {
byte[] utf8Bytes = status.getText().getBytes("UTF-8");
utf8tweet = new String(utf8Bytes, "UTF-8");
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Pattern unicodeOutliers = Pattern.compile("[\\u1f300-\\u1f64f]", Pattern.UNICODE_CASE | Pattern.CANON_EQ | Pattern.CASE_INSENSITIVE);
Matcher unicodeOutlierMatcher = unicodeOutliers.matcher(utf8tweet);
utf8tweet = unicodeOutlierMatcher.replaceAll(" ");
我该怎么做才能删除这些字符?
在正则表达式模式中添加否定运算符
^
。对于过滤可打印字符,您可以使用以下表达式[^\\x00-\\x7F]
,您应该得到所需的结果。import java.io.UnsupportedEncodingException; import java.util.regex.Matcher; import java.util.regex.Pattern; public class UTF8 { public static void main(String[] args) { String utf8tweet = ""; try { byte[] utf8Bytes = "#Hello twitter How are you?".getBytes("UTF-8"); utf8tweet = new String(utf8Bytes, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } Pattern unicodeOutliers = Pattern.compile("[^\\x00-\\x7F]", Pattern.UNICODE_CASE | Pattern.CANON_EQ | Pattern.CASE_INSENSITIVE); Matcher unicodeOutlierMatcher = unicodeOutliers.matcher(utf8tweet); System.out.println("Before: " + utf8tweet); utf8tweet = unicodeOutlierMatcher.replaceAll(" "); System.out.println("After: " + utf8tweet); } }
结果如下:
编辑
为了进一步解释,您也可以继续用
\u
以下方式表达范围[^\\u0000-\\u007F]
,它将匹配所有不是前 128 个 UNICODE 字符的字符(与之前相同)。如果您想扩展范围以支持额外的字符,您可以使用此处的 UNICODE 字符列表来实现。例如,如果您想包含带重音的元音(在西班牙语中使用),您应该将范围扩展到
\u00FF
,因此您有[^\\u0000-\\u00FF]
或[^\\x00-\\xFF]
: