Regex.GetGroupNames 方法   
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
返回正则表达式的捕获组名数组。
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命名组。 | 
注解
组名称的集合包含用于命名表达式中捕获组的字符串集。 即使捕获组未显式命名,它们也会自动 (“0”、“1”、“2”、“3”等) 分配数字名称。 命名组表示正则表达式模式匹配的所有文本。 在集合中显式命名的组之前,命名组按正则表达式模式中定义的顺序显示。
可以使用 Length 此方法返回的数组的属性来确定正则表达式中的组数。