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

有没有办法获得在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); } 

我想得到这个结果:

小组:[我不知道该怎么走],价值:123456789 04/09/2009 999
组:数字,数值:123456789
组:date,值:04/09/2009
组:代码,值:999

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

例如,

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

最干净的方法是使用这种扩展方法:

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

一旦这个扩展方法到位,你可以得到像这样的名称和值:

  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"]; 

你应该使用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); } 

正则expression式是这个关键!

 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

由于.NET 4.7,有Group.Name属性可用 。