正則表達式是 Java 開發中處理字符串匹配、提取與替換的利器。掌握其核心語法與 java.util.regex 套件的應用,能大幅提升文本處理效率。本文將系統梳理 Java 正則的基礎語法、核心 API 及實戰技巧。
.:匹配任意單一字元(除換行符)\d:數字 [0-9];\D:非數字\w:單字字元 [a-zA-Z0-9_];\W:非單字字元\s:空白字元;\S:非空白字元[abc]:匹配 a、b、c 中任一;[^abc]:排除這些字元*:0 次或多次;+:1 次或多次;?:0 次或 1 次{n}:恰好 n 次;{n,}:至少 n 次;{n,m}:n 到 m 次?,如 *?)^ 行首、$ 行尾、\b 單字邊界(...) 捕獲組;(?:...) 非捕獲組;(?<name>...) 命名組(Java 7+)\1、\k<name>// 編譯模式(建議複用 Pattern 實例)
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
// 獲取匹配器
Matcher matcher = pattern.matcher(input);
// 完整匹配
boolean matches = matcher.matches();
// 尋找下一個子序列匹配
while (matcher.find()) {
String group = matcher.group(); // 整個匹配
String group1 = matcher.group(1); // 第 1 組
int start = matcher.start(); // 起始索引
int end = matcher.end(); // 結束索引
}
// 一次性匹配
boolean b = Pattern.matches(regex, input);
// 分割字符串
String[] parts = input.split(regex); // 等同於 Pattern.compile(regex).split(input)
String[] partsLimited = input.split(regex, limit); // 限制分割數量
// 替換
String replaced = matcher.replaceAll(replacement); // 全部替換
String replacedFirst = matcher.replaceFirst(replacement); // 僅首次
// 使用函數式替換
String funcReplaced = matcher.replaceAll(mr -> mr.group().toUpperCase());
將 Pattern 定義為 static final 常數,避免重複編譯開銷。
不需要回溯引用的分組使用 (?:...),減少記憶體佔用。
(a+)+、(a*)*Pattern.DOTALL 時謹慎使用 .*++、*+ 或原子組 (?>...)Pattern p = Pattern.compile("(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})");
Matcher m = p.matcher("2024-05-18");
if (m.matches()) {
System.out.println(m.group("year")); // 2024
}
String mobileRegex = "^1[3-9]\\d{9}$";
boolean valid = Pattern.matches(mobileRegex, "13812345678"); // true
String urlRegex = "\\bhttps?://[\\w.-]+(?:\\.[\\w.-]+)+[\\w/\\-?=%&.#~]*";
Matcher m = Pattern.compile(urlRegex).matcher(text);
while (m.find()) System.out.println(m.group());
String clean = html.replaceAll("<[^>]+>", ""); // 簡易版,複雜場景建議用 Jsoup
(?=...)正向前瞻、(?!...)負向前瞻、(?<=...)正向後顧、(?<!...)負向後顧(?(1)yes|no) 根據組 1 是否匹配選擇模式(?i)啟用不區分大小寫、(?m)多行模式、(?s)單行模式(.匹配換行)Java 正則表達式功能強大,關鍵在於理解引擎匹配原理(NFA 回溯),並遵循「預編譯、避免過度匹配、善用斷言」三大原則。實戰中建議結合單元測試驗證邊界情況,確保穩健高效。