Computer >> Máy Tính >  >> Lập trình >> C#

Làm cách nào để tìm một chuỗi con phù hợp bằng cách sử dụng biểu thức chính quy trong C #?

Chuỗi của chúng tôi là -

string str = " My make ";

Sử dụng biểu thức chính quy sau để tìm chuỗi con “make”

@"\bmake\b"

Đây là mã hoàn chỉnh -

Ví dụ

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");
      }
   }
}

Đầu ra

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