如何在 C# 中使用正则表达式查找匹配的子字符串?

csharpprogrammingserver side programming更新于 2025/6/2 2:52:17

我们的字符串是 −

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

相关文章