是什么在PowerShell中.replace和-replace之间的区别?是什么在PowerShe

2019-05-13 13:31发布

我是根据印象.replace和-replace是同样的事情,但是我发现我无法完成一些任务正则表达式与.replace是我能与-replace。 可能有人请指出我错过了什么?

Broken Regex replace:
$a=$a.Replace('.:\\LOGROOT\\', "\\$env:computername\logroot\")


Working Regex replace:
$a=$a -Replace('.:\\LOGROOT\\', "\\$env:computername\logroot\")

PS:以下网址让我觉得有我不熟悉.replace选择,但我似乎无法找到如何使用它们,或者如何访问帮助这些选项的任何其他信息。 http://www.computerperformance.co.uk/powershell/powershell_regex.htm Regex.Replace(字符串,字符串,字符串,RegexOptions)以及:Regex.Replace(字符串,字符串,MatchEvaluator,RegexOptions)的方法。

谢谢

Answer 1:

虽然@Keith希尔的回答解释之间的区别Replace方法和-replace操作,解释为什么您可能看不到相同的结果,那是因为你使用的是String.Replace这确实字符串替换和方法-replace运算符使用正则表达式顶替。 您可以使用Regex.Replace方法用于此目的,你会看到同样的效果:

[regex]::replace($a,'.:\\LOGROOT\\', "\\$env:computername\logroot\")

总之, -replace操作者是相同Regex.Replace (上面链接的特定过载),但一般来说, Replace()可以是实例或静态方法可以做任何事情从完全不同的-replace



Answer 2:

它们不是同一件事。 .Replace是on System.String或任何其它类型的与名为一个实例方法的.NET方法Replace-replace是使用正则表达式PowerShell的运营商。 运行man about_operators上看到更多信息-replace操作。



文章来源: What's the difference between .replace and -replace in powershell?