2009-09-04 84 views
83

有沒有辦法在C#中獲取捕獲的組的名稱?如何獲取C#Regex中捕獲的組的名稱?

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

我想要得到這樣的結果:

 
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 

回答

110

使用GetGroupNames獲得組列表中的表達式,然後遍歷這些,使用的名稱作爲關鍵字爲組集合。

例如,

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

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

謝謝!正是我想要的。我從來沒有想過這將是在正則表達式對象:( – 2009-09-04 20:00:23

5

您應該使用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); 
    } 
+0

+1謝謝伊蘭。 – 2009-09-04 20:03:01

18

做到這一點,最徹底的方法是使用這個擴展方法:

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

由於.NET 4.7,有Group.Name財產available