正则表达式:在C#中得到捕获组的名称 [英] Regex: get the name of captured groups in C#

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

问题描述

有没有办法得到一个捕获组的名称,在C#?

 串线=No.123456789 04/09/2009 999;
正则表达式的regex ​​=新的正则表达式(@(小于?号> [\\ D] {9})(LT;日期> [\\ D] {2} / [\\ D] {2} / [\\ D] {4 })(LT; code基。*));GroupCollection组= regex.Match(线).Groups;的foreach(在组组组)
{
    Console.WriteLine(组:{0},值:{1},???,group.Value);
}

我要得到这样的结果:


组:[我不知道什么应该在这里],值:123456789 04/09/2009 999
组:号码,值:123456789
组:日期,值:04/09/2009
组:code,值:999


解决方案

使用<一个href=\"http://msdn.microsoft.com/en-us/library/system.text.regularex$p$pssions.regex.getgroupnames.aspx\">GetGroupNames以获得组的列表在离pression然后遍历那些,使用名作为密钥进组集合

例如,

  GroupCollection组= regex.Match(线).Groups;的foreach(在regex.GetGroupNames串组名())
{
    Console.WriteLine(
       组:{0},值:{1},
       组名,
       组[组名]。价值);
}

Is there a way to get the name of a captured group in 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

解决方案

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

For example,

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

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

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

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