Regex.GetGroupNumbers 方法

定义

返回与数组中的组名相对应的捕获组号的数组。

C#
public int[] GetGroupNumbers ();

返回

Int32[]

组号的整数数组。

示例

以下示例定义与句子匹配的正则表达式 \b((?<word>\w+)\s*)+(?<end>[.?!])。 正则表达式包含三个捕获组:一个未命名的组,该组捕获单个单词以及可能遵循它的空格字符:一个名为捕获句子中各个单词的组 word ,以及一个名为 end 捕获结束句子的标点符号的组。 该示例调用 GetGroupNumbers 该方法以获取所有捕获组的数目,然后显示其捕获的字符串。 此外, GroupNameFromNumber 该方法用于指示特定编号组是否与命名组相对应。

C#
using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"\b((?<word>\w+)\s*)+(?<end>[.?!])";
      string input = "This is a sentence. This is a second sentence.";
      
      Regex rgx = new Regex(pattern);
      int[] groupNumbers = rgx.GetGroupNumbers();
      Match m = rgx.Match(input);
      if (m.Success) {
         Console.WriteLine("Match: {0}", m.Value);
         foreach (var groupNumber in groupNumbers) {
            string name = rgx.GroupNameFromNumber(groupNumber);
            int number;
            Console.WriteLine("   Group {0}{1}: '{2}'", 
                              groupNumber, 
                              ! string.IsNullOrEmpty(name) & 
                              ! Int32.TryParse(name, out number) ?
                                 " (" + name + ")" : String.Empty, 
                              m.Groups[groupNumber].Value);
         }
      } 
   }
}
// The example displays the following output:
//       Match: This is a sentence.
//          Group 0: 'This is a sentence.'
//          Group 1: 'sentence'
//          Group 2 (word): 'sentence'
//          Group 3 (end): '.'

正则表达式模式可以解释为下表中所示内容。

模式 描述
\b 在单词边界处开始匹配。
(?<word>\w+) 匹配一个或多个单词字符,并将匹配的字符串分配给名为 word的组。
\s* 匹配零个或多个空白字符。
((?<word>\w+)\s*) 将捕获的 word 组后跟任何捕获的空白字符分配给第一个捕获的组。
((?<word>\w+)\s*)+ 匹配一个或多个单词字符的模式,后跟任意空格字符一次或多次。
(?<end>[.?!]) 匹配句号、问号或感叹号。 将匹配的字符分配给 end 捕获组。

注解

可以通过数字访问未命名和命名捕获组。 从 1 开始,从左到右对未命名组进行编号。 (索引 0 (零) 中的捕获组表示整个匹配项。) 命名组从左到右编号,以一个大于未命名捕获组数的数字开始编号。

按组编号而不是字符串名称引用组可以提供更快的访问速度。

适用于

产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

另请参阅