Match 클래스

정의

정규식으로 찾은 단일 일치 항목의 결과를 나타냅니다.

public ref class Match : System::Text::RegularExpressions::Group
public class Match : System.Text.RegularExpressions.Group
[System.Serializable]
public class Match : System.Text.RegularExpressions.Group
type Match = class
    inherit Group
[<System.Serializable>]
type Match = class
    inherit Group
Public Class Match
Inherits Group
상속
특성

예제

다음 예제에서는 정규식을 Console\.Write(Line)?사용합니다. 정규식은 다음과 같이 해석됩니다.

콘솔\. 쓰기 "Console.Write"라는 문자열을 찾습니다. "." 문자는 모든 문자와 일치하는 와일드카드가 아닌 리터럴 마침표로 해석되도록 이스케이프됩니다.
(선)? "Line"이라는 0개 또는 1개의 문자열을 찾습니다.

예제 1

다음 예제에서는 메서드를 Regex.Matches(String, String) 호출하여 입력 문자열의 모든 패턴 일치 항목을 검색합니다. 그런 다음 반환 MatchCollection 된 개체의 Match 개체를 반복하여 각 일치 항목에 대한 정보를 표시합니다.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "int[] values = { 1, 2, 3 };\n" +
                     "for (int ctr = values.GetLowerBound(1); ctr <= values.GetUpperBound(1); ctr++)\n" +
                     "{\n" +
                     "   Console.Write(values[ctr]);\n" +
                     "   if (ctr < values.GetUpperBound(1))\n" +
                     "      Console.Write(\", \");\n" +
                     "}\n" +
                     "Console.WriteLine();\n";   
      
      string pattern = @"Console\.Write(Line)?";
      MatchCollection matches = Regex.Matches(input, pattern);
      foreach (Match match in matches)
         Console.WriteLine("'{0}' found in the source code at position {1}.",  
                           match.Value, match.Index);
   }
}
// The example displays the following output:
//    'Console.Write' found in the source code at position 112.
//    'Console.Write' found in the source code at position 184.
//    'Console.WriteLine' found in the source code at position 207.
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "Dim values() As Integer = { 1, 2, 3 }" & vbCrLf & _
                            "For ctr As Integer = values.GetLowerBound(1) To values.GetUpperBound(1)" & vbCrLf & _
                            "   Console.Write(values(ctr))" & vbCrLf & _
                            "   If ctr < values.GetUpperBound(1) Then Console.Write("", "")" & vbCrLf & _
                            "Next" & vbCrLf & _
                            "Console.WriteLine()"   
      Dim pattern As String = "Console\.Write(Line)?"
      Dim matches As MatchCollection = Regex.Matches(input, pattern)
      For Each match As Match In matches
         Console.WriteLine("'{0}' found in the source code at position {1}.", _ 
                           match.Value, match.Index)       
      Next                            
   End Sub
End Module
' The example displays the following output:
'    'Console.Write' found in the source code at position 115.
'    'Console.Write' found in the source code at position 184.
'    'Console.WriteLine' found in the source code at position 211.

예제 2

다음 예제에서는 한 번에 하나의 일치 항목을 검색하는 메서드 및 NextMatch 메서드를 호출 Match(String, String) 합니다.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "int[] values = { 1, 2, 3 };\n" +
                     "for (int ctr = values.GetLowerBound(1); ctr <= values.GetUpperBound(1); ctr++)\n" +
                     "{\n" +
                     "   Console.Write(values[ctr]);\n" +
                     "   if (ctr < values.GetUpperBound(1))\n" +
                     "      Console.Write(\", \");\n" +
                     "}\n" +
                     "Console.WriteLine();\n";   
      string pattern = @"Console\.Write(Line)?";
      Match match = Regex.Match(input, pattern);
      while (match.Success)
      {
         Console.WriteLine("'{0}' found in the source code at position {1}.",  
                           match.Value, match.Index);
         match = match.NextMatch();
      }
   }
}
// The example displays the following output:
//    'Console.Write' found in the source code at position 112.
//    'Console.Write' found in the source code at position 184.
//    'Console.WriteLine' found in the source code at position 207.
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "Dim values() As Integer = { 1, 2, 3 }" & vbCrLf & _
                            "For ctr As Integer = values.GetLowerBound(1) To values.GetUpperBound(1)" & vbCrLf & _
                            "   Console.Write(values(ctr))" & vbCrLf & _
                            "   If ctr < values.GetUpperBound(1) Then Console.Write("", "")" & vbCrLf & _
                            "Next" & vbCrLf & _
                            "Console.WriteLine()"   
      Dim pattern As String = "Console\.Write(Line)?"
      Dim match As Match = Regex.Match(input, pattern)
      Do While match.Success
         Console.WriteLine("'{0}' found in the source code at position {1}.", _ 
                           match.Value, match.Index)
         match = match.NextMatch()                  
      Loop                            
   End Sub
End Module
' The example displays the following output:
'    'Console.Write' found in the source code at position 115.
'    'Console.Write' found in the source code at position 184.
'    'Console.WriteLine' found in the source code at position 211.

설명

Match 개체는 변경할 수 없으며 공용 생성자가 없습니다. 클래스의 Match 인스턴스는 메서드에서 Regex.Match 반환되며 문자열의 첫 번째 패턴 일치를 나타냅니다. 이후 일치 항목은 메서드에서 Match 반환된 개체로 Match.NextMatch 표시됩니다. 또한 0개 MatchCollection , 1개 이상의 Match 개체로 구성된 개체가 메서드에서 Regex.Matches 반환됩니다.

메서드가 Regex.Matches 입력 문자열의 정규식 패턴과 일치하지 않으면 빈 MatchCollection 개체를 반환합니다. 그런 다음 C#의 foreach 구문 또는 For Each Visual Basic 구문을 사용하여 컬렉션을 반복할 수 있습니다.

메서드가 Regex.Match 정규식 패턴과 일치하지 않으면 동일한 Match.Empty개체를 Match 반환합니다. 속성을 Success 사용하여 일치가 성공했는지 여부를 확인할 수 있습니다. 다음 예제에서 이에 대해 설명합니다.

// Search for a pattern that is not found in the input string.
string pattern = "dog";
string input = "The cat saw the other cats playing in the back yard.";
Match match = Regex.Match(input, pattern);
if (match.Success )
   // Report position as a one-based integer.
   Console.WriteLine("'{0}' was found at position {1} in '{2}'.", 
                     match.Value, match.Index + 1, input);
else
   Console.WriteLine("The pattern '{0}' was not found in '{1}'.",
                     pattern, input);
' Search for a pattern that is not found in the input string.
Dim pattern As String = "dog"
Dim input As String = "The cat saw the other cats playing in the back yard."
Dim match As Match = Regex.Match(input, pattern)
If match.Success Then
   ' Report position as a one-based integer.
   Console.WriteLine("'{0}' was found at position {1} in '{2}'.", _ 
                     match.Value, match.Index + 1, input)
Else
   Console.WriteLine("The pattern '{0}' was not found in '{1}'.", _
                     pattern, input)
End If

패턴 일치에 성공 Value 하면 속성에 일치하는 부분 문자열이 포함되고, Index 속성은 입력 문자열에서 일치하는 부분 문자열의 시작 위치(0부터 시작)를 나타내고 Length , 속성은 입력 문자열에서 일치하는 부분 문자열의 길이를 나타냅니다.

단일 일치 항목에는 여러 캡처링 그룹이 Match Groups 포함될 수 있으므로 해당 항목을 반환 GroupCollection하는 속성이 있습니다. Match 인스턴스 자체는 전체 일치 항목을 나타내는 컬렉션의 첫 번째 개체(Match.Groups[0]``Match.Groups(0)Visual Basic)에 해당합니다. 다음과 같은 방법으로 일치하는 방식으로 캡처된 그룹에 액세스할 수 있습니다.

  • (C#) 또는 For Each (Visual Basic) 구문을 사용하여 foreach 개체의 GroupCollection 멤버를 반복할 수 있습니다.

  • GroupCollection.Item[Int32] 속성을 사용하여 캡처링 그룹의 수만큼 그룹을 검색할 수 있습니다. 인스턴스 Regex.GetGroupNumbers 메서드를 호출하여 정규식에 있는 번호가 매겨진 그룹을 확인할 수 있습니다.

  • 이 속성을 사용하여 GroupCollection.Item[String] 캡처링 그룹의 이름으로 그룹을 검색할 수 있습니다. 인스턴스 Regex.GetGroupNames() 메서드를 호출하여 정규식에 있는 명명된 그룹을 확인할 수 있습니다.

속성

Captures

안쪽-왼쪽 우선 순서로 캡처링 그룹을 사용하여 일치시킨 모든 캡처의 컬렉션을 가져옵니다. 정규식을 RightToLeft 옵션으로 수정한 경우에는 안쪽-오른쪽 우선 순서로 가져올 수 있습니다. 컬렉션에는 0이상의 항목이 있을 수 있습니다.

(다음에서 상속됨 Group)
Empty

빈 그룹을 가져옵니다. 일치 항목을 찾지 못하는 모든 경우에는 이 빈 일치 항목이 반환됩니다.

Groups

정규식으로 일치시킨 그룹의 컬렉션을 가져옵니다.

Index

원래 문자열에서 캡처된 부분 문자열의 첫째 문자를 찾은 위치입니다.

(다음에서 상속됨 Capture)
Length

캡처된 부분 문자열의 길이를 가져옵니다.

(다음에서 상속됨 Capture)
Name

현재 인스턴스로 표시되는 캡처링 그룹의 이름을 반환합니다.

(다음에서 상속됨 Group)
Success

일치 작업이 성공적이었는지 여부를 나타내는 값을 가져옵니다.

(다음에서 상속됨 Group)
Value

입력 문자열에서 캡처된 부분 문자열을 가져옵니다.

(다음에서 상속됨 Capture)
ValueSpan

입력 문자열에서 캡처된 범위를 가져옵니다.

(다음에서 상속됨 Capture)

메서드

Equals(Object)

지정된 개체가 현재 개체와 같은지 확인합니다.

(다음에서 상속됨 Object)
GetHashCode()

기본 해시 함수로 작동합니다.

(다음에서 상속됨 Object)
GetType()

현재 인스턴스의 Type을 가져옵니다.

(다음에서 상속됨 Object)
MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
NextMatch()

마지막 일치 항목이 끝나는 위치(마지막으로 일치한 문자 다음 문자)에서 시작하여 다음 일치 항목에 대한 결과와 함께 새로운 Match 개체를 반환합니다.

Result(String)

지정된 바꾸기 패턴의 확장을 반환합니다.

Synchronized(Match)

여러 스레드 간에 공유하기에 적합하고 제공된 인스턴스와 동등한 Match 인스턴스를 반환합니다.

ToString()

Value 속성을 호출하여 입력 문자열로부터 캡처된 하위 문자열을 검색합니다.

(다음에서 상속됨 Capture)

적용 대상

추가 정보