Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using RegEx to Insert Character before Matches

Tags:

c#

regex

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

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

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

like image 896
Jonathan Wood Avatar asked May 21 '12 23:05

Jonathan Wood


People also ask

How do you add a character in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

What does '$' mean in regex?

Literal Characters and Sequences For instance, you might need to search for a dollar sign ("$") as part of a price list, or in a computer program as part of a variable name. Since the dollar sign is a metacharacter which means "end of line" in regex, you must escape it with a backslash to use it literally.

What is \r and \n in regex?

\n. Matches a newline character. \r. Matches a carriage return character.

How do you use wildcards in regex?

In regular expressions, the period ( . , also called "dot") is the wildcard pattern which matches any single character. Combined with the asterisk operator . * it will match any number of any characters.


1 Answers

You can transform each Match using a MatchEvaluator delegate and this overload of Replace...

Regex.Replace(input, @"[abc]", m => string.Format(@"\{0}", m.Value))
like image 144
spender Avatar answered Sep 19 '22 06:09

spender