在 C# WinForms / 爬蟲場景中,從伺服器回傳的 HTML 片段提取特定查詢參數 (如 `uid=555`),使用 System.Text.RegularExpressions.Regex 配合**正向顧後斷言** 是最簡潔高效的方法。
using System;
using System.Text.RegularExpressions;
public class HtmlUidExtractor {
public static void Main() {
string html = @"";
// 正則:(?<=uid=)\d+
// (?<=uid=) 正向顧後斷言:匹配位置前面必須是 "uid=",但不消耗字元
// \d+ 匹配一個或多個數字 (uid 的值)
string pattern = @"(?<=uid=)\d+";
Match match = Regex.Match(html, pattern);
if (match.Success) {
Console.WriteLine("提取到的 uid: " + match.Value); // 輸出: 555
} else {
Console.WriteLine("未找到 uid 參數");
}
// 若 HTML 中有多個 uid,需提取全部:
MatchCollection matches = Regex.Matches(html, pattern);
Console.WriteLine("所有 uid:");
foreach (Match m in matches) {
Console.WriteLine(m.Value);
}
}
}
| 片段 | 含義 |
|---|---|
(?<=uid=) | 正向顧後斷言:斷言當前位置前方必須為字串 "uid="。匹配結果不包含 "uid="。 |
\d+ | 匹配一個或多個數字字元 (0-9)。若 uid 可能含字母,改用 `[^&"']+` 或 `\w+`。 |
string pattern = @"(?<=uid=)[\w-]+"; // \w = [a-zA-Z0-9_]
// 匹配 ?uid= 或 &uid= 開頭的參數
string pattern = @"(?<=[?&]uid=)[^&""']+";
string uid = Regex.Match(html, @"(?<=uid=)\d+").Value;
// .Value 直接返回匹配字串,無匹配時返回 String.Empty
string pattern = @"(?<=uid=)(?\d+)";
Match m = Regex.Match(html, pattern);
if (m.Success) {
string uid = m.Groups["uid"].Value;
}
private static readonly Regex UidRegex = new Regex(@"(?<=uid=)\d+", RegexOptions.Compiled);
// 使用:UidRegex.Match(html)
uid=` + `\d+`,無回溯風險。若 HTML 結構複雜、巢狀深、屬性值含引號變化大,正則易出錯。建議引入 HtmlAgilityPack** (NuGet) 進行結構化解析:
// using HtmlAgilityPack;
var doc = new HtmlDocument();
doc.LoadHtml(html);
var nodes = doc.DocumentNode.SelectNodes("//@href | //@content"); // 取所有 href、content 屬性
foreach (var attr in nodes.SelectMany(n => n.Attributes)) {
var match = Regex.Match(attr.Value, @"(?<=uid=)\d+");
if (match.Success) Console.WriteLine(match.Value);
}
針對「從 HTML 字串提取 `uid=數字`」這類明確模式,Regex.Match(html, @"(?<=uid=)\d+").Value 是**最少代碼、最高效能**的方案。若需處理複雜/不規範 HTML,請改用 HtmlAgilityPack 解析後再配合正則提取參數值。