我理解.Replace()和-replace之间的区别,但是-replace和[Regex]::Replace()是什么?
我测试了以下两个代码,但对我来说,结果是完全一样的。
我还提到了PowerShell烹饪手册(O‘’reilly),上面写着
(Regex是)非常高级的正则表达式替换。
我想知道[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发布于 2018-09-14 15:46:32
鱼的有用的答案包含了很好的指针,但让我把事情的框架稍微不同一点,部分是受到安斯加·威奇斯的评论的启发:
[Regex]::Replace()方法的友好包装器。- Given that PowerShell is built on the .NET framework, it is a common pattern for PowerShell to surface .NET functionality in a simpler, higher-level fashion.-replace 在默认情况下是 case-INsensitive ,这与PowerShell的一般行为是一致的。- Use variant `-creplace` for case-_sensitive_ replacements.-replace 只提供各种[Regex]::Replace()重载提供的功能的子集。- The functionality gap has narrowed in PowerShell _Core_ v6.1.0+, which now also offers _callback_ functionality via a script block passed to `-replace`, thanks to work by [Mathias R. Jessen](https://stackoverflow.com/users/712649/mathias-r-jessen); e.g.,'1 + 1 = 2' -replace '\d+', { [int] $_.Value * 2 }生成'2 + 2 = 4',相当于:
[regex]::replace('1 + 1 = 2', '\d+', { param($match) [int] $match.Value * 2 })
-replace 对于给定的用例来说足够好,那么使用 it而不是[regex]::Replace()。- The syntax of method calls differs from the rest of PowerShell, and there are subtleties around type conversion and long-term stability of code; it is therefore generally preferable to stick with native PowerShell features (cmdlets and operators), if feasible.- However, if `-replace` doesn't provide the functionality you need, calling `[regex]::Replace()` directly is a great advanced option; note that `Replace()` also exists as an _instance_ method, in which case it offers additional functionality - e.g., the ability to [limit the number of replacements](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.:只替换前两个'o‘实例。PS> $re = regex 'o';$re.Replace('fooo','@',2) f@@o
https://stackoverflow.com/questions/52332794
复制相似问题