Regex.GetGroupNames 方法

定義

傳回規則運算式的擷取群組名稱的陣列。

public:
 cli::array <System::String ^> ^ GetGroupNames();
public string[] GetGroupNames ();
member this.GetGroupNames : unit -> string[]
Public Function GetGroupNames () As String()

傳回

String[]

群組名稱的字串陣列。

範例

下列範例會定義一般用途 ShowMatches 方法,以顯示正則運算式群組的名稱及其相符的文字。

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"\b(?<FirstWord>\w+)\s?((\w+)\s)*(?<LastWord>\w+)?(?<Punctuation>\p{Po})";
      string input = "The cow jumped over the moon.";
      Regex rgx = new Regex(pattern);
      Match match = rgx.Match(input);
      if (match.Success)
         ShowMatches(rgx, match);
   }

   private static void ShowMatches(Regex r, Match m)
   {
      string[] names = r.GetGroupNames();
      Console.WriteLine("Named Groups:");
      foreach (var name in names) {
         Group grp = m.Groups[name];
         Console.WriteLine("   {0}: '{1}'", name, grp.Value);
      }
   }
}
// The example displays the following output:
//       Named Groups:
//          0: 'The cow jumped over the moon.'
//          1: 'the '
//          2: 'the'
//          FirstWord: 'The'
//          LastWord: 'moon'
//          Punctuation: '.'
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = "\b(?<FirstWord>\w+)\s?((\w+)\s)*(?<LastWord>\w+)?(?<Punctuation>\p{Po})"
      Dim input As String = "The cow jumped over the moon."
      Dim rgx As New Regex(pattern)
      Dim match As Match = rgx.Match(input)
      If match.Success Then ShowMatches(rgx, match)
   End Sub
   
   Private Sub ShowMatches(r As Regex, m As Match)
      Dim names() As String = r.GetGroupNames()
      Console.WriteLine("Named Groups:")
      For Each name In names
         Dim grp As Group = m.Groups.Item(name)
         Console.WriteLine("   {0}: '{1}'", name, grp.Value)
      Next
   End Sub
End Module
' The example displays the following output:
'       Named Groups:
'          0: 'The cow jumped over the moon.'
'          1: 'the '
'          2: 'the'
'          FirstWord: 'The'
'          LastWord: 'moon'
'          Punctuation: '.'

在此情況下,正則運算式模式 \b(?<FirstWord>\w+)\s?((\w+)\s)*(?<LastWord>\w+)?(?<Punctuation>\p{Po}) 旨在剖析簡單的句子,並識別其第一個單字、最後一個字和結尾標點符號。 下表顯示如何解譯正則運算式模式:

模式 描述
\b 開始字緣比對。
(?<FirstWord>\w+) 比對一個或多個文字字元。 這是 FirstWord 具名群組。
\s? 比對零個或一個空白字元。
(\w+) 比對一個或多個文字字元。 這是第二個擷取群組。
\s 比對空白字元。
( (\w+) \s) * 比對一或多個文字字元的零或多個出現次數,後面接著空白字元。 這是第一個擷取群組。
(? <LastWord>\w+) ? 比對零或一次出現的一或多個單字字元。 這是 LastWord 具名群組。
(? <Punctuation>\p{Po}) 比對 Unicode 類別為 Punctuation、Other 的字元。 這是 Punctuation 具名群組。

備註

組名的集合包含用來命名運算式中擷取群組的字串集合。 即使未明確命名擷取群組,它們仍會自動指派 (「0」、「1」、「2」、「3」 等) 。 「0」 具名群組代表正則運算式模式所比對的所有文字。 編號群組在集合中明確命名的群組之前,且具名群組會以正則運算式模式中定義的順序顯示。

您可以使用 Length 這個方法所傳回陣列上的 屬性來判斷正則運算式中的群組數目。

適用於

另請參閱