Regex.GroupNameFromNumber(Int32) 메서드

정의

지정된 그룹 번호에 해당하는 그룹 이름을 가져옵니다.

public:
 System::String ^ GroupNameFromNumber(int i);
public string GroupNameFromNumber (int i);
member this.GroupNameFromNumber : int -> string
Public Function GroupNameFromNumber (i As Integer) As String

매개 변수

i
Int32

해당 그룹 이름으로 변환할 그룹 번호입니다.

반환

지정된 그룹 번호에 연결되어 있는 그룹 이름이 포함된 문자열입니다. i에 해당하는 그룹 이름이 없는 경우 이 메서드는 Empty를 반환합니다.

예제

다음 예제에서는 미국 도시 이름, 주 이름 및 우편 번호를 포함하는 주소 줄과 일치하는 정규식 패턴을 정의합니다. 이 예제에서는 메서드를 GroupNameFromNumber 사용하여 캡처링 그룹의 이름을 검색합니다. 그런 다음 이러한 이름을 사용하여 일치 항목에 대해 해당 캡처된 그룹을 검색합니다.

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"(?<city>[A-Za-z\s]+), (?<state>[A-Za-z]{2}) (?<zip>\d{5}(-\d{4})?)";
      string[] cityLines = {"New York, NY 10003", "Brooklyn, NY 11238", "Detroit, MI 48204", 
                            "San Francisco, CA 94109", "Seattle, WA 98109" };
      Regex rgx = new Regex(pattern);
      List<string> names = new List<string>();
      int ctr = 1;
      bool exitFlag = false;
      // Get group names.
      do {
         string name = rgx.GroupNameFromNumber(ctr);
         if (! String.IsNullOrEmpty(name))
         {
            ctr++;
            names.Add(name);
         }
         else
         {
            exitFlag = true;
         }
      } while (! exitFlag);

      foreach (string cityLine in cityLines)
      {
         Match match = rgx.Match(cityLine);
         if (match.Success)
            Console.WriteLine("Zip code {0} is in {1}, {2}.", 
                               match.Groups[names[3]], 
                               match.Groups[names[1]], 
                               match.Groups[names[2]]);
      } 
   }
}
// The example displays the following output:
//       Zip code 10003 is in New York, NY.
//       Zip code 11238 is in Brooklyn, NY.
//       Zip code 48204 is in Detroit, MI.
//       Zip code 94109 is in San Francisco, CA.
//       Zip code 98109 is in Seattle, WA.
Imports System.Collections.Generic
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = "(?<city>[A-Za-z\s]+), (?<state>[A-Za-z]{2}) (?<zip>\d{5}(-\d{4})?)"
      Dim cityLines() As String = {"New York, NY 10003", "Brooklyn, NY 11238", "Detroit, MI 48204", _
                                   "San Francisco, CA 94109", "Seattle, WA 98109" }
      Dim rgx As New Regex(pattern)
      Dim names As New List(Of String)      
      Dim ctr As Integer = 1
      Dim exitFlag As Boolean = False
      ' Get group names.
      Do 
         Dim name As String = rgx.GroupNameFromNumber(ctr)
         If Not String.IsNullOrEmpty(name) Then
            ctr += 1
            names.Add(name)
         Else
            exitFlag = True
         End If
      Loop While Not exitFlag
      
      For Each cityLine As String In cityLines
         Dim match As Match = rgx.Match(cityLine)
         If match.Success Then
            Console.WriteLine("Zip code {0} is in {1}, {2}.", _
                               match.Groups.Item(names.Item(3)), _
                               match.Groups.Item(names.Item(1)), _
                               match.Groups.Item(names.Item(2)))
         End If   
      Next 
   End Sub
End Module
' The example displays the following output:
'       Zip code 10003 is in New York, NY.
'       Zip code 11238 is in Brooklyn, NY.
'       Zip code 48204 is in Detroit, MI.
'       Zip code 94109 is in San Francisco, CA.
'       Zip code 98109 is in Seattle, WA.

정규식 패턴은 다음 식으로 정의됩니다.

(?<city>[A-Za-z\s]+), (?<state>[A-Za-z]{2}) (?<zip>\d{5}(-\d{4})?)

다음 테이블은 정규식 패턴이 해석되는 방법을 보여 줍니다.

무늬 설명
(?<city>[A-Za-z\s]+) 하나 이상의 알파벳 또는 공백 문자를 찾습니다. 캡처된 이 그룹에 이름을 city할당합니다.
, 쉼표(,)와 공백 문자를 찾습니다.
(?<state>[A-Za-z]{2}) 두 개의 사전순 문자를 일치합니다. 캡처된 이 그룹에 이름을 state할당합니다. 이 그룹 뒤에 공백 문자가 있어야 합니다.
(?<zip>\d{5}(-\d{4})?) 숫자 5개와 하이픈 0개 또는 1개, 숫자 4개를 찾습니다. 캡처된 이 그룹에 이름을 zip할당합니다.

설명

정규식 패턴에는 패턴 일치 내에서 하위 식이 구분되는 명명된 또는 번호가 매겨진 캡처링 그룹이 포함될 수 있습니다. 번호가 매겨진 그룹은 구문(하위 식)으로 구분되며 정규식의 순서에 따라 숫자가 할당됩니다. 명명된 그룹은 구문으로 구분됩니다(?<이름>subexpression) 또는 (?' name'subexpression) 여기서 name은 하위 식이 식별될 이름입니다. (자세한 내용은 그룹화 구문을 참조하세요.) 메서드는 GroupNameFromNumber 정규식의 서수 위치로 명명된 그룹과 번호가 매겨진 그룹을 모두 식별합니다. 서수 위치 0은 항상 전체 정규식을 나타냅니다. 그런 다음 정규식 패턴의 실제 위치에 관계없이 모든 번호가 매겨진 그룹이 명명된 그룹 앞에 계산됩니다.

가 명명된 그룹의 수이면 i 메서드는 그룹의 이름을 반환합니다. 가 명명되지 않은 그룹의 수이면 i 메서드는 숫자의 문자열 표현을 반환합니다. 예를 들어 가 1이면 i 메서드는 "1"을 반환합니다. 가 i 캡처링 그룹의 수가 아니면 메서드는 를 반환합니다 String.Empty.

패턴 일치가 발견되면 이 메서드에서 반환된 값을 사용하여 속성에서 GroupCollection.Item[] 캡처된 그룹을 나타내는 개체를 검색 Group 할 수 있습니다. 개체는 GroupCollection 속성에 의해 반환됩니다 Match.Groups .

적용 대상

추가 정보