If I have the following string
"/test\\dso\dsa"
how can I convert it, using Regex, to
"\\test\\dso\\dsa"?
If I try something like
Regex.Replace (FilePath, @"/|\\", @"\\");
it creates a mess in the middle (since it adds the \\ twice, thus adding \\\\\\\\). How can I make it only match one backslash at a time?
You can use the following code:
var FilePath = @"/test\\dso\dsa";
var myres = Regex.Replace(FilePath, @"[\\/]+", @"\\");
Output:
\\test\\dso\\dsa
The regex [\\/]+ matches 1 or more \ or / characters that are then replaced with two \ symbols.
The problem with @"/|\\" regex is that it matches each \ or / one by one, thus resulting in more replacements than you need. Also, it is not a good idea to use separate symbols as alternatives since there is more backtracking involved. The best practice is adding them into a character class [...].
You may try this,
Regex.Replace (FilePath, @"/|\\{1,2}", "\\\\");
\\{1,2} will match a single or double backslashes,.
DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With