Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

regex

I'm parsing a text using C# regex. I want to replace only one specific group in for each match. Here how I'm doing it:

void Replace(){
  string newText = Regex.Replace(File.ReadAllText(sourceFile), myRegex, Matcher, RegexOptions.Singleline);
  //.......   
}

void string Matcher(Match m){
  // how do I replace m.Groups[2] with "replacedText"?
  return ""; // I want to return m.Value with replaced m.Group[2]
}
like image 307
Alan Coromano Avatar asked Oct 22 '12 06:10

Alan Coromano


3 Answers

You can use MatchEvaluator: Try This.

var replaced = Regex.Replace(text, pattern, m => m.Groups[1] + "AA" + m.Groups[3]);

I found one post in stackoverflow related to this: watch This

like image 189
Bhavik Patel Avatar answered Oct 15 '22 03:10

Bhavik Patel


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 written, you may find zero-width lookarounds simpler for your actual scenario:

Regex.Replace(input, @"(?<=e)l+(?=o)", replacement)

Example: http://rextester.com/SOWWS24307

like image 43
Justin Morgan Avatar answered Oct 15 '22 01:10

Justin Morgan


How about this?

    static string Matcher(Match m)
    {
        var group = m.Groups[2];
        var startIndex = group.Index - m.Index;
        var length = group.Length;
        var original = m.Value;
        var prior = original.Substring(0, startIndex);
        var trailing = original.Substring(startIndex + length);
        return string.Concat(prior, "replacedText", trailing);
    }
like image 24
mlorbetske Avatar answered Oct 15 '22 02:10

mlorbetske