Copied to clipboard

#### Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at

• Arun 29 posts 99 karma points
1 week ago
0

## Replacing "\\" to "\" in Umbraco

Hi Guys

I'm trying to replace a string "abc\\def" to "abc\def"
I have tried these codes but didn't work..! I'm getting the same text returned!

-) sampleText = sampleText.Replace(@"\\\", @"\");

-) sampleText = Regex.Replace(sampleText ,@"\\", @"\");

I've been stuck here for a long time..!!!
Anybody knows the solution..?

• Laura Weatherhead 25 posts 153 karma points
1 week ago
0

Hey Arun,

The backslash is used as an escape character in Regex, so you'd need to double them to match "\"

Depending on your requirements, you probably want to match something more like:

sampleText.Replace(@"\\{2,}", @"\")

Where you are matching 2 or more backslash characters and replacing them. This is a good resource for testing Regex: https://regexr.com/

Cheers, Laura

• Steve Megson 126 posts 780 karma points
1 week ago
0

sampleText = sampleText.Replace(@"\\\", @"\");

In a "verbatim" string literal prefixed by @, the \ character isn't special so there's no need to escape it. You can use sampleText = sampleText.Replace(@"\\", @"\"); as you would for replacing any other character.

sampleText = Regex.Replace(sampleText ,@"\\", @"\");

Here the \ isn't a special character to C#, but it's still a special character in a regex pattern, so you need sampleText = Regex.Replace(sampleText ,@"\\\\", @"\");

I'd prefer the first option since it'll be quicker.