首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 正則表達式 Match 與 Group 深度解析:從單一匹配到命名捕獲組實戰

     編輯:關於C#

核心類別關係圖

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

效能提示

  1. 預編譯:new Regex(pattern, RegexOptions.Compiled) 或 RegexOptions.Compiled 靜態方法,首次較慢但後續匹配快 30%+。
  2. 靜態快取:Regex.IsMatch(input, pattern) 內部有 LRU 快取(預設 15 條),高頻熱路徑建議自行 static readonly Regex。
  3. 避免過度捕獲:不需提取的括號用 (?:...) 非捕獲組,減少 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[]
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved