我正在使用以下代码读取文本文件,try (BufferedReader br = new BufferedReader(new FileReader(<file.txt>))) { for (String line; (line = br.readLine()) != null;) { //I want to skip a line with unicode character and continue next line if(line.toLowerCase().startsWith("\\u")){ continue; //This is not working because i get the character itself and not the text } }}文本文件:如何在读取文件时跳过所有 unicode 字符?
3 回答

炎炎设计
TA贡献1808条经验 获得超4个赞
String 中的所有字符都是 Unicode。字符串是 UTF-16 代码单元的计数序列。通过“Unicode”,您必须表示不在某些未指定的其他字符集中。为了争论,让我们说ASCII。
正则表达式有时可以是模式要求的最简单表达式:
if (!line.matches("\\p{ASCII}*")) continue;
也就是说,如果该字符串不只包含任何数字,包括 0,(就是这个意思*
)“ASCII”字符,则继续。
(String.matches
查找整个字符串的匹配项,因此实际的正则表达式模式是^\p{ASCII}*$
。)

慕姐4208626
TA贡献1852条经验 获得超7个赞
这样的事情可能会让你继续:
for (char c : line.toCharArray()) {
if (Character.UnicodeBlock.of(c) == Character.UnicodeBlock.BASIC_LATIN) {
// do something with this character
}
}
您可以以此为起点来丢弃每个非基本字符,或者丢弃包含单个非基本字符的整行。

冉冉说
TA贡献1877条经验 获得超1个赞
您可以跳过所有包含非 ASCII 字符的行:
if(Charset.forName("US-ASCII").newEncoder().canEncode(line)){ continue; }
添加回答
举报
0/150
提交
取消