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

Java 正則表達式提取 HTML 標籤指定屬性值實戰

     編輯:Java 相關知識

需求場景

從 HTML 字串快速提取特定標籤的特定屬性值,例如所有 <a> 的 href 或 title。

核心正則

String regex = "<" + tagName + "[^<>]*?\\s" + attrName + "=['\"]?(.*?)['\"]?(\\s.*?)?>";

解析:

  • [^<>]*?:非貪婪匹配非尖括號字元(屬性前綴)
  • \\s:屬性名前至少一個空白
  • ['\"]?:可選引號
  • (.*?):捕獲組 1 = 屬性值(非貪婪)
  • (\\s.*?)?:剩餘屬性

完整工具類

public final class HtmlAttrExtractor {
    private HtmlAttrExtractor() {}

    public static List extract(String html, String tag, String attr) {
        List result = new ArrayList<>();
        String regex = "<" + tag + "[^<>]*?\\s" + attr + "=['\"]?(.*?)['\"]?(\\s.*?)?>";
        Matcher m = Pattern.compile(regex, Pattern.CASE_INSENSITIVE).matcher(html);
        while (m.find()) result.add(m.group(1));
        return result;
    }

    public static void main(String[] args) {
        String html = "aaabbb";
        System.out.println(extract(html, "a", "title"));  // [中國體育報, 北京日報]
    }
}

⚠️ 重要限制

  • 正則無法正確處理:巢狀標籤、屬性值含 >、跨行、註解、CDATA、Script/Style 內容
  • 生產環境強烈建議使用解析器:Jsoup、Jericho、TagSoup

Jsoup 替代方案(推薦)

Document doc = Jsoup.parse(html);
Elements links = doc.select("a[title]");
for (Element a : links) System.out.println(a.attr("title"));

線上測試工具

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved