95 votes

Comment obtenir le nom des groupes capturés dans une Regex C# ?

Existe-t-il un moyen d'obtenir le nom d'un groupe capturé en 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);
}

Je veux obtenir ce résultat :

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

0voto

Kinetic Points 46

Mettre à jour la méthode d'extension existante répondu par @whitneyland avec une méthode qui peut gérer les correspondances multiples :

public static List<Dictionary<string, string>> MatchNamedCaptures(this Regex regex, string input)
    {
        var namedCaptureList = new List<Dictionary<string, string>>();
        var match = regex.Match(input);

        do
        {
            Dictionary<string, string> namedCaptureDictionary = new Dictionary<string, string>();
            GroupCollection groups = match.Groups;

            string[] groupNames = regex.GetGroupNames();
            foreach (string groupName in groupNames)
            {
                if (groups[groupName].Captures.Count > 0)
                    namedCaptureDictionary.Add(groupName, groups[groupName].Value);
            }

            namedCaptureList.Add(namedCaptureDictionary);
            match = match.NextMatch();
        }
        while (match!=null && match.Success);

        return namedCaptureList;
    }

Uso:

  Regex pickoutInfo = new Regex(@"(?<key>[^=;,]+)=(?<val>[^;,]+(,\d+)?)", RegexOptions.ExplicitCapture);

  var matches = pickoutInfo.MatchNamedCaptures(_context.Database.GetConnectionString());

  string server = matches.Single( a => a["key"]=="Server")["val"];

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X