.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);
string trimmed = Regex.Replace(" hello ", @"^\s*(.*?)\s*$", "$1");
// 結果: "hello"
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();
}
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"
IgnoreCase:忽略大小寫。Multiline:^$ 比對行首尾。Singleline:. 比對換行符。IgnorePatternWhitespace:忽略模式中的空白與註解(方便撰寫複雜模式)。Compiled:編譯為 IL,提升重複使用效能。RightToLeft:從右向左搜尋。Compiled 選項。String.Contains、StartsWith 等。
參考資源: Microsoft Docs - Regular Expression Language、Jeffrey Friedl 《Mastering Regular Expressions》。