我正在使用以下代碼讀取文本文件,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
提交
取消