Question

I need to write a method that will do a regex match, and then return all matches and all groups (except for group 0, which is entire matched string) in every match in a single string, glued by two different delimiteres (one for mathes, one for groups). I almost got it:

using System.Text.RegularExpressions;

MatchCollection mc = Regex.Matches(
    "one=123 something two=5678 nothing three=90",
     @"([a-z]+)=(\d+)"
);

Console.WriteLine(string.Join("|", 
    mc.OfType<Match>().SelectMany(m => 
        m.Groups.OfType<Group>().Select(g => 
            g.Value
        ).Skip(1)
    ).ToArray()));

This produces result: one|123|two|567|three|90, but what I need is: one;123|two;567|three;90

Problem is, that I don't know how to glue GroupCollection separately, that is, where and how to put another string.Join() (may be any other method of adding delimiter, ofcourse).

Please keep in mind, that I want to keep this syntax. I wouldn't be asking this question if I wanted to write two foreach loops :).

Was it helpful?

Solution

Ok, got it:

string.Join("|", 
    mc.OfType<Match>().Select(m => 
        string.Join(";",m.Groups.OfType<Group>().Select(g => 
            g.Value
        ).Skip(1).ToArray())
    ).ToArray()));

Now I know that Select and SelectMany work differently :).

Any answers with other approaches and explanations are still very welcome.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top