C#正則運算式

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

定義正則運算式的構造

有各種類型的字元,運算符和結構,可以讓您用來定義正則運算式。點擊以下鏈接查找這些結構。

Regex類

正則運算式 - Regex 類用於表示正則運算式。 它有以下常用的方法:

序號 方法 描述
1 public bool IsMatch(string input) 指示在正則運算式構造函數中指定的正則運算式是否在指定的輸入字串中找到匹配項。
2 public bool IsMatch(string input, int startat) 指示在正則運算式構造函數中指定的正則運算式是否在指定的輸入字串(input)中找到匹配,從字串中指定的起始(startat)位置開始。
3 public static bool IsMatch(string input, string pattern) 在指定的正則運算式是否在指定的輸入字串中找到匹配項。
4 public MatchCollection Matches(string input) 搜索所有出現正則運算式的指定輸入字串。
5 public string Replace(string input, string replacement) 在指定的輸入字串中,將與正則運算式模式匹配的所有字串替換為指定的替換字串(replacementreplacement)。
6 public string[] Split(string input) 將輸入字串拆分為由正則運算式構造函數中指定的正則運算式模式定義的位置的子字串數組。

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

上一篇: C#預處理指令 下一篇: C#異常處理