Java java.util.regex 套件提供強大的正則表達式功能。本文透過一個簡單的 HTML 字串,示範四大核心操作:分割字串、全文比對、替換標籤、擷取特定內容。
String html = "regex test this is a simple regex test
";
使用 Pattern.split() 以 HTML 標籤符號 (<, >, /) 切割:
String[] parts = Pattern.compile("[</?|>]").split(html);
for (String part : parts) System.out.print(part + " ");
輸出:html head title regex test /title /head body p this is a simple regex test /p /body /html
驗證字串是否符合「單一根標籤包裹」結構:
boolean matched = Pattern.compile("^<(\\w*)>.*</\\1>$").matcher(html).matches();
System.out.println(matched); // false (因為有巢狀標籤)
將所有 <p> 與 </p> 替換為 <h1> 與 </h1>:
String replaced = Pattern.compile("<(/?)p>").matcher(html).replaceAll("<$1h1>");
System.out.println(replaced);
關鍵:$1 參照第一個捕獲群組 (/?),保留可選的斜線。
提取 <title> 標籤內的文字:
Matcher m = Pattern.compile("<title>(.*)</title>").matcher(html);
while (m.find()) {
System.out.println(m.group(1)); // 輸出: regex test
}
| 類別/方法 | 用途 |
|---|---|
Pattern.compile(regex) | 編譯正則為 Pattern 物件 (可重用) |
pattern.matcher(input) | 建立 Matcher 執行比對操作 |
matcher.matches() | 整個字串完整比對 |
matcher.find() | 尋找下一個符合的子字串 |
matcher.group(n) | 取得第 n 個捕獲群組內容 (0 為整體) |
matcher.replaceAll(repl) | 替換所有符合處 |
pattern.split(input) | 依正則分割字串陣列 |
.* 為貪婪匹配,.*? 為非貪婪,擷取 HTML 內容建議用非貪婪或排除標籤字元 [^<]*。\\\\,原始字串 (Java 13+ """...""") 可簡化。