DEV Community

baris
baris

Posted on

Answer: Regex in C# - how I replace only one specific group in Match?

Nice one

This should do it:

string Matcher(Match m)
{
    if (m.Groups.Count < 3)
    {
        return m.Value;
    }

    return string.Join("",  m.Groups
                             .OfType<Group>() //for LINQ
                             .Select((g, i) => i == 2 ? "replacedText" : g.Value)
                             .Skip(1) //for Groups[0]
                             .ToArray());
}

Example: http://rextester.com/DLGVPA38953

EDIT: Although the above is the answer to your question as…

Top comments (0)