在正则表达式模式中添加否定运算符
^。为了过滤可打印的字符,您可以使用以下表达式
[^\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 unipreOutliers = Pattern.compile("[^\x00-\x7F]", Pattern.UNICODE_CASE | Pattern.CANON_EQ | Pattern.CASE_INSENSITIVE); Matcher unipreOutlierMatcher = unipreOutliers.matcher(utf8tweet); System.out.println("Before: " + utf8tweet); utf8tweet = unipreOutlierMatcher.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? á é í ó ú



