Using RegEx to insert characters before matches

I know that I can use RegEx to replace all occurrences of 'a', 'b' or 'c' with a blackslash character in a line like this:

string result = Regex.Replace(input, "[abc]", "\\");

But how can I replace each occurrence with a backslash followed by a character that matches?

+3
source share
1 answer

You can convert every Match using MatchEvaluator and this overload Replace ...

Regex.Replace(input, @"[abc]", m => string.Format(@"\{0}", m.Value))
+15
source

All Articles