正則表達式是文本處理利器。本文通過兩個實戰案例,演示如何提取中文字符、按字符類型分類(數字、字母、中文、特殊符號),並提供完整可運行代碼。
String str = "n1e你v00a?Az$Z000?#99?9900瞇2_悄s3你y4@好?!6求救你d75a8t";
Pattern p = Pattern.compile("[\\u4e00-\\u9fa5]"); // 中文 Unicode 範圍
Matcher m = p.matcher(str);
while (m.find()) {
System.out.print(m.group());
}
// 輸出:你瞇悄你好求救你
通過字符編碼範圍判斷類型:
String str = "n1e你v00a?Az$Z000?#99?9900瞇2_悄s3你y4@好?!6求救你d75a8t";
String num = "", letter = "", chinese = "", other = "";
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c >= '0' && c <= '9') {
num += c;
} else if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) {
letter += c;
} else if (String.valueOf(c).getBytes().length > 1) { // 簡易判斷中文(雙字節)
chinese += c;
} else {
other += c;
}
}
System.out.println("數字:" + num);
System.out.println("字母:" + letter);
System.out.println("中文:" + chinese);
System.out.println("其他:" + other);
| 任務 | 關鍵代碼 | 說明 |
|---|---|---|
| 匹配中文 | [\\u4e00-\\u9fa5] | 基本多文種平面中文範圍 |
| 匹配數字 | \\d 或 [0-9] | |
| 匹配字母 | [a-zA-Z] | |
| 匹配非字母數字 | [^a-zA-Z0-9] | 含標點、空格、中文等 |
| 獲取匹配文本 | matcher.group() | 返回當前匹配子串 |
Character.UnicodeBlock.of(c) == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHSPattern 復用,避免重複編譯開銷