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

C# .NET 正則表達式完整指南:Regex 類別、比對、取代、群組捕獲

     編輯:關於C語言

.NET 正則表達式核心類別與用法

.NET 基礎類別庫在 System.Text.RegularExpressions 命名空間提供完整的 Regex 功能,相容 Perl 5 語法並擴充 .NET 特有功能(如具名群組、右向左比對、MatchEvaluator)。

核心類別架構

  • Regex:編譯後的正則表達式實例,提供靜態與實體方法。
  • Match:單次比對結果,繼承自 Group。
  • Group:群組捕獲結果,繼承自 Capture。
  • Capture:單次捕獲片段。
  • MatchCollection、GroupCollection、CaptureCollection:對應集合。
  • MatchEvaluator:委派,用於複雜取代邏輯。

常用靜態方法

// 簡單比對
bool isMatch = Regex.IsMatch(input, pattern);

// 取得第一個比對
Match m = Regex.Match(input, pattern);
if (m.Success) Console.WriteLine(m.Value);

// 取得所有比對
MatchCollection matches = Regex.Matches(input, pattern);
foreach (Match match in matches) { ... }

// 字串取代
string replaced = Regex.Replace(input, pattern, replacement);

// 依模式分割
string[] parts = Regex.Split(input, pattern);

// 轉義/反轉義
string escaped = Regex.Escape(input);
string unescaped = Regex.Unescape(escaped);

實用範例

1. 去除字串首尾空白

string trimmed = Regex.Replace("  hello  ", @"^\s*(.*?)\s*$", "$1");
// 結果: "hello"

2. 群組捕獲與巢狀群組

string text = "abracadabra1abracadabra2abracadabra3";
string pattern = @"
    (           # 群組 1
        abra    # 比對 abra
        (cad)?  # 群組 2:選擇性比對 cad
    )+          # 重複一次以上
";

Regex regex = new Regex(pattern, RegexOptions.IgnorePatternWhitespace);
Match m = regex.Match(text);
while (m.Success)
{
    Console.WriteLine($"完整比對: {m.Value}");
    for (int i = 1; i < m.Groups.Count; i++)
    {
        Group g = m.Groups[i];
        Console.WriteLine($"  群組 {i}: {g.Value}");
        foreach (Capture c in g.Captures)
            Console.WriteLine($"    捕獲: {c.Value} @{c.Index} 長度{c.Length}");
    }
    m = m.NextMatch();
}

3. 具名群組與 MatchEvaluator

string pattern = @"(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})";
string input = "2023-08-15";

string formatted = Regex.Replace(input, pattern, m =>
    $"{m.Groups[\"day\"]}/{m.Groups[\"month\"]}/{m.Groups[\"year\"]}");
// 結果: "15/08/2023"

RegexOptions 常用選項

  • IgnoreCase:忽略大小寫。
  • Multiline:^$ 比對行首尾。
  • Singleline:. 比對換行符。
  • IgnorePatternWhitespace:忽略模式中的空白與註解(方便撰寫複雜模式)。
  • Compiled:編譯為 IL,提升重複使用效能。
  • RightToLeft:從右向左搜尋。

效能建議

  • 重複使用的 Regex 實體化並啟用 Compiled 選項。
  • 避免過度使用回溯導致災難性回溯(Catastrophic Backtracking)。
  • 簡單字串操作優先用 String.Contains、StartsWith 等。

參考資源: Microsoft Docs - Regular Expression Language、Jeffrey Friedl 《Mastering Regular Expressions》。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved