我明白了之间的区别.Replace()
and -replace
,但是什么是-replace
and [Regex]::Replace()
?
我测试了以下两个代码,但对我来说结果完全相同。
我还提到了 PowerShell Cookbook(O'reilly),它说
([Regex] is)极其高级的正则表达式替换
我想知道什么[Regex]
可以但是-replace
can't.
$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
鱼的回答很有帮助 https://stackoverflow.com/a/52333140/45375包含很好的指针,但让我以不同的方式构建事物,部分灵感来自安斯加尔·维彻斯 https://stackoverflow.com/users/1630171/ansgar-wiechers' 评论:
-
PowerShell 的 -replace operator https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators?view=powershell-6#replacement-operator is a 友好的包装器为了.NET [Regex]::Replace() https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.replace method.
- 鉴于 PowerShell 是基于 .NET 框架构建的,因此 PowerShell 以更简单、更高级的方式呈现 .NET 功能是一种常见模式。
-
默认行为的一个重要区别是-replace
is 不区分大小写默认情况下,与 PowerShell 的一般行为一致。
- 使用变体
-creplace
对于案例-敏感的替代品。
-
-replace
只提供一个subset的功能性由各方面提供[Regex]::Replace()
过载。
- PowerShell 中的功能差距已缩小Corev6.1.0+,现在还提供callback通过传递给脚本块的功能
-replace
,感谢工作马蒂亚斯·R·杰森 https://stackoverflow.com/users/712649/mathias-r-jessen; e.g.,
'1 + 1 = 2' -replace '\d+', { [int] $_.Value * 2 }
yields '2 + 2 = 4'
并且相当于:
[regex]::replace('1 + 1 = 2', '\d+', { param($match) [int] $match.Value * 2 })
-
If -replace
对于给定的用例来说足够好,使用it而不是[regex]::Replace()
.
-
方法调用的语法与 PowerShell 的其余部分不同,并且在类型转换和代码的长期稳定性方面存在微妙之处;因此,如果可行的话,通常最好坚持使用本机 PowerShell 功能(cmdlet 和运算符)。
-
然而,如果-replace
不提供您需要的功能,调用[regex]::Replace()
直接是一个很好的高级选项;注意Replace()
也作为一个存在instance方法,在这种情况下它提供了额外的功能 - 例如,能够限制更换数量 https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.replace?view=netframework-4.7.2#System_Text_RegularExpressions_Regex_Replace_System_String_System_Text_RegularExpressions_MatchEvaluator_System_Int32_; e.g.:
# Replace only the first two 'o' instances.
PS> $re = [regex] 'o'; $re.Replace('fooo', '@', 2)
f@@o
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)