tags:

views:

1599

answers:

3

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.

+4  A: 
Regex.Replace(input, @"\\(.|$)", "$1");

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

Juliet
Short and sweet, I like it.
Charlie
A: 

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.

GONeale
All you need to do is add a check for "end of input" in the capture group: Regex.Replace(@"\L\\A\", @"\\(.|$)", "$1")
Alan Moore
A: 

thanks for your help Princess and Alan, working perfectly now with the RegEx adjustment!

GONeale