top
Loading...
C# 正則表達式

C# 正則表達式

正則表達式 是一種匹配輸入文本的模式。.Net 框架提供了允許這種匹配的正則表達式引擎。模式由一個或多個字符、運算符和結構組成。

定義正則表達式

下面列出了用於定義正則表達式的各種類別的字符、運算符和結構。

  • 字符轉義
  • 字符類
  • 定位點
  • 分組構造
  • 限定符
  • 反向引用構造
  • 備用構造
  • 替換
  • 雜項構造

字符轉義

正則表達式中的反斜槓字符(\)指示其後跟的字符是特殊字符,或應按原義解釋該字符。

下表列出了轉義字符:

轉義字符描述模式匹配
\a與報警 (bell) 符 \u0007 匹配。\a"Warning!" + '\u0007' 中的 "\u0007"
\b在字符類中,與退格鍵 \u0008 匹配。[\b]{3,}"\b\b\b\b" 中的 "\b\b\b\b"
\t與製表符 \u0009 匹配。(\w+)\t"Name\tAddr\t" 中的 "Name\t" 和 "Addr\t"
\r與回車符 \u000D 匹配。(\r 與換行符 \n 不是等傚的。)\r\n(\w+)"\r\Hello\nWorld." 中的 "\r\nHello"
\v與垂直製表符 \u000B 匹配。[\v]{2,}"\v\v\v" 中的 "\v\v\v"
\f與換頁符 \u000C 匹配。[\f]{2,}"\f\f\f" 中的 "\f\f\f"
\n與換行符 \u000A 匹配。\r\n(\w+)"\r\Hello\nWorld." 中的 "\r\nHello"
\e與轉義符 \u001B 匹配。\e"\x001B" 中的 "\x001B"
\ nnn使用八進製表示形式指定一個字符(nnn 由二到三位數字組成)。\w\040\w"a bc d" 中的 "a b" 和 "c d"
\x nn使用十六進製表示形式指定字符(nn 恰好由兩位數字組成)。\w\x20\w"a bc d" 中的 "a b" 和 "c d"
\c X \c x 匹配 X 或 x 指定的 ASCII 控件字符,其中 X 或 x 是控件字符的字母。\cC"\x0003" 中的 "\x0003" (Ctrl-C)
\u nnnn使用十六進製表示形式匹配一個 Unicode 字符(由 nnnn 表示的四位數)。\w\u0020\w"a bc d" 中的 "a b" 和 "c d"
\在後面帶有不識別的轉義字符時,與該字符匹配。\d+[\+-x\*]\d+\d+[\+-x\*\d+"(2+2) * 3*9" 中的 "2+2" 和 "3*9"

字符類

字符類與一組字符中的任何一個字符匹配。

下表列出了字符類:

字符類描述模式匹配
[character_group]匹配 character_group 中的任何單個字符。 默認情況下,匹配區分大小寫。[mn]"mat" 中的 "m","moon" 中的 "m" 和 "n"
[^character_group]非:與不在 character_group 中的任何單個字符匹配。 默認情況下,character_group 中的字符區分大小寫。[^aei]"avail" 中的 "v" 和 "l"
[ first - last ]字符範圍:與從 first 到 last 的範圍中的任何單個字符匹配。[b-d][b-d]irds 可以匹配 Birds、 Cirds、 Dirds
.通配符:與除 \n 之外的任何單個字符匹配。
若要匹配原意句點字符(. 或 \u002E),您必須在該字符前面加上轉義符 (\.)。
a.e"have" 中的 "ave", "mate" 中的 "ate"
\p{ name }name 指定的 Unicode 通用類別或命名塊中的任何單個字符匹配。\p{Lu} "City Lights" 中的 "C" 和 "L"
\P{ name }與不在 name 指定的 Unicode 通用類別或命名塊中的任何單個字符匹配。\P{Lu}"City" 中的 "i"、 "t" 和 "y"
\w與任何單詞字符匹配。\w"Room#1" 中的 "R"、 "o"、 "m" 和 "1"
\W與任何非單詞字符匹配。\W"Room#1" 中的 "#"
\s與任何空白字符匹配。\w\s"ID A1.3" 中的 "D "
\S與任何非空白字符匹配。\s\S"int __ctr" 中的 " _"
\d與任何十進製數字匹配。\d"4 = IV" 中的 "4"
\D匹配不是十進製數的任意字符。\D"4 = IV" 中的 " "、 "="、 " "、 "I" 和 "V"

定位點

定位點或原子零寬度斷言會使匹配成功或失敗,具體取決於字符串中的當前位置,但它們不會使引擎在字符串中前進或使用字符。

下表列出了定位點:

斷言描述模式匹配
^匹配必須從字符串或一行的開頭開始。^\d{3}"567-777-" 中的 "567"
$匹配必須出現在字符串的末尾或出現在行或字符串末尾的 \n 之前。-\d{4}$"8-12-2012" 中的 "-2012"
\A匹配必須出現在字符串的開頭。\A\w{4}"Code-007-" 中的 "Code"
\Z匹配必須出現在字符串的末尾或出現在字符串末尾的 \n 之前。-\d{3}\Z"Bond-901-007" 中的 "-007"
\z匹配必須出現在字符串的末尾。-\d{3}\z"-901-333" 中的 "-333"
\G匹配必須出現在上一個匹配結束的地方。\G\(\d\)"(1)(3)(5)[7](9)" 中的 "(1)"、 "(3)" 和 "(5)"
\b匹配一個單詞邊界,也就是指單詞和空格間的位置。er\b匹配"never"中的"er",但不能匹配"verb"中的"er"。
\B匹配非單詞邊界。er\B匹配"verb"中的"er",但不能匹配"never"中的"er"。

分組構造

分組構造描述了正則表達式的子表達式,通常用於捕獲輸入字符串的子字符串。

下表列出了分組構造:

分組構造描述模式匹配
( subexpression )捕獲匹配的子表達式併將其分配到一個從零開始的序號中。(\w)\1"deep" 中的 "ee"
(?< name >subexpression)將匹配的子表達式捕獲到一個命名組中。(?< double>\w)\k< double>"deep" 中的 "ee"
(?< name1 -name2 >subexpression)定義平衡組定義。(((?'Open'\()[^\(\)]*)+((?'Close-Open'\))[^\(\)]*)+)*(?(Open)(?!))$"3+2^((1-3)*(3-1))" 中的 "((1-3)*(3-1))"
(?: subexpression)定義非捕獲組。Write(?:Line)?"Console.WriteLine()" 中的 "WriteLine"
(?imnsx-imnsx:subexpression)應用或禁用 subexpression 中指定的選項。 A\d{2}(?i:\w+)\b"A12xl A12XL a12xl" 中的 "A12xl" 和 "A12XL"
(?= subexpression)零寬度正預測先行斷言。\w+(?=\.)"He is. The dog ran. The sun is out." 中的 "is"、 "ran" 和 "out"
(?! subexpression)零寬度負預測先行斷言。\b(?!un)\w+\b"unsure sure unity used" 中的 "sure" 和 "used"
(?<=subexpression)零寬度正回顧後發斷言。(?<=19)\d{2}\b"1851 1999 1950 1905 2003" 中的 "99"、"50"和 "05"
(?<! subexpression)零寬度負回顧後發斷言。(?"Hi woman Hi man" 中的 "man"
(?> subexpression)非回溯(也稱為"貪婪")子表達式。[13579](?>A+B+)"1ABB 3ABBC 5AB 5AC" 中的 "1ABB"、 "3ABB" 和 "5AB"

實例

using System;
using System.Text.RegularExpressions;
public class Example
{
   public static void Main()
   {
      string input = "1851 1999 1950 1905 2003";
      string pattern = @"(?<=19)\d{2}\b";
      foreach (Match match in Regex.Matches(input, pattern))
         Console.WriteLine(match.Value);
   }
}

限定符

限定符指定在輸入字符串中必須存在上一個元素(可以是字符、組或字符類)的多少個實例才能出現匹配項。 限定符包括下表中列出的語言元素。

下表列出了限定符:

限定符描述模式匹配
*匹配上一個元素零次或多次。\d*\.\d".0"、 "19.9"、 "219.9"
+匹配上一個元素一次或多次。"be+""been" 中的 "bee", "bent" 中的 "be"
?匹配上一個元素零次或一次。"rai?n""ran"、 "rain"
{ n }匹配上一個元素恰好 n 次。",\d{3}""1,043.6" 中的 ",043", "9,876,543,210" 中的 ",876"、 ",543" 和 ",210"
{ n ,}匹配上一個元素至少 n 次。"\d{2,}""166"、 "29"、 "1930"
{ n , m }匹配上一個元素至少 n 次,但不多於 m 次。"\d{3,5}""166", "17668", "193024" 中的 "19302"
*?匹配上一個元素零次或多次,但次數儘可能少。\d*?\.\d".0"、 "19.9"、 "219.9"
+?匹配上一個元素一次或多次,但次數儘可能少。"be+?""been" 中的 "be", "bent" 中的 "be"
??匹配上一個元素零次或一次,但次數儘可能少。"rai??n""ran"、 "rain"
{ n }?匹配前導元素恰好 n 次。",\d{3}?""1,043.6" 中的 ",043", "9,876,543,210" 中的 ",876"、 ",543" 和 ",210"
{ n ,}?匹配上一個元素至少 n 次,但次數儘可能少。"\d{2,}?""166"、 "29" 和 "1930"
{ n , m }?匹配上一個元素的次數介於 n 和 m 之間,但次數儘可能少。"\d{3,5}?""166", "17668", "193024" 中的 "193" 和 "024"

反向引用構造

反向引用允許在同一正則表達式中隨後標識以前匹配的子表達式。

下表列出了反向引用構造:

反向引用構造描述模式匹配
\ number反向引用。 匹配編號子表達式的值。(\w)\1"seek" 中的 "ee"
\k< name >命名反向引用。 匹配命名表達式的值。(?< char>\w)\k< char>"seek" 中的 "ee"

備用構造

備用構造用於修改正則表達式以啟用 either/or 匹配。

下表列出了備用構造:

備用構造描述模式匹配
|匹配以豎線 (|) 字符分隔的任何一個元素。th(e|is|at)"this is the day. " 中的 "the" 和 "this"
(?( expression )yes | no )如果正則表達式模式由 expression 匹配指定,則匹配 yes;否則匹配可選的 no 部分。 expression 被解釋為零寬度斷言。(?(A)A\d{2}\b|\b\d{3}\b)"A10 C103 910" 中的 "A10" 和 "910"
(?( name )yes | no )如果 name 或已命名或已編號的捕獲組具有匹配,則匹配 yes;否則匹配可選的 no(?< quoted>")?(?(quoted).+?"|\S+\s)"Dogs.jpg "Yiska playing.jpg"" 中的 Dogs.jpg 和 "Yiska playing.jpg"

替換

替換是替換模式中使用的正則表達式。

下表列出了用於替換的字符:

字符描述模式替換模式輸入字符串結果字符串
$number替換按組 number 匹配的子字符串。\b(\w+)(\s)(\w+)\b$3$2$1"one two""two one"
${name}替換按命名組 name 匹配的子字符串。\b(?< word1>\w+)(\s)(?< word2>\w+)\b${word2} ${word1}"one two""two one"
$$替換字符"$"。\b(\d+)\s?USD$$$1"103 USD""$103"
$&替換整個匹配項的一個副本。(\$*(\d*(\.+\d+)?){1})**$&"$1.30""**$1.30**"
$`替換匹配前的輸入字符串的所有文本。B+$`"AABBCC""AAAACC"
$'替換匹配後的輸入字符串的所有文本。B+$'"AABBCC""AACCCC"
$+替換最後捕獲的組。B+(C+)$+"AABBCCDD"AACCDD
$_替換整個輸入字符串。B+$_"AABBCC""AAAABBCCCC"

雜項構造

下表列出了各種雜項構造:

構造描述實例
(?imnsx-imnsx)在模式中間對諸如不區分大小寫這樣的選項進行設置或禁用。\bA(?i)b\w+\b 匹配 "ABA Able Act" 中的 "ABA" 和 "Able"
(?#注釋)內聯注釋。該注釋在第一個右括號處終止。\bA(?#匹配以A開頭的單詞)\w+\b
# [行尾]該注釋以非轉義的 # 開頭,併繼續到行的結尾。(?x)\bA\w+\b#匹配以 A 開頭的單詞

Regex 類

Regex 類用於表示一個正則表達式。

下表列出了 Regex 類中一些常用的方法:

序號方法 & 描述
1public bool IsMatch( string input )
指示 Regex 構造函數中指定的正則表達式是否在指定的輸入字符串中找到匹配項。
2public bool IsMatch( string input, int startat )
指示 Regex 構造函數中指定的正則表達式是否在指定的輸入字符串中找到匹配項,從字符串中指定的開始位置開始。
3public static bool IsMatch( string input, string pattern )
指示指定的正則表達式是否在指定的輸入字符串中找到匹配項。
4public MatchCollection Matches( string input )
在指定的輸入字符串中搜索正則表達式的所有匹配項。
5public string Replace( string input, string replacement )
在指定的輸入字符串中,把所有匹配正則表達式模式的所有匹配的字符串替換為指定的替換字符串。
6public string[] Split( string input )
把輸入字符串分割為子字符串數組,根據在 Regex 構造函數中指定的正則表達式模式定義的位置進行分割。

如需了解 Regex 類的完整的屬性列表,請參閱微軟的 C# 文檔。

實例 1

下面的實例匹配了以 'S' 開頭的單詞:

using System;
using System.Text.RegularExpressions;
namespace RegExApplication
{
   class Program
   {
      private static void showMatch(string text, string expr)
      {
         Console.WriteLine("The Expression: " + expr);
         MatchCollection mc = Regex.Matches(text, expr);
         foreach (Match m in mc)
         {
            Console.WriteLine(m);
         }
      }
      static void Main(string[] args)
      {
         string str = "A Thousand Splendid Suns";
         Console.WriteLine("Matching words that start with 'S': ");
         showMatch(str, @"\bS\S*");
         Console.ReadKey();
      }
   }
}

當上面的代碼被編譯和執行時,它會產生下列結果:

Matching words that start with 'S':
The Expression: \bS\S*
Splendid
Suns

實例 2

下面的實例匹配了以 'm' 開頭以 'e' 結尾的單詞:

using System;
using System.Text.RegularExpressions;
namespace RegExApplication
{
   class Program
   {
      private static void showMatch(string text, string expr)
      {
         Console.WriteLine("The Expression: " + expr);
         MatchCollection mc = Regex.Matches(text, expr);
         foreach (Match m in mc)
         {
            Console.WriteLine(m);
         }
      }
      static void Main(string[] args)
      {
         string str = "make maze and manage to measure it";
         Console.WriteLine("Matching words start with 'm' and ends with 'e':");
         showMatch(str, @"\bm\S*e\b");
         Console.ReadKey();
      }
   }
}

當上面的代碼被編譯和執行時,它會產生下列結果:

Matching words start with 'm' and ends with 'e':
The Expression: \bm\S*e\b
make
maze
manage
measure

實例 3

下面的實例替換掉多余的空格:

using System;
using System.Text.RegularExpressions;
namespace RegExApplication
{
   class Program
   {
      static void Main(string[] args)
      {
         string input = "Hello   World   ";
         string pattern = "\\s+";
         string replacement = " ";
         Regex rgx = new Regex(pattern);
         string result = rgx.Replace(input, replacement);
         Console.WriteLine("Original String: {0}", input);
         Console.WriteLine("Replacement String: {0}", result);    
         Console.ReadKey();
      }
   }
}

當上面的代碼被編譯和執行時,它會產生下列結果:

Original String: Hello   World   
Replacement String: Hello World   
北斗有巢氏 有巢氏北斗