如何在 C# 正则表达式中获取捕获组的名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1381097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 15:52:45  来源:igfitidea点击:

How do I get the name of captured groups in a C# Regex?

c#regex

提问by Luiz Damim

Is there a way to get the name of a captured group in C#?

有没有办法在 C# 中获取捕获组的名称?

string line = "No.123456789  04/09/2009  999";
Regex regex = new Regex(@"(?<number>[\d]{9})  (?<date>[\d]{2}/[\d]{2}/[\d]{4})  (?<code>.*)");

GroupCollection groups = regex.Match(line).Groups;

foreach (Group group in groups)
{
    Console.WriteLine("Group: {0}, Value: {1}", ???, group.Value);
}

I want to get this result:

我想得到这个结果:

Group: [I don′t know what should go here], Value: 123456789  04/09/2009  999
Group: number, Value: 123456789
Group: date,   Value: 04/09/2009
Group: code,   Value: 999

采纳答案by Jeff Yates

Use GetGroupNamesto get the list of groups in an expression and then iterate over those, using the names as keys into the groups collection.

使用GetGroupNames获取表达式中的组列表,然后迭代这些组,使用名称作为组集合的键。

For example,

例如,

GroupCollection groups = regex.Match(line).Groups;

foreach (string groupName in regex.GetGroupNames())
{
    Console.WriteLine(
       "Group: {0}, Value: {1}",
       groupName,
       groups[groupName].Value);
}

回答by Eran Betzalel

You should use GetGroupNames();and the code will look something like this:

您应该使用GetGroupNames();,代码将如下所示:

    string line = "No.123456789  04/09/2009  999";
    Regex regex = 
        new Regex(@"(?<number>[\d]{9})  (?<date>[\d]{2}/[\d]{2}/[\d]{4})  (?<code>.*)");

    GroupCollection groups = regex.Match(line).Groups;

    var grpNames = regex.GetGroupNames();

    foreach (var grpName in grpNames)
    {
        Console.WriteLine("Group: {0}, Value: {1}", grpName, groups[grpName].Value);
    }

回答by whitneyland

The cleanest way to do this is by using this extension method:

最简洁的方法是使用此扩展方法:

public static class MyExtensionMethods
{
    public static Dictionary<string, string> MatchNamedCaptures(this Regex regex, string input)
    {
        var namedCaptureDictionary = new Dictionary<string, string>();
        GroupCollection groups = regex.Match(input).Groups;
        string [] groupNames = regex.GetGroupNames();
        foreach (string groupName in groupNames)
            if (groups[groupName].Captures.Count > 0)
                namedCaptureDictionary.Add(groupName,groups[groupName].Value);
        return namedCaptureDictionary;
    }
}


Once this extension method is in place, you can get names and values like this:


一旦此扩展方法就位,您可以获得如下名称和值:

    var regex = new Regex(@"(?<year>[\d]+)\|(?<month>[\d]+)\|(?<day>[\d]+)");
    var namedCaptures = regex.MatchNamedCaptures(wikiDate);

    string s = "";
    foreach (var item in namedCaptures)
    {
        s += item.Key + ": " + item.Value + "\r\n";
    }

    s += namedCaptures["year"];
    s += namedCaptures["month"];
    s += namedCaptures["day"];

回答by Joel

The Regex class is the key to this!

Regex 类是关键!

foreach(Group group in match.Groups)
{
    Console.WriteLine("Group: {0}, Value: {1}", regex.GroupNameFromNumber(group.Index), group.Value);
}

http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.groupnamefromnumber.aspx

http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.groupnamefromnumber.aspx

回答by Jozef Benikovsky

Since .NET 4.7, there is Group.Nameproperty available.

从 .NET 4.7 开始,有可用的Group.Name属性。