正則表達式定義文本匹配模式。.NET 提供 System.Text.RegularExpressions.Regex 引擎,支援豐富語法元素。
| 類別 | 關鍵構造 |
|---|---|
| 字符轉義 | \a \b \t \r \n \v \f \e \nnn \xnn \cX \unnnn \\ |
| 字符類 | [abc] [^abc] [a-z] . \w \W \s \S \d \D \p{name} \P{name} |
| 定位點 | ^ $ \A \Z \z \G \b \B |
| 分組 | (sub) (? |
| 限定符 | * + ? {n} {n,} {n,m} *? +? ?? {n}? {n,}? {n,m}? |
| 反向引用 | \1 \k |
| 備選 | | (?(expr)yes|no) (?(name)yes|no) |
| 替換 | $n ${name} $$ $& $` $' $+ $_ |
IsMatch(input):是否匹配Matches(input):所有匹配集合Replace(input, replacement):替換匹配Split(input):按模式分割// 1. 以 S 開頭的單詞
Regex.Matches("A Thousand Splendid Suns", @"\bS\S*")
// Splendid, Suns
// 2. 以 m 開頭 e 結尾
Regex.Matches("make maze manage measure", @"\bm\S*e\b")
// make, maze, manage, measure
// 3. 合并多餘空格
Regex.Replace("Hello World", @"\s+", " ")
// "Hello World"
@ 逐字字符串避免雙重轉義new Regex(pattern, RegexOptions.Compiled) 提升重用性能(?...) 增強可讀性