正则表达式翻转并合并除第一个之外的所有反斜杠

Rom*_*omz 3 regex powershell

我正在尝试编写正则表达式,它将翻转和合并除第一个之外的所有反斜杠.

像这样的东西:

 C:\a\b\c\d\e         --> C:/a/b/c/d/e
 C:\a\\b\\\c\d\\\\\\e --> C:/a/b/c/d/e
 C:/a///b//c/d//////e --> C:/a/b/c/d/e
 C:\a/\/b/\c/d//\///e --> C:/a/b/c/d/e
 C:/a/b/c/d/e         --> C:/a/b/c/d/e
Run Code Online (Sandbox Code Playgroud)

\\my_share\a\b\c\d/e             --> //my_share/a/b/c/d/e
\\my_share\\\a\\\\b\c\\\//\\d\e   --> //my_share/a/b/c/d/e
\\/\my_share\\\a\\\\b\c\\\\\\d\e --> //my_share/a/b/c/d/e (if multiple '\' or\and '/' in the front - put two //)
\my_share\\\a\\\\b\c\\\\\\d\e    --> /my_share/a/b/c/d/e (if one '\' or\and '/' in the front - flip it)
my_share\\\a\\\\b\c\\\\\\d\e     --> my_share/a/b/c/d/e (if no '\' or\and '/' in the front - don't do anything)
Run Code Online (Sandbox Code Playgroud)

如何在powershell中做到这一点?$my_path -ireplace "\\", "/"

Wik*_*żew 5

你可以用

$s = 'C:\a\b\c\d\e'
[regex]::Replace($s,'^([\\/]{2,})|[\\/]+',{param($match) If ($match.Groups[1].Success) { '//' } Else { '/' }})
Run Code Online (Sandbox Code Playgroud)

正则表达式匹配

  • ^([\\/]{2,})- 组1由字符串开头的2个或多个/\字符组成
  • | - 要么
  • [\\/]+- 一个或多个/\其他地方的字符.

如果组1匹配,//则用作替换,否则/.