正則表達式基礎速查
| 模式 | 說明 | 範例匹配 |
Mic* | Mic 後接 0+ 個 'c' | Mic, Micc, Miccc... |
Mic+ | Mic 後接 1+ 個 'c' | Micc, Miccc... (不含 Mic) |
. | 任意單一字元 | a, 1, @, 中... |
[a-zA-Z_0-9] | 字母、數字、底線 | a, Z, 5, _ |
\w | 等同 [a-zA-Z_0-9] | 同上 |
\w+ | 至少一個單字字元 | identifier, var1 |
^...$ | 行首/行尾錨點 | 整行匹配 |
\d | 數字 [0-9] | 0~9 |
{n} | 重複 n 次 | |
{m,n} | 重複 m~n 次 | |
? | 0 或 1 次 (等同 {0,1}) | |
(...) | 分組捕獲 | |
\b | 單字邊界 | |
經典範例解析
- C 識別碼:
^[a-zA-Z_]\w*$
- MasterCard (16 碼, 5 開頭):
^5\d{15}$
- Visa (16 碼, 4/5 開頭):
^[45]\d{15}$
- 美國郵遞區號 (ZIP/ZIP+4):
^\d{5}(-\d{4})?$
.NET Framework Regex 類架構
Regex
├── Match(string) → Match (第一個匹配)
├── Matches(string) → MatchCollection (所有匹配)
├── Replace(input, repl) → string (替換)
├── Split(string) → string[] (分割)
└── 靜態方法:Regex.Match/Replace/IsMatch 等
支援類別
- Match:單次匹配結果 (
Value, Index, Length, Groups)
- Group:分組捕獲 (
Value, Index, Length, Captures)
- Capture:單次捕獲片段
核心用法範例
1. 列舉所有單字
Regex r(@"\b\w+\b");
MatchCollection mc = r.Matches("abc ,_foo ,<& mumble7");
foreach (Match m in mc)
Console.WriteLine(m.Value); // abc, foo, mumble7
2. 分組捕獲:郵遞區號
Regex r(@"^(\d{5})(-\d{4})?$");
Match m = r.Match("98007-4235");
if (m.Success) {
Console.WriteLine(m.Groups[1].Value); // 98007
Console.WriteLine(m.Groups[2].Value); // -4235
}
3. Replace 字串替換
// \n → \r\n
string s = Regex.Replace(s, @"\n", "\r\n");
// 動態替換:委派
string result = Regex.Replace(input, @"\d+", m => (int.Parse(m.Value) * 2).ToString());
4. 靜態方法快速使用
bool valid = Regex.IsMatch(email, @"^[\w.+-]+@[\w-]+\.[\w.-]+$");
string[] tokens = Regex.Split(line, @"\s+");
進階技巧
- 命名分組:
(?<name>...) → m.Groups["name"]
- 非捕獲分組:
(?:...) 不佔用 Groups 索引
- 前瞻/後顧:
(?=...) (?!...) (?<=...) (?<!...)
- 單行/多行模式:
RegexOptions.Singleline (.含換行), Multiline (^$匹配行首尾)
- 編譯優化:
RegexOptions.Compiled 重複使用時提升速度
跨平台/語言差異提醒
| 特性 | .NET | Perl/PCRE | JavaScript |
{,1} 寫法 | 不支援 | 支援 (= {0,1}) | 不支援 |
\b Unicode 感知 | 是 | 視版本 | 否 (僅 ASCII) |
| 命名分組語法 | (?<name>...) | (?P<name>...) | (?<name>...) (ES2018+) |
最佳實務
- 複雜模式加註解:
Regex(@"^ (?<area>\d{3}) - (?<num>\d{4}) $", RegexOptions.IgnorePatternWhitespace)
- 重複使用編譯後的
Regex 實例,避免每次重新解析。
- 輸入驗證優先用
IsMatch,擷取資料用 Match/Groups。
- 大量文字處理考慮
StringBuilder + Regex.Replace 代替字串串接。
- 上一篇文章: 2D 遊戲等軸測視角地圖滾動核心算法與實作 (Win32 組語)
- 下一篇文章: 基於 libpcap/WinPcap 的簡易網路封包擷取器 (Sniffer) C 實作
Copyright ©
程式碼之家 All Rights Reserved