C# - 正則表示式



正則表示式是一種可以與輸入文字匹配的模式。.Net 框架提供了一個正則表示式引擎,允許進行這種匹配。模式由一個或多個字元字面量、運算子或構造組成。

定義正則表示式的構造

有各種型別的字元、運算子和構造可以讓你定義正則表示式。點選以下連結查詢這些構造。

Regex 類

Regex 類用於表示正則表示式。它具有以下常用方法:

序號 方法和描述
1

public bool IsMatch(string input)

指示在 Regex 建構函式中指定的正則表示式是否在指定的輸入字串中找到匹配項。

2

public bool IsMatch(string input, int startat)

指示在 Regex 建構函式中指定的正則表示式是否在指定的輸入字串中找到匹配項,從字串中的指定起始位置開始。

3

public static bool IsMatch(string input, string pattern)

指示指定的正則表示式是否在指定的輸入字串中找到匹配項。

4

public MatchCollection Matches(string input)

搜尋指定的輸入字串中正則表示式的所有出現。

5

public string Replace(string input, string replacement)

在指定的輸入字串中,將與正則表示式模式匹配的所有字串替換為指定的替換字串。

6

public string[] Split(string input)

根據 Regex 建構函式中指定的正則表示式模式定義的位置,將輸入字串拆分為子字串陣列。

有關方法和屬性的完整列表,請閱讀 Microsoft 的 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   
廣告