正则表达式:如何获取组名

8 .net regex

我有一个.NET Regex,看起来类似于:

(?<Type1>AAA)|(?<Type2>BBB)
Run Code Online (Sandbox Code Playgroud)

我正在对样本字符串使用Matches方法,例如"AAABBBAAA",然后迭代匹配.

我的目标是使用正则表达式匹配组找到匹配类型,因此对于此正则表达式,它将是:

  • 类型1
  • 类型2
  • 类型1

我找不到任何GetGroupName方法.请帮忙.

Jon*_*eet 17

这是你正在寻找的那种东西吗?它使用,Regex.GroupNameFromNumber所以你不需要知道正则表达式本身之外的组名.

using System;
using System.Text.RegularExpressions;

class Test
{
    static void Main()
    {
        Regex regex = new Regex("(?<Type1>AAA)|(?<Type2>BBB)");
        foreach (Match match in regex.Matches("AAABBBAAA"))
        {
            Console.WriteLine("Next match:");
            GroupCollection collection = match.Groups;
            // Note that group 0 is always the whole match
            for (int i = 1; i < collection.Count; i++)
            {
                Group group = collection[i];
                string name = regex.GroupNameFromNumber(i);
                Console.WriteLine("{0}: {1} {2}", name, 
                                  group.Success, group.Value);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Eri*_*ver 7

如果要检索特定组名,可以使用该方法.Regex.GroupNameFromNumber

//regular expression with a named group
Regex regex = new Regex(@"(?<Type1>AAA)|(?<Type2>BBB)", RegexOptions.Compiled);

//evaluate results of Regex and for each match
foreach (Match m in regex.Matches("AAABBBAAA"))
{
    //loop through all the groups in current match
    for(int x = 1; x < m.Groups.Count; x ++)
    {
        //print the names wherever there is a succesful match
        if(m.Group[x].Success)
            Console.WriteLine(regex.GroupNameFromNumber(x));
    }
}
Run Code Online (Sandbox Code Playgroud)

另外,还有一个字符串索引器GroupCollection.在属性上可访问的对象,这允许您按名称而不是索引访问匹配中的组.Match.Groups

//regular expression with a named group
Regex regex = new Regex(@"(?<Type1>AAA)|(?<Type2>BBB)", RegexOptions.Compiled);

//evaluate results of Regex and for each match
foreach (Match m in regex.Matches("AAABBBAAA"))
{
    //print the value of the named group
    if(m.Groups["Type1"].Success)
        Console.WriteLine(m.Groups["Type1"].Value);
    if(m.Groups["Type2"].Success)
        Console.WriteLine(m.Groups["Type2"].Value);
}
Run Code Online (Sandbox Code Playgroud)