JDK 1.4+ 引入 java.util.regex 包,String.replaceAll/split 內部均委託該包實現。
Pattern p = Pattern.compile(regex); // 編譯
Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); // 忽略大小寫
Matcher m = p.matcher(input); // 創建匹配器
matches():整個輸入序列完全匹配lookingAt():從開頭開始匹配find():掃描尋找下一個匹配子串(最常用)group() 獲取整組,group(i) 獲取第 i 個捕獲組,groupCount() 組數| 符號 | 含義 | 等價 |
|---|---|---|
| \d | 數字 | [0-9] |
| \D | 非數字 | [^0-9] |
| \s | 空白字符 | [ \t\n\x0B\f\r] |
| \S | 非空白 | [^ \t\n\x0B\f\r] |
| \w | 單詞字符 | [a-zA-Z_0-9] |
| \W | 非單詞字符 | [^a-zA-Z_0-9] |
| . | 任意字符(含換行需 DOTALL) | — |
| ^ | 行首(MULTILINE 模式) | — |
| $ | 行尾(MULTILINE 模式) | — |
| [abc] | 單字符集合 | — |
| [^abc] | 排除字符集合 | — |
| (...) | 捕獲組 | — |
| (?:...) | 非捕獲組 | — |
String str = "aaabc efg ABC";
String regex = "aaa";
Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(str);
boolean found = m.find(); // true
// 循環查找所有匹配
while (m.find()) {
System.out.println("位置:" + m.start() + "-" + m.end() + " 內容:" + m.group());
}
// 從完整路徑提取文件名
String regex = ".+[/\\\\](.+)$"; // 兼容 Windows/Linux 分隔符
String path = "c:/dir1/dir2/name.txt";
Matcher m = Pattern.compile(regex).matcher(path);
if (m.find()) {
System.out.println(m.group(1)); // 輸出:name.txt
}
// 方式一:Pattern.split
String[] parts = Pattern.compile("::").split("xd::abc::cde");
// 方式二:String.split(內部同樣用 Pattern)
String[] parts2 = "xd::abc::cde".split("::");
// 結果:[xd, abc, cde]
String input = "aaabbced a ccdeaa";
String regex = "a+"; // 連續一個或多個 a
String replaced = Pattern.compile(regex).matcher(input).replaceAll("A");
// 結果:"Abbced A ccdeA"
// 刪除:替換為空串
String deleted = Pattern.compile(regex).matcher(input).replaceAll("");
// 結果:"bbced ccde"
* + ? (貪婪) / *? +? ?? (勉強) / *+ ++ ?+ (佔有,不回溯)\b 單詞邊界、\A 字符串開頭、\z 字符串結尾(?=...) 正向前瞻、(?!...) 負向前瞻、(?<=...) 正向後顧、(? 負向後顧(?i) 忽略大小寫、(?m) 多行、(?s) DOTALLprivate static final Pattern EMAIL = Pattern.compile(...),避免重複編譯開銷(a+)+ 匹配 aaaaaaaaaaaa! 會指數級回溯,改用佔有量詞 (a++)+ 或原子組 (?>a+)+find() 迭代而非 matches()Pattern 常量Matcher.replaceAll(Function) 支持函數式替換邏輯掌握 Pattern/Matcher 雙核模型、捕獲組提取、分割替換四大核心操作,配合常用字符類速查表,即可應對 90%+ 的文本處理場景。進階時關注回溯陷阱、預編譯復用、Java 9+ 新 API,將正則從「寫時讀懂、改時崩潰」轉化為可維護的文本處理利器。