Reputation: 249
I am trying to check to see if a path has more than two \'s and replace them with two \'s.
For example if the path I have looks like:
C:\\documents\\\\temporary
replace the \\\\
with \\
so the result would be:
C:\\documents\\temporary
At the moment what I am using in C# (which doesn't work) is this:
strVersion = Regex.Replace(strVersion, @"\\\\{4}", "\\\\");
Edit: This is fixed now I used Daniel Gimenez's solution.
Upvotes: 2
Views: 432
Reputation: 8580
Daniel's answer is correct, but to add to it:
If you are not expecting escaped strings, it would make sense to also replace single instances of backslashes with two.
strVersion = Regex.Replace(strVersion, @"\\+", @"\\");
Upvotes: 0
Reputation: 20504
Use the regex \\{2,}
to replace instaces of 2 or more slashes. {n,}
means the pattern can occur any number of times from n
to infinity.
strVersion = Regex.Replace(strVersion, @"\\{2,}", "\\");
Now I'm not sure if you just want one slash back or two. If you want two back change it to:
strVersion = Regex.Replace(strVersion, @"\\{2,}", @"\\");
Upvotes: 4
Reputation: 3214
In your initial code, my guess would be that
strVersion = Regex.Replace(strVersion, @"\\{4}", "\\");
Replaces with '\' rather than "\\". Perhaps try @"\\" or "\\\\"? (It's a bit annoying that the stackoverflow text editor actually treats the \ like a string would, so in my solution I actually had to type out 4 \'s for the first and 8 for the second)
Upvotes: -1