【问题标题】:What's the difference between .replace and -replace in powershell?powershell中的.replace和-replace有什么区别?
【发布时间】:2012-04-28 09:00:03
【问题描述】:

我的印象是 .replace 和 -replace 是完全相同的东西,但是我发现我无法使用 .replace 完成一些 RegEx 任务,而我可以使用 -replace 完成。有人可以指出我缺少什么吗?

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


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

ps: 以下 URL 使我认为存在我不熟悉的 .replace 选项,但我似乎无法找到有关如何使用它们或如何访问这些选项的帮助的任何其他信息。 http://www.computerperformance.co.uk/powershell/powershell_regex.htm Regex.Replace(String, String, String, RegexOptions) 以及: Regex.Replace(String, String, MatchEvaluator, RegexOptions) 方法。

谢谢

【问题讨论】:

  • 我认为-Replace 是一个运算符,而.Replace 是一个方法(在$a 上)。

标签: powershell methods replace


【解决方案1】:

它们不是一回事。 .Replace 是 System.String 或具有名为 Replace 的实例方法的任何其他类型的 .NET 方法。 -replace 是一个使用正则表达式的 PowerShell 运算符。运行 man about_operators 以查看有关 -replace 运算符的更多信息。

【讨论】:

【解决方案2】:

虽然@Keith Hill 的回答解释了Replace 方法和-replace 运算符之间的区别,但解释了为什么您可能看不到相同的结果,这是因为您使用的是String.Replace 方法,它可以替换字符串和-replace 运算符使用正则表达式替换。您可以为此目的使用Regex.Replace 方法,您应该会看到相同的效果:

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

简而言之,-replace 运算符与Regex.Replace 相同(上面链接的特定重载),但通常Replace() 可以是实例或静态方法,可以做与-replace 完全不同的任何事情

【讨论】:

  • 很好,但请注意-regex[regex]::Replace() 之间的一个重要区别:-regex 默认情况下是不区分大小写的(就像 PowerShell 通常那样);更具体地说,它是 sensitive 变体 -creplace 对应于 .NET 方法。
猜你喜欢
  • 2019-02-19
  • 2018-04-24
  • 2021-11-10
  • 1970-01-01
  • 2012-06-05
  • 1970-01-01
  • 2021-09-22
  • 2011-11-09
相关资源
最近更新 更多