jjaspe
jjaspe

Reputation: 21

Replace "\" with "\/" in C#

I'm trying to change a string that has "/" to "\/" for a regex match.

This is what I've tried so far:

var test = "test/txt";
var testResult = test.Replace("/", @"\/");
var testResult2 = test.Replace("/", "\\/");
var testResult3 = @test.Replace("/", "\\/");
var testResult4 = test.Replace("/",@"\").Replace(@"\","\\/");
var testResult5 = test.Replace("/", @"\/").Replace("\\\\", "\\");

They all return "test\\/txt", I want "test\/txt".

I've seen the answers to replace / with \, and that works fine , when I try to put the / back in the same thing happens (testResult4).

Thanks in advance.

Upvotes: 1

Views: 1165

Answers (1)

Roman
Roman

Reputation: 12171

This code works fine:

var testResult = test.Replace("/", @"\/");

But when you watch testResult in debug mode it shows "test\\/txt".

Print testResult to console or debug and you will see result you expect:

Debug.WriteLine(testResult);

or

Console.WriteLine(testResult);

In debug you get double \ because it is escape symbol. So, in watch you get test\\/txt but it is result you expect - test\/txt.

Upvotes: 1

Related Questions