用 Regex 在 C# 中進行模式匹配


正則表示式是一種可以與輸入文字進行匹配的模式。模式由一個或多個字元字面值、運算子或結構組成。

讓我們看一個使用 Regex 顯示以字母“M”開頭的單詞的示例。

示例

 現場演示

using System;
using System.Text.RegularExpressions;

namespace Demo {
   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 = "Mandatory requirements for a Cricket Match Event!";

         Console.WriteLine("Matching words that start with 'M': ");
         showMatch(str, @"\bM\S*");
         Console.ReadKey();
      }
   }
}

輸出

Matching words that start with 'M':
The Expression: \bM\S*
Mandatory
Match

上面是我的字串。

string str = "Mandatory requirements for a Cricket Match Event!";

為了獲得所有以“M”開頭的單詞,我使用了以下模式 -

@"\bM\S*


更新於: 2020 年 6 月 22 日

359 次瀏覽

開啟您的 事業

完成課程,獲得認證

開始
廣告
© . All rights reserved.