当然,问题在于,有时& 分隔 路径,有时它是路径的一部分。一个简单的字符替换将无法分辨哪个& 是哪个,所以我们需要使用一些上下文来弄清楚。
我们知道,当& 分隔两条路径时,下一条路径将以pathX= 形式的标签开始。我们可以使用模式&(?=(path\d+=)) 来匹配& 这样的字符。 (?=) 是 zero-width positive lookahead assertion,这意味着其中的所有内容都必须遵循 &,但实际上不会匹配(替换)。 path\d+= 表示文字字符 path 后跟 one or more digits (\d+) 后跟文字字符 =。
PS> $pattern = '&(?=(path\d+=))'
PS> 'path1=/path/me & you/file.json' -replace $pattern, ';'
path1=/path/me & you/file.json
PS> 'path1=/path/me & you/file.json&path2=/path/you & me/file.txt' -replace $pattern, ';'
path1=/path/me & you/file.json;path2=/path/you & me/file.txt
PS> 'path1=/path/me & you/file.json&path2=/path/you & me/file.txt&path3=/folder/R & B/ me & you/file.txt' -replace $pattern, ';'
path1=/path/me & you/file.json;path2=/path/you & me/file.txt;path3=/folder/R & B/ me & you/file.txt
PS> '&path1=/path/me & you/file.json&path2=/path/you & me/file.txt' -replace $pattern, ';'
;path1=/path/me & you/file.json;path2=/path/you & me/file.txt
PS> 'path1=/path/me & you/file.json&path2=/path/you & me/file.txt&' -replace $pattern, ';'
path1=/path/me & you/file.json;path2=/path/you & me/file.txt&
PS> 'path1=/path/me & you/file.json&&path2=/path/you & me/file.txt&&&&&path3=/folder/R & B/ me & you/file.txt' -replace $pattern, ';'
path1=/path/me & you/file.json&;path2=/path/you & me/file.txt&&&&;path3=/folder/R & B/ me & you/file.txt
请注意,前面的&(第四个测试输入)被替换,因为它后面跟着通常的path1=,但尾随&(第五个测试输入)和多个连续的&(最后一个测试输入)不是。如果这些情况应该被视为空路径而不是以& 结尾的文件名,则可以使用模式&+(?=(path\d+=)|$) 来完成。 &+ 现在将匹配 one or more &,添加 |$ 将在 end of the string 处出现 also match &。
PS> $pattern = '&+(?=(path\d+=)|$)'
PS> 'path1=/path/me & you/file.json' -replace $pattern, ';'
path1=/path/me & you/file.json
PS> 'path1=/path/me & you/file.json&path2=/path/you & me/file.txt' -replace $pattern, ';'
path1=/path/me & you/file.json;path2=/path/you & me/file.txt
PS> 'path1=/path/me & you/file.json&path2=/path/you & me/file.txt&path3=/folder/R & B/ me & you/file.txt' -replace $pattern, ';'
path1=/path/me & you/file.json;path2=/path/you & me/file.txt;path3=/folder/R & B/ me & you/file.txt
PS> '&path1=/path/me & you/file.json&path2=/path/you & me/file.txt' -replace $pattern, ';'
;path1=/path/me & you/file.json;path2=/path/you & me/file.txt
PS> 'path1=/path/me & you/file.json&path2=/path/you & me/file.txt&' -replace $pattern, ';'
path1=/path/me & you/file.json;path2=/path/you & me/file.txt;
PS> 'path1=/path/me & you/file.json&&path2=/path/you & me/file.txt&&&&&path3=/folder/R & B/ me & you/file.txt' -replace $pattern, ';'
path1=/path/me & you/file.json;path2=/path/you & me/file.txt;path3=/folder/R & B/ me & you/file.txt