2009-09-04 13 views
83

C'è un modo per ottenere il nome di un gruppo catturato in C#?Come posso ottenere il nome dei gruppi catturati in un 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); 
} 

Voglio ottenere questo risultato:

 
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 

risposta

110

Usa GetGroupNames per ottenere la lista dei gruppi in un'espressione e poi iterare chi, utilizzando i nomi come chiavi in ​​Raccolta gruppi.

Per esempio,

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

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

Grazie! Esattamente quello che volevo. Non ho mai pensato che questo sarebbe stato nell'oggetto Regex :( –

5

Si dovrebbe usare GetGroupNames(); e il codice sarà simile a questa:

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 Grazie Eran. –

18

Il modo più pulito per farlo è quello di utilizzare questo metodo di estensione:

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


Una volta che questo metodo di estensione i s in atto, è possibile ottenere nomi e valori come questo:

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

Dal .NET 4.7, c'è Group.Name proprietà available.

Problemi correlati