萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C# 正則表達式入門教程:元字符、轉義、限定符與實戰模式

正則表達式是文本處理利器。本文系統講解 C# 正則核心語法:元字符、轉義、限定符,並給出常用驗證模式速查表。

1. 元字符

元字符含義示例匹配
.除換行符外任意單字符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非單詞邊界
元字符表1
元字符表2

2. 轉義字符

需匹配元字符本身時,用 \ 轉義:

  • \. → 匹配字面點號
  • \\ → 匹配反斜槓
  • \*, \+, \?, \^, \$, \(, \), \[, \], \{, \}, \|
轉義字符示例

C# 字符串中 \ 需雙寫或用 @ 逐字字符串:@"\\d+"。

3. 限定符 (量詞)

限定符含義貪婪/惰性
*0 次或多次貪婪
+1 次或多次貪婪
?0 次或 1 次貪婪
{n}恰好 n 次
{n,}至少 n 次貪婪
{n,m}n 到 m 次貪婪
*?, +?, ??, {n,m}?惰性匹配 (最少)惰性
限定符表

4. 分組與捕獲

  • (...):捕獲組,可用 $1 (替換) 或 \1 (反向引用) 引用。
  • (?:...):非捕獲組,僅分組不捕獲,性能略優。
  • (?<name>...):命名捕獲組,${name} 引用。

5. 常用驗證模式速查 (C# 字符串寫法)

場景正則模式
郵箱@"^[\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])$"

6. C# 核心 API 速覽

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)。

copyright © 萬盛學電腦網 all rights reserved