正则表达式:如何获取组名 [英] Regex: How to get a group name

查看:47
本文介绍了正则表达式:如何获取组名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.NET正则表达式,其外观类似于:

I have a .NET Regex which looks similar to:

(?<Type1>AAA)|(?<Type2>BBB)

我正在针对样本字符串使用 Matches 方法,例如"AAABBBAAA" ,然后遍历所有匹配项.

I'm using the Matches method against a sample string e.g. "AAABBBAAA", and then iterating over the matches.

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

My goal is to find the match types, using the regex match group, so for this regex it will be:

  • Type1
  • Type2
  • Type1

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

I couldn't find any GetGroupName method. Please help.

推荐答案

这是您要找的东西吗?它使用 Regex.GroupNameFromNumber ,因此您无需知道正则表达式本身之外的组名.

Is this the sort of thing you're looking for? It uses Regex.GroupNameFromNumber so you don't need to know the group names outside the regex itself.

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);
            }
        }
    }
}

这篇关于正则表达式:如何获取组名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆