Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing backslashes, forward slashes and double forward slashes with double backslashes

Tags:

string

c#

regex

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?

like image 766
MKII Avatar asked Nov 26 '25 20:11

MKII


2 Answers

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 [...].

like image 107
Wiktor Stribiżew Avatar answered Nov 29 '25 09:11

Wiktor Stribiżew


You may try this,

Regex.Replace (FilePath, @"/|\\{1,2}", "\\\\");

\\{1,2} will match a single or double backslashes,.

DEMO

like image 21
Avinash Raj Avatar answered Nov 29 '25 09:11

Avinash Raj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!