Copied to clipboard

Flag this post as spam?

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


  • Arun 141 posts 394 karma points
    Jan 10, 2020 @ 11:41
    Arun
    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 MVP 6x c-trib
    Jan 10, 2020 @ 12:03
    Laura Weatherhead
    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 151 posts 1024 karma points MVP c-trib
    Jan 10, 2020 @ 13:11
    Steve Megson
    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.

  • Arun 141 posts 394 karma points
    Jan 20, 2020 @ 06:02
    Arun
    0

    Thanks Buddys for your precious time.
    I've tried all these suggestions but didn't get the desired output.
    A weird thing that i found upon debugging is the "sampleText" is changed to "abc\\\\\\def" (6 backward slashes)


    var sampleText = @"abc\\\def"
    then it changes to "abc\\\\\\def"


    among this sampleText.Replace(@"\\\", @"\")

    returns a nearly output abc\\def.

    ~Arun

  • Steve Megson 151 posts 1024 karma points MVP c-trib
    Jan 20, 2020 @ 10:11
    Steve Megson
    0

    I think you're just seeing escaped strings in the debugger. For example, if a string contains a line break then the debugger will show it as "123\n456". If I do

        var sampleText = @"abc\\\def";
        var result = sampleText.Replace(@"\\\", @"\");
        Console.WriteLine(result);
    

    then I get the expected abc\def in the console, but the debugger will display the value of result as "abc\\def".

Please Sign in or register to post replies

Write your reply to:

Draft