Come posso ottenere il nome dei gruppi acquisiti in un C # Regex?


97

C'è un modo per ottenere il nome di un gruppo acquisito 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);
}

Voglio ottenere questo risultato:

Gruppo: [Non so cosa dovrebbe andare qui], Valore: 123456789 04/09/2009 999
Gruppo: numero, valore: 123456789
Gruppo: data, Valore: 04/09/2009
Gruppo: codice, Valore: 999

Risposte:


127

Utilizzare GetGroupNames per ottenere l'elenco dei gruppi in un'espressione e quindi scorrere su quelli, utilizzando i nomi come chiavi nella raccolta dei 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);
}

9
Grazie! Esattamente quello che volevo. Non avrei mai pensato che questo sarebbe stato nell'oggetto Regex :(
Luiz Damim

22

Il modo più pulito per farlo è 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 è a posto, puoi 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"];


7

Dovresti usare GetGroupNames();e il codice sarà simile a questo:

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

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.