Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you replace a single character with a backslash using regex.replace in c#

Tags:

c#

regex

If I do this:

Regex.Replace("unlocktheinbox.com", "[t]", "\\$&");

My result is:

"unlock\\theinbox.com"

I'm expecting it to be

"unlock\theinbox.com"

I'm trying to replace "t" with "\t" using regex.replace. I made this example very basic to explain what I'm trying to accomplish.

like image 928
Henry Avatar asked Oct 19 '22 16:10

Henry


1 Answers

Try following

var result = Regex.Replace("unlocktheinbox.com", "[t]", @"\");

Note that, if you observe result while debugging via hovering mouse on result. it will look like unlock\\theinbox.com because \ is escaped. But actually, if you print result or use anywhere it will be unlock\theinbox.com

like image 148
tchelidze Avatar answered Oct 31 '22 20:10

tchelidze