从字符串中删除特定unicode范围的字符
我有一个程序可以从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);
}
}
结果如下:
Before: #Hello twitter How are you?After: #Hello twitter How are you?
为了进一步说明,您还可以\u
通过以下方式继续使用范围表示范围,该范围[^\\u0000-\\u007F]
将匹配不是前128个UNICODE字符的所有字符(与以前相同)。如果要扩展范围以支持其他字符,可以使用此处的UNICODE字符列表来实现。
例如,如果要包含带有重音的元音(在西班牙语中使用),则应将范围扩展到\u00FF
,因此您具有[^\\u0000-\\u00FF]
或[^\\x00-\\xFF]
:
Before: #Hello twitter How are you? á é í ó úAfter: #Hello twitter How are you? á é í ó ú
以上是 从字符串中删除特定unicode范围的字符 的全部内容, 来源链接: utcz.com/qa/416027.html