網頁爬蟲、內容分析、SEO 檢測等場景常需從 HTML 中提取超連結的 href 屬性(Link)與連結文字(Text)。使用 Regex 是輕量級的解析方案。
string pattern = @"<a[^>]*href=(""(?<href>[^""]*)""|'(?<href>[^']*)'|(?<href>[^\s>]*))[^>]*>(?<text>.*?)</a>";
模式解析:
<a[^>]*:匹配 <a 開始,後接任意非 > 字元href=:匹配 href 屬性("(?<href>[^""]*)"|'(?<href>[^']*)'|(?<href>[^\s>]*)):三種引號格式支援
"(?<href>[^""]*)"'(?<href>[^']*)'(?<href>[^\s>]*)[^>]*>:匹配剩餘屬性至標籤結束(?<text>.*?):非貪婪匹配連結文字(命名群組 text)</a>:匹配結束標籤string html = @"<a href=""https://example.com"" class=""link">範例網站</a>
<a href='https://test.com' id='t1'>測試站</a>
<a href=https://noquote.com>無引號</a>";
Regex re = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);
foreach (Match m in re.Matches(html))
{
string link = m.Groups["href"].Value;
// 移除文字中的巢狀 HTML 標籤
string text = Regex.Replace(m.Groups["text"].Value, @"<[^>]*>", "");
Console.WriteLine($"Link: {link}");
Console.WriteLine($"Text: {text}");
Console.WriteLine("---");
}
Link: https://example.com
Text: 範例網站
---
Link: https://test.com
Text: 測試站
---
Link: https://noquote.com
Text: 無引號
| 場景 | 建議方案 |
|---|---|
| 簡單提取、效能敏感 | Regex(如本文) |
| 複雜 HTML、巢狀結構、錯誤容忍 | HtmlAgilityPack / AngleSharp |
| 需執行 JavaScript 渲染後內容 | Selenium / Playwright / Puppeteer |
| 大規模爬蟲專案 | ScrapySharp / HttpClient + 解析器 |
RegexOptions.Singleline 讓 . 匹配換行符href 屬性順序不固定:正則假設 href 在前,實際 HTML 可能 <a class=""x"" href=""..."">& 等實體,需解碼// 更健壯但較複雜的模式
string robustPattern = @"<a\s+(?:[^>]*?\s)?href=(""(?<href>[^""]*)""|'(?<href>[^']*)'|(?<href>[^\s>]*))[^>]*>(?<text>.*?)</a>";