正則表達式是文本處理利器。本文系統講解 C# 正則核心語法:元字符、轉義、限定符,並給出常用驗證模式速查表。
| 元字符 | 含義 | 示例匹配 |
|---|---|---|
. | 除換行符外任意單字符 | a.c → "abc", "a-c", "a c" |
\d | 數字 [0-9] | \d{3} → "123" |
\D | 非數字 [^0-9] | |
\w | 單詞字符 [a-zA-Z0-9_] | |
\W | 非單詞字符 | |
\s | 空白字符 (空格、制表、換行...) | |
\S | 非空白字符 | |
^ | 字符串開始 (多行模式下行首) | |
$ | 字符串結束 (多行模式下行尾) | |
\b | 單詞邊界 | \bword\b 匹配獨立單詞 |
\B | 非單詞邊界 |


需匹配元字符本身時,用 \ 轉義:
\. → 匹配字面點號\\ → 匹配反斜槓\*, \+, \?, \^, \$, \(, \), \[, \], \{, \}, \|
C# 字符串中 \ 需雙寫或用 @ 逐字字符串:@"\\d+"。
| 限定符 | 含義 | 貪婪/惰性 |
|---|---|---|
* | 0 次或多次 | 貪婪 |
+ | 1 次或多次 | 貪婪 |
? | 0 次或 1 次 | 貪婪 |
{n} | 恰好 n 次 | |
{n,} | 至少 n 次 | 貪婪 |
{n,m} | n 到 m 次 | 貪婪 |
*?, +?, ??, {n,m}? | 惰性匹配 (最少) | 惰性 |

(...):捕獲組,可用 $1 (替換) 或 \1 (反向引用) 引用。(?:...):非捕獲組,僅分組不捕獲,性能略優。(?<name>...):命名捕獲組,${name} 引用。| 場景 | 正則模式 |
|---|---|
| 郵箱 | @"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$" |
| 手機號 (中國大陸) | @"^1[3-9]\d{9}$" |
| 身份證 (18位) | @"^\d{17}[\dXx]$" |
| URL | @"^(https?|ftp)://[^\s/$.?#].[^\s]*$" |
| IPv4 | @"^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$" |
| 中文字符 | @"^[\u4e00-\u9fa5]+$" |
| 密碼 (8-16位,含大小寫數字特殊) | @"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[~!@#$%^&*]).{8,16}$" |
| 日期 (YYYY-MM-DD) | @"^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$" |
using System.Text.RegularExpressions;
// 判斷匹配
bool isMatch = Regex.IsMatch(input, pattern);
// 單次匹配
Match m = Regex.Match(input, pattern);
if (m.Success) Console.WriteLine(m.Value); // m.Groups[1].Value
// 所有匹配
foreach (Match m in Regex.Matches(input, pattern)) { ... }
// 替換
string result = Regex.Replace(input, pattern, replacement); // $1 $2 引用組
// 分割
string[] parts = Regex.Split(input, pattern);
// 編譯優化 (靜態只读 Regex 對象, 重用)
private static readonly Regex EmailRegex = new Regex(pattern, RegexOptions.Compiled);
最佳實踐: 複用 Regex 實例、使用 RegexOptions.Compiled、避免災難性回溯 (慎用嵌套量詞)、複雜正則加註釋 (RegexOptions.IgnorePatternWhitespace)。