gpt4 book ai didi

regex - [Regex]::Replace() 和 -replace 之间有什么区别?

转载 作者:行者123 更新时间:2023-12-02 09:10:55 27 4
gpt4 key购买 nike

我了解.Replace()-replace 之间的区别,但是什么是-replace[Regex]: :替换()?

我测试了以下 2 个代码,但对我来说结果完全一样。

我还引用了 PowerShell Cookbook(O'reilly),它说

([Regex] is) extremely advanced regular expression replacement

我想知道 [Regex] 可以但 -replace 不能。

$line = "Loosen the socket by turning it#counterclockwise."
$line = $line -Replace "([a-z])#([a-z])","`$1 `$2"
$line

# Loosen the socket by turning it counterclockwise.

$line.GetType()
# IsPublic IsSerial Name BaseType
# -------- -------- ---- --------
# True True String System.Object

$line2 = "Loosen the socket by turning it#counterclockwise."
$line2 = [Regex]::Replace($line3,"([a-z])#([a-z])","`$1 `$2")
$line2

# Loosen the socket by turning it counterclockwise.

$line2.GetType()
# IsPublic IsSerial Name BaseType
# -------- -------- ---- --------
# True True String System.Object

最佳答案

The Fish's helpful answer包含很好的指示,但让我以不同的方式构建事物,部分灵感来自 Ansgar Wiechers ' 评论:

  • PowerShell 的 -replace operator.NET友好包装器 [Regex]::Replace() 方法

    • 鉴于 PowerShell 构建于 .NET 框架之上,因此 PowerShell 以更简单、更高级别的方式呈现 .NET 功能是一种常见模式。
  • 默认行为的一个重要区别是 -replace 默认不区分大小写,这与 PowerShell 在一般。

    • 使用变体 -creplace 进行大小写敏感替换。
  • -replace 仅提供由各种 [Regex]::Replace( ) 重载。

    • PowerShell Core v6.1.0+ 中的功能差距已经缩小,现在还通过传递给 -replace 的脚本 block 提供回调功能>,感谢 Mathias R. Jessen 的工作;例如,
      '1 + 1 = 2' -replace '\d+', { [int] $_.Value * 2 } 产生 '2 + 2 = 4' 并且是相当于:
      [regex]::replace('1 + 1 = 2', '\d+', { param($match) [int] $match.Value * 2 })
  • 如果 -replace 对于给定用例足够好,请使用 而不是 [regex]: :替换()

    • 方法调用的语法不同于 PowerShell 的其余部分,并且在类型转换和代码的长期稳定性方面存在细微差别;因此,如果可行,通常最好坚持使用 native PowerShell 功能(cmdlet 和运算符)。

    • 但是,如果 -replace 没有提供您需要的功能,直接调用 [regex]::Replace() 是一个很好的高级选项;请注意,Replace() 也作为一个实例 方法存在,在这种情况下它提供了额外的功能 - 例如,limit the number of replacements 的能力;例如:

      # Replace only the first two 'o' instances.
      PS> $re = [regex] 'o'; $re.Replace('fooo', '@', 2)
      f@@o

关于regex - [Regex]::Replace() 和 -replace 之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52332794/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com