首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 程式設計入門

Java 正則表達式實戰:中文提取與字符分類

     編輯:Java 程式設計入門

正則表達式是文本處理利器。本文通過兩個實戰案例,演示如何提取中文字符、按字符類型分類(數字、字母、中文、特殊符號),並提供完整可運行代碼。

案例一:提取字符串中的所有中文字符

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_IDEOGRAPHS
  • 大量文本處理時,預編譯 Pattern 復用,避免重複編譯開銷
  • 正則雖強,但複雜邏輯下可讀性下降,適時拆分為代碼邏輯更清晰
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved