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]
}
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
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
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With