Using RegEx to Insert Character before Matches
You can transform each Match using a MatchEvaluator delegate and this overload of Replace...
Regex.Replace(input, @"[abc]", m => string.Format(@"\{0}", m.Value))
No need to use any MatchEvaluator
, Regex.Replace
offers dedicated means to access the whole match value in the replacement pattern: $&
. See Substituting the Entire Match:
The
$&
substitution includes the entire match in the replacement string. Often, it is used to add a substring to the beginning or end of the matched string. For example, the ($&
) replacement pattern adds parentheses to the beginning and end of each match. If there is no match, the$&
substitution has no effect.
Use
var result = Regex.Replace(input, @"[abc]", @"\$&");
C# demo:
var s = "abcd";
var result = Regex.Replace(s, @"[abc]", @"\$&");
Console.WriteLine(result);
// => \a\b\cd