Passionate.C
Passionate.C

Reputation: 243

How to replace "\\" to "\" C#

Here is an example: "\\\r\\\n\\\u003c"

Expected Result: "\r\n\u003c"

I have tried string.Replace(@"\\\", @"\");, but it doesn't work.

Upvotes: 0

Views: 197

Answers (3)

STLDev
STLDev

Reputation: 6164

Hard to tell since you don't show your exact code, but possibly you're not saving the result of your string.Replace(). Your code looks good.

The @ symbol in front of your literal strings make them verbatim literal strings, and therefore prevents the backslashes from being uses as escape characters, which is what you want here.

string.Replace() doesn't modify the input string, but rather it returns the modified string. Perhaps you're not using the return value from string.Replace().

The following code works:

var stringWithDoubleSlashes = @"\\r\\n\\u003c";

var stringWithSingleSlashes = stringWithDoubleSlashes.Replace(@"\\", @"\");
Console.WriteLine(stringWithSingleSlashes); // displays \r\n\u003c

Upvotes: 1

Samvel Petrosov
Samvel Petrosov

Reputation: 7706

You can use Regex.Unescape method for this approach. It will replace all double \\ with \.

Upvotes: 4

H. Pauwelyn
H. Pauwelyn

Reputation: 14280

Replace the full char \\n to \n. Your way does't work because a backslash is used to escape charachters.

Upvotes: 0

Related Questions