從 HTML 原始碼中解析 <a> 標籤的 href 與連結文字,是網頁爬蟲基礎步驟。本文使用 Pattern/Matcher 示範提取流程,並說明正則局限性與建議改用 HTML 解析器。
import java.io.*;
import java.net.URL;
import java.util.regex.*;
public class LinkExtractor {
public static void main(String[] args) throws IOException {
String html = fetch("https://www.example.com/");
// 1. 可選:先截取 區塊
int bodyStart = html.indexOf("= 0) bodyStart = html.indexOf('>', bodyStart) + 1;
int bodyEnd = html.indexOf("", bodyStart);
String body = (bodyStart > 0 && bodyEnd > bodyStart) ? html.substring(bodyStart, bodyEnd) : html;
// 2. 匹配 ...
Pattern linkTag = Pattern.compile("]*>(.*?)", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
Matcher m = linkTag.matcher(body);
while (m.find()) {
String fullTag = m.group(0);
String inner = m.group(1);
// 取 href
Matcher hrefM = Pattern.compile("href\\s*=\\s*[\"']?([^\"'>\\s]+)", Pattern.CASE_INSENSITIVE).matcher(fullTag);
String href = hrefM.find() ? hrefM.group(1) : "";
// 取純文字 (移除內部標籤)
String text = inner.replaceAll("<[^>]+>", "").trim();
System.out.printf("連結: %s | 文字: %s%n", href, text);
}
}
static String fetch(String urlStr) throws IOException {
try (BufferedReader br = new BufferedReader(new InputStreamReader(new URL(urlStr).openStream(), "UTF-8"))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) sb.append(line);
return sb.toString();
}
}
}
連結: /about.html | 文字: 關於我們 連結: https://api.example.com | 文字: 開放 API 連結: #contact | 文字: 聯絡我們
Document doc = Jsoup.connect(url).get(); doc.select("a[href]").forEach(...)。Pattern.DOTALL 跨行匹配,並針對目標網站調整規則。