如何使用 C# 中的正則表示式查詢匹配的子字串?


我們的字串是 -

string str = " My make ";

使用以下正則表示式查詢子字串“make”

@"\bmake\b"

以下是完整程式碼 -

示例

即時演示

using System;
using System.Text.RegularExpressions;

namespace RegExApplication {
   public 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("Found:" + m);
         }
      }

      public static void Main(string[] args) {
         string str = "My make";

         Console.WriteLine("Matching words start with 'm' and ends with 'e':");
         showMatch(str, @"\bmake\b");
      }
   }
}

輸出

Matching words start with 'm' and ends with 'e':
The Expression: \bmake\b
Found:make

更新於: 30-七月-2019

1000+ 次瀏覽

啟動你的 職業生涯

完成課程並獲得認證

開始
廣告