括號 () 定義捕獲群組,預設自動編號 (Group 0 為完整比對)。(tr|b)ee 比對 "tree" 或 "bee",Group 1 捕獲 "tr" 或 "b"。命名群組 (?<name>...) 提升可讀性與維護性。
\1、\k<name> 參考前面捕獲群組內容。實用場景:HTML 標籤配對 <(?<tag>\w+)>.*?</\k<tag>>、重複單字偵測 \b(?<word>\w+)\b\s+\k<word>\b。
string input = "2024-01-15";
string pattern = @"(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})";
string replacement = "${d}/${m}/${y}"; // 15/01/2024
var result = Regex.Replace(input, pattern, replacement);
// 或使用 MatchEvaluator 複雜邏輯
var result2 = Regex.Replace(input, pattern, m =>
$"{m.Groups["d"].Value}/{m.Groups["m"].Value}/{m.Groups["y"].Value}");
(?:...) 非捕獲群組,僅分組不佔用群組編號(?=...) 正向先行斷言 (Zero-width positive lookahead)(?!...) 負向先行斷言(?<=...) 正向後行斷言 (固定寬度)(?<!...) 負向後行斷言(?#...) 註解| 選項 | 說明 |
|---|---|
| IgnoreCase | 不區分大小寫 |
| Multiline | ^$ 比對行首行尾 |
| Singleline | . 比對換行符 |
| ExplicitCapture | 僅命名群組捕獲 |
| Compiled | 編譯為 IL 提升重複使用效能 |
| CultureInvariant | 忽略文化特性差異 |


