正則表達式為字串模式描述語言,由字面字元、中繼字元、量詞、定位符、群組構成。C# 透過 System.Text.RegularExpressions.Regex 類別提供完整支援。
| 模式 | 說明 | 範例比對 |
|---|---|---|
abc | 字面字元序列 | "abc", "zabcx" |
. | 任意單一字元 (除 \n) | "a", "1", "中" |
\d | 數字 [0-9] | "5" |
\w | 單字字元 [a-zA-Z0-9_] | "A", "9", "_" |
\s | 空白字元 (空格、Tab、換行) | " ", "\t" |
\D \W \S | 對應反向類別 | - |
[aeiou] // 單一母音
[^aeiou] // 非母音 (排除類別)
[a-z] // 範圍:小寫字母
[a-zA-Z0-9] // 英數字
[\\d\\w] // 類別中可用簡寫 (等同 [\d\w])
(a|b|c) // 選擇:a 或 b 或 c
(?:cat|dog) // 非捕獲選擇
(...) 捕獲群組,自動編號 $1, $2... / \1, \2...(?<name>...) 命名群組,${name} / \k<name> 參考(?:...) 非捕獲群組,僅分組不佔編號// 靜態方法
bool isMatch = Regex.IsMatch(input, pattern);
Match match = Regex.Match(input, pattern);
MatchCollection matches = Regex.Matches(input, pattern);
string replaced = Regex.Replace(input, pattern, replacement);
// 實例模式 (重複使用編譯後表達式)
var regex = new Regex(pattern, RegexOptions.Compiled);
foreach (Match m in regex.Matches(input)) {
Console.WriteLine(m.Value);
foreach (Group g in m.Groups) {
Console.WriteLine($" Group[{g.Name}] = {g.Value}");
}
}
(?=...) (?!...)(?<=...) (?<!...)(?(condition)yes|no)(?<NAME>...) (?<-NAME>...) 處理巢狀結構




