核心代碼
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 判斷字串是否包含中文字符(漢字)
* @param str 待檢測字串
* @return true 包含中文,false 不包含
*/
public static boolean containsChinese(String str) {
if (str == null || str.isEmpty()) {
return false;
}
// Unicode 範圍:\u4e00-\u9fa5 涵蓋常用漢字
String regex = "[\u4e00-\u9fa5]";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
return matcher.find();
}
關鍵點解析
- 正則範圍:
\u4e00-\u9fa5 覆蓋基本區漢字 20,902 個,滿足絕大多數業務場景。若需包含擴展區,可擴展為 [\u4e00-\u9fff\u3400-\u4dbf]。
- 效能優化:
Pattern 編譯耗時,建議靜態常量複用;matcher.find() 比 matches() 更快(後者需全串匹配)。
- 邊界處理:空值、空串直接返回 false,避免 NPE。
擴展:統計中文字符數量
public static int countChineseChars(String str) {
if (str == null) return 0;
Matcher matcher = Pattern.compile("[\u4e00-\u9fa5]").matcher(str);
int count = 0;
while (matcher.find()) count++;
return count;
}
應用場景
- 表單驗證:姓名、地址必填中文。
- 內容審核:檢測用戶輸入是否混雜中文繞過敏感詞過濾。
- 數據清洗:區分中英混排字段,分流處理。