核心類別與流程
Pattern:編譯後的正則表示式(Pattern.compile(regex))。
Matcher:對輸入字串執行比對(pattern.matcher(input))。
String.split(regex) / pattern.split(input):依正則分割字串。
Java 正則轉義規則(重要)
- Java 字串字面值中
\\ 代表單一反斜線;正則引擎再解析一次。
- 要在正則中表示字面反斜線,需寫
\\\\(四個反斜線)。
- 常見轉義:
\\d 數字、\\w 單字字元、\\s 空白字元;\\. 表示字面點號。
- 換行
\n、定位 \t 等在 Java 字串中只需單一反斜線。
常用元字元速查
| 符號 | 說明 |
. | 任意字元(除換行) |
^ | 字串開頭 |
$ | 字串結尾 |
* | 0 次或多次(貪婪) |
+ | 1 次或多次(貪婪) |
? | 0 次或 1 次;緊隨量詞後表示非貪婪(如 *?) |
\\d | 數字 [0-9] |
\\D | 非數字 [^0-9] |
\\w | 單字字元 [a-zA-Z0-9_] |
\\W | 非單字字元 |
[...] | 字元類別 |
(...) | 捕獲群組 |
實戰範例
1. 多重分隔符號分割字串
Pattern pattern = Pattern.compile("[, |]+");
String[] strs = pattern.split("Java Hello World Java,Hello,,World|Sun");
// 結果:Java Hello World Java Hello World Sun
2. Email 格式驗證
String email = "ceponline@yahoo.com.cn";
Pattern p = Pattern.compile(".+@.+\\..+?");
Matcher m = p.matcher(email);
System.out.println(m.matches()); // true
3. 移除 HTML 標籤
Pattern p = Pattern.compile("<.+?>");
Matcher m = p.matcher("<a href=\"index.html\">首頁</a>");
String clean = m.replaceAll("");
// 結果:首頁
4. 擷取 URL
Pattern p = Pattern.compile("<https://.+?>");
Matcher m = p.matcher("dsdsds<https://www.baidu.com/>fdf");
if (m.find()) System.out.println(m.group()); // <https://www.baidu.com/>
5. 擷取數字 / 英文字元工具方法
// 取數字(含小數點)
public Double extractNumber(String input) {
Pattern p = Pattern.compile("[^0-9/.]");
Matcher m = p.matcher(input);
String numStr = m.replaceAll("");
return Double.parseDouble(numStr);
}
// 取英文字母並轉小寫
public String extractLettersLower(String input) {
Pattern p = Pattern.compile("[^a-zA-Z]");
Matcher m = p.matcher(input);
return m.replaceAll("").toLowerCase();
}
最佳實踐提醒
- 複雜正則優先使用
Pattern.COMMENTS 模式加上註解,提升可維護性。
- 重複使用的
Pattern 應編譯一次並快取重用。
- 輸入來源不可信時,注意防範 ReDoS(正則拒絕服務攻擊)。