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

时间:2018-03-28 06:16:47

标签: 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

但是

\\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)

如何在powershell中执行此操作? $my_path -ireplace "\\", "/"

1 个答案:

答案 0 :(得分:5)

您可以使用

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

正则表达式匹配

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

如果第1组匹配,则使用//作为替代,否则使用/

相关问题