首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 正則表達式實戰:分割、比對、替換與擷取 HTML 範例

     編輯:Java 相關知識

Java 正則表達式實戰:分割、比對、替換與擷取 HTML 範例

Java java.util.regex 套件提供強大的正則表達式功能。本文透過一個簡單的 HTML 字串,示範四大核心操作:分割字串、全文比對、替換標籤、擷取特定內容。

測試字串

String html = "regex test

this is a simple regex test

";

1. 分割字串 (split)

使用 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

2. 全文比對 (matches)

驗證字串是否符合「單一根標籤包裹」結構:

boolean matched = Pattern.compile("^<(\\w*)>.*</\\1>$").matcher(html).matches();
System.out.println(matched); // false (因為有巢狀標籤)

3. 替換字串 (replaceAll)

將所有 <p> 與 </p> 替換為 <h1> 與 </h1>:

String replaced = Pattern.compile("<(/?)p>").matcher(html).replaceAll("<$1h1>");
System.out.println(replaced);

關鍵:$1 參照第一個捕獲群組 (/?),保留可選的斜線。

4. 擷取子字串 (Matcher.find + group)

提取 <title> 標籤內的文字:

Matcher m = Pattern.compile("<title>(.*)</title>").matcher(html);
while (m.find()) {
    System.out.println(m.group(1)); // 輸出: regex test
}

核心 API 速查表

類別/方法用途
Pattern.compile(regex)編譯正則為 Pattern 物件 (可重用)
pattern.matcher(input)建立 Matcher 執行比對操作
matcher.matches()整個字串完整比對
matcher.find()尋找下一個符合的子字串
matcher.group(n)取得第 n 個捕獲群組內容 (0 為整體)
matcher.replaceAll(repl)替換所有符合處
pattern.split(input)依正則分割字串陣列

效能與最佳實踐

  • 預編譯 Pattern:靜態常量或重用場景務必預編譯,避免重複編譯開銷。
  • 貪婪 vs 非貪婪:.* 為貪婪匹配,.*? 為非貪婪,擷取 HTML 內容建議用非貪婪或排除標籤字元 [^<]*。
  • 轉義:Java 字串中反斜線需雙重轉義 \\\\,原始字串 (Java 13+ """...""") 可簡化。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved