核心類別關係圖
Regex → MatchCollection → Match → GroupCollection → Group → CaptureCollection → Capture
Match:單次匹配結果,Value 為整個匹配字串。
Group:括號內子表達式匹配,Groups[0] 等同 Match.Value。
Capture:量詞(* + ?)重複匹配的每一次結果,通常 Group.Captures.Count == 1,除非括號內含量詞。
基礎:提取 URL
string text = "Visit https://example.com and ftp://files.org";
string pattern = @"\b(\S+)://(\S+)\b";
foreach (Match m in Regex.Matches(text, pattern))
Console.WriteLine(m.Value); // https://example.com, ftp://files.org
進階:命名捕獲組
string pattern = @"\b(?\S+)://(?\S+)\b";
foreach (Match m in Regex.Matches(text, pattern))
{
Console.WriteLine($"URL: {m.Value}");
Console.WriteLine($" Protocol: {m.Groups["proto"].Value}");
Console.WriteLine($" Host: {m.Groups["host"].Value}");
}
// 輸出:
// URL: https://example.com
// Protocol: http
// Host: example.com
Group 索引 vs 名稱
| 存取方式 | 範例 | 說明 |
| 索引 | m.Groups[1] | 依括號出現順序,0 為整體 |
| 名稱 | m.Groups["proto"] | 可讀性高,重構不易出錯 |
| 列舉 | foreach (Group g in m.Groups) | 含 Group 0,需自行過濾 |
Capture 進階:重複捕獲
string pattern = @"(?\d)+"; // 連續數字,每位都是一個捕獲
Match m = Regex.Match("12345", pattern);
Console.WriteLine(m.Value); // 12345
Console.WriteLine(m.Groups["digit"].Value); // 5 (最後一次)
foreach (Capture c in m.Groups["digit"].Captures)
Console.Write(c.Value + " "); // 1 2 3 4 5
效能提示
- 預編譯:
new Regex(pattern, RegexOptions.Compiled) 或 RegexOptions.Compiled 靜態方法,首次較慢但後續匹配快 30%+。
- 靜態快取:
Regex.IsMatch(input, pattern) 內部有 LRU 快取(預設 15 條),高頻熱路徑建議自行 static readonly Regex。
- 避免過度捕獲:不需提取的括號用
(?:...) 非捕獲組,減少 Group 物件分配。
常用靜態方法速查
Regex.IsMatch(input, pattern) // bool
Regex.Match(input, pattern) // Match (第一個)
Regex.Matches(input, pattern) // MatchCollection
Regex.Replace(input, pattern, repl) // string
Regex.Split(input, pattern) // string[]