Computer >> 컴퓨터 >  >> 프로그램 작성 >> C#

Regex를 사용한 C#의 패턴 일치


정규 표현식은 입력 텍스트와 일치할 수 있는 패턴입니다. 패턴은 하나 이상의 문자 리터럴, 연산자 또는 구성으로 구성됩니다.

정규식을 사용하여 문자 '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*