前言
正則表達式 是字串比對、驗證、擷取、替換的利器。C# 透過 `System.Text.RegularExpressions.Regex` 類別提供完整支援。本文涵蓋基礎語法、常用驗證模式、核心 API (`Match`/`Matches`/`Replace`/`Split`)、編譯優化、常見陷阱與效能調優。
一、基礎語法速查表
| 元字元 | 說明 | 範例 |
| `^` | 字串開頭 (多行模式為行首) | `^Hello` |
| `$` | 字串結尾 (多行模式為行尾) | `World$` |
| `.` | 任意單一字元 (預設不含換行) | `a.c` → `abc`, `axc` |
| `\d` | 數字 `[0-9]` | `\d{4}` → 4 位數 |
| `\w` | 字母數字底線 `[A-Za-z0-9_]` | `\w+` → 變數名 |
| `\s` | 空白字元 (空格、Tab、換行) | `\s+` → 多個空白 |
| `[abc]` | 字元集合 | `[aeiou]` → 母音 |
| `[^abc]` | 排除字元集合 | `[^0-9]` → 非數字 |
| `*` | 零或多次 (貪婪) | `ab*c` → `ac`, `abc`, `abbc` |
| `+` | 一次或多次 | `\d+` → 至少一位數 |
| `?` | 零或一次 | `colou?r` → `color`, `colour` |
| `{n,m}` | n 到 m 次 | `\d{3,5}` → 3-5 位數 |
| `|` | 或 (Alternation) | `cat|dog` |
| `()` | 捕獲群組 | `(\d{4})-(\d{2})` |
| `(?:)` | 非捕獲群組 (效能較好) | `(?:http|https)://` |
| `(?<name>)` | 命名捕獲群組 | `(?<year>\d{4})` |
| `\1`, `\k<name>` | 反向參照 | `(['\"])(.*?)\1` → 引號配對 |
| `(?=)` | 正向預查 (零寬斷言) | `\w+(?=\d)` → 後面接數字的字 |
| `(?!)` | 負向預查 | `\b(?!password)\w+\b` → 不含 password 的詞 |
二、常用驗證模式 (可直接複製)
public static class RegexPatterns
{
// 帳號:字母開頭,6-16 字元,英數底線
public const string Username = @"^[A-Za-z][A-Za-z0-9_]{5,15}$";
// 密碼:8-20 字元,至少一大寫、一小寫、一數字、一特殊符號
public const string PasswordStrong = @"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*]).{8,20}$";
// Email (RFC 5322 簡化版)
public const string Email = @"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$";
// 手機 (台灣):09 開頭 10 碼
public const string PhoneTW = @"^09\d{8}$";
// 身分證字號 (台灣):1 字母 + 9 數字,含檢查碼邏輯 (需額外程式碼驗證)
public const string IdNumberTW = @"^[A-Z][12]\d{8}$";
// 統一編號 (台灣):8 位數字
public const string VatNumberTW = @"^\d{8}$";
// URL (http/https)
public const string Url = @"^https?://[\w.-]+(?:\.[\w.-]+)+[\w\-._~:/?#[\]@!$&'()*+,;=.]+$";
// IPv4
public const string Ipv4 = @"^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$";
// 日期 YYYY-MM-DD (含閏年簡易檢查)
public const string DateIso = @"^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])$";
// 中文字 (含標點)
public const string ChineseChars = @"^[\u4e00-\u9fa5\u3000-\u303f\uff00-\uffef]+$";
}
三、Regex 核心 API 實戰
1. 驗證 `IsMatch`
bool valid = Regex.IsMatch(input, RegexPatterns.Email, RegexOptions.IgnoreCase);
2. 擷取單一 `Match`
Match m = Regex.Match(logLine, @"(?<time>\d{2}:\d{2}:\d{2})\s+(?<level>\w+)\s+(?<msg>.+)");
if (m.Success)
{
Console.WriteLine($"Time: {m.Groups["time"].Value}, Level: {m.Groups["level"].Value}");
}
3. 擷取全部 `Matches`
foreach (Match m in Regex.Matches(html, @"<a\s+href=\""(?<url>[^\""]+)\"""))
Console.WriteLine(m.Groups["url"].Value);
4. 替換 `Replace`
// 隱藏身分證中間 4 碼
string masked = Regex.Replace(id, @"(?<=\w{1}\d{1})\d{4}(?=\d{4})", "****");
// 移除 HTML 標籤
string plain = Regex.Replace(html, @"<[^>]+>", "");
// 回呼替換:將所有數字 *2
string doubled = Regex.Replace("a1b23c", @"\d+", m => (int.Parse(m.Value) * 2).ToString());
5. 分割 `Split`
string[] tokens = Regex.Split(input, @"\s*,\s*"); // 依逗號分割,允許前後空白
四、效能優化關鍵
- 靜態編譯:重複使用的 Regex 宣告為 `static readonly` 並加 `RegexOptions.Compiled` (或 .NET 7+ `RegexGenerator` Source Generator)。
- 避免災難性回溯:巢狀量詞 `(.+)+`、重疊選項 `(a|a*)+` → 改用具體字元類別、原子群組 `(?>...)`、佔有優先量詞 `*+`, `++` (需 .NET 7+ / PCRE)。
- 預編譯快取:`RegexOptions.Compiled` 會編譯為 IL,首次較慢但後續極快;.NET 7+ 可用 `[GeneratedRegex]` 於編譯期產生代碼。
- 避免在迴圈 `new Regex(...)`:每次實例化都會解析編譯。
五、.NET 7+ Source Generator 範例 (編譯期生成最佳化代碼)
using System.Text.RegularExpressions;
public partial class MyRegex
{
[GeneratedRegex(@"^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})$", RegexOptions.Compiled | RegexOptions.CultureInvariant)]
public static partial Regex DateIsoRegex();
}
// 使用
Match m = MyRegex.DateIsoRegex().Match("2024-05-20");
if (m.Success) Console.WriteLine($"Year: {m.Groups["year"].Value}");
六、常見陷阱與除錯技巧
| 陷阱 | 說明 | 解決 |
| 貪婪 vs 惰性 | `.*` 會吞噬整行 | 改用 `.*?` 或 `[^"]*` 明確排除 |
| 跳脫字元 | C# 字串 `\\` → Regex `\` | 使用 `@` 字面字串:`@"\d+"` |
| 多行模式 | `^$` 預設匹配整串開頭結尾 | 加 `RegexOptions.Multiline` 讓 `^$` 匹配行首尾 |
| 忽略大小寫 | 預設區分大小寫 | `RegexOptions.IgnoreCase` 或 `(?i)` 內嵌選項 |
| 文化特性 | `\w` 在某文化包含非 ASCII | `RegexOptions.CultureInvariant` 或 `[\p{L}\p{N}_]` |
七、線上測試工具推薦
- Regex101 (支援 PCRE/.NET/JavaScript/Python,即時解釋、單元測試)
- RegExr (視覺化高亮、社群範例庫)
- Visual Studio「正則運算式設計工具」 (Ctrl+K, Ctrl+R) 或擴充 Regex Editor。