Java 正則表達式主要涉及 java.util.regex 包下的兩個核心類:
Pattern.compile(regex) 獲取實例。pattern.matcher(input) 獲取。判斷整個字符串是否符合規則,使用 String.matches(regex) 或 Matcher.matches()。
// 驗證手機號:1開頭,第二位3/5/8,共11位
String phone = "13539770000";
boolean valid = phone.matches("1[358]\\d{9}"); // true
// 驗證字符串包含特定子串
String str = "abcd12345efgh";
boolean contains = str.matches("\\w+12345\\w+"); // true
使用 Matcher.find() 遍歷所有匹配片段,group() 獲取捕獲組內容。
String str = "qq84461376qq qq84461377qq qq84461378qq";
Pattern p = Pattern.compile("qq(.*?)qq"); // 非貪婪模式
Matcher m = p.matcher(str);
List results = new ArrayList<>();
while (m.find()) {
results.add(m.group(1)); // 獲取第1個捕獲組
}
// 結果: [84461376, 84461377, 84461378]
String.replaceAll(regex, replacement) 或 Matcher.replaceAll() / replaceFirst()。
String str = "file.name.txt.doc";
// 將點替換為下劃線 (需轉義)
String result = str.replaceAll("\\.", "_");
// 結果: "file_name_txt_doc"
// 使用 Matcher 進行複雜替換 (如格式化手機號)
String phone = "13539770000";
String formatted = phone.replaceAll("(\\d{3})(\\d{4})(\\d{4})", "$1-$2-$3");
// 結果: "135-3977-0000"
String.split(regex) 根據正則切割字符串。
String domains = "www.google.com;mail.yahoo.com;docs.microsoft.com";
// 按分號或點分割
String[] parts = domains.split("[;.]");
// 結果: ["www", "google", "com", "mail", "yahoo", "com", "docs", "microsoft", "com"]
| 元字符 | 說明 |
|---|---|
. | 匹配除換行符外任意字符 |
\d | 數字 [0-9] |
\w | 單詞字符 [a-zA-Z0-9_] |
\s | 空白字符 (空格, Tab, 換行) |
^ | 行首 |
$ | 行尾 |
* | 0 次或多次 |
+ | 1 次或多次 |
? | 0 次或 1 次 |
{n} | 恰好 n 次 |
{n,} | 至少 n 次 |
{n,m} | n 到 m 次 |
() | 捕獲組 |
(?:) | 非捕獲組 |
| | 或運算 |
^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$^https?://([\\w-]+\\.)+[\\w-]+(/[\\w-./?%&=]*)?$^\\d{17}[\\dXx]$^((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$[\\u4e00-\\u9fa5](?:...) 減少內存開銷。(a+)* 易導致災難性回溯。^ $ 縮小匹配範圍。掌握 Pattern/Matcher 雙核心、四大操作 API 及常用語法,即可應對 90% 的文本處理場景。複雜業務中請優先考慮預編譯與回溯優化。