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]
}
Regex.Replace
will always replace everything that the provided regex has matched.You have two possibilities:
Match only what you want to replace
or
Insert the parts of the original string which has been matched, but should be kept, into the replacement string, using capturing groups.
You provided not enough information to answer your question more specific. E.g. do you really need a
MatchEvaluator
? This is only needed, if you want to provide an individual replacement string for each match.This should do it:
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:
Example: http://rextester.com/SOWWS24307
How about this?
You can use
MatchEvaluator
: Try This.I found one post in stackoverflow related to this: watch This
The below code will take a match and construct a replacement string based on the groupValues collection. This collection specifies a Group index and the text to replace it's value with.
Unlike other solutions, it does not require the entire match to be contained in groups, only the parts of the match that you want to have in groups.