Friday, March 4, 2011

[.NET || RegEx] Remove single backslashes, convert doubles to single in string.

Hi all,

How best can I convert instances of double backslashes to a single backslash in a string, but remove any occurrences of single backslash?

So this:

\|Testing|ABC:1234\\1000-1\|

Should convert to this:

|Testing|ABC:1234\1000-1|

Ideally I want to avoid a temporary replace of '\' to another character. A solution using .NET or Regular Expressions is preferred.

From stackoverflow
  • Regex.Replace(input, @"\\(.|$)", "$1");
    

    [Edit: Pattern didn't match all possible cases specified in the OP. Thanks for the suggestions, GONeale and Alan M.]

    Charlie : Short and sweet, I like it.
  • Thanks for your response Princess,

    However in a few other scenarios it fails. I'm using this input:

    Regex.Replace(@"\L\\A\", @"\\(.)", "$1")
    

    It's returning: L\A\ When it should return L\A. I understand you are seeking any other character with the ".", but not sure how to fix it as sometimes there will not be other chars.

    I managed to put together a working (yet slightly long-winded) approach in C#:

    for (int i = 0; i < text.Length; i++)
    {
        if (text[i] == '\\' && (i + 1 <= text.Length && text[i + 1] == '\\'))
            newText += '\\';
        else if (text[i] == '\\')
            newText += string.Empty;
        else
            newText += text[i];
    }
    

    But would prefer something more elegant.

    Alan Moore : All you need to do is add a check for "end of input" in the capture group: Regex.Replace(@"\L\\A\", @"\\(.|$)", "$1")
  • thanks for your help Princess and Alan, working perfectly now with the RegEx adjustment!

0 comments:

Post a Comment