從 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、TagSoupDocument doc = Jsoup.parse(html);
Elements links = doc.select("a[title]");
for (Element a : links) System.out.println(a.attr("title"));