同一個需求,換個語言寫,正則的「骨架」幾乎一樣,但細節差異會直接影響你能不能取到目標。以下用「抓出 HTML 中所有帶 href 的 a 標籤」當例子,看看 JavaScript 與 C# 各自的寫法。
<html>
<head>
<script language="javascript">
var a = '<P><A href=\'~abc/ccg/ab.jpg\' width="3">文字</A><A width="4" style="color:#ddd; font-weight:bold;" mm_href="http:www.baidu.com" href="https://bbs.cn.yimg.com/user_img/200701/31/soso1.jpg" mce_href="https://bbs.cn.yimg.com/user_img/200701/31/jisuanji986_117025184198149.jpg">cc</A> href="www.baidu.com" cbas <span>cchref</span> 1<a dd href="ccc"> <A width="5" href="https://bbs.cn.yimg.com/user_img/200701/31/soso2.jpg" mce_href="https://bbs.cn.yimg.com/user_img/200701/31/cc.jpg"></A></P>';
var b = /<a([\s]+|[\s]+[^<>]+[\s]+)href=("([^<>"']*)"|'([^<>"']*)')[^<>]*>/gi;
var s = a.toLowerCase().match(b);
alert(s.length);
for (var i = 0; i < s.length; i++) {
var ss = s[i].toLowerCase().match(b);
alert(RegExp.$3 + RegExp.$4);
}
</script>
</head>
<body>
</body>
</html>
string html = "<P><A href='~abc/ccg/ab.jpg' height=\"4\" width='3' >文字</A><A width=\"4\" style=\"color:#ddd; font-weight:bold;\" mm_href=\"http:www.baidu.com\" href=\"https://bbs.cn.yimg.com/user_img/200701/31/soso1.jpg\" mce_href=\"https://bbs.cn.yimg.com/user_img/200701/31/jisuanji986_117025184198149.jpg\">cc</A> href=\"www.baidu.com\" cbas <span>cchref</span> 1<a df href=\"cc\"> <A width=\"5\" href=\"https://bbs.cn.yimg.com/user_img/200701/31/soso2.jpg\" mce_href=\"https://bbs.cn.yimg.com/user_img/200701/31/cc.jpg\"></A></P>";
Regex reg = new Regex(
"<a([\\s]+|[\\s]+[^<>]+[\\s]+)href=(\"(<href>[^<>\"']*)\"|'(<href>[^<>\"']*)')[^<>]*>",
RegexOptions.IgnoreCase
);
MatchCollection matchCollection = reg.Matches(html);
MessageBox.Show(matchCollection.Count.ToString());
foreach (Match match in matchCollection)
{
MessageBox.Show(match.Groups["href"].ToString());
}
JavaScript 直到 ES2018 才支援 (?<name>...),在此之前只能用位置編號($3、$4)搭配 RegExp.$n 取值。C# 早就提供 (?<name>...),透過 match.Groups["name"] 直接命名取值,可讀性明顯更好。
C# 字串裡的 \ 本身要跳脫,所以正則的 \s 得寫成 \\s;或使用逐字字串 @"...\s..." 少寫一層。
JS 用 String.match(帶 g 回傳全部匹配陣列,不帶則回傳含捕獲組的單一結果)或 RegExp.exec(可反覆呼叫,靠 lastIndex 前進)。C# 則用 Regex.Matches 一次取得 MatchCollection,用 foreach 遍歷。
JS 靠修飾符 gi;C# 靠 RegexOptions.IgnoreCase 列舉參數。
用正則解析 HTML 在實務上並不建議。HTML 不是規則語言,遇到註解、CDATA、屬性跨行、單雙引號混用時,正則很容易誤判。上面的範例文本刻意塞了 mm_href、mce_href、cbas 這類干擾項,正是為了凸顯這個問題。真正要處理 HTML,JS 請用 DOMParser 或 querySelectorAll,C# 請用 HtmlAgilityPack。正則適合用來做「格式已知且穩定」的字串比對,而不是解析標記語言。