Powershell-Match运算符只查找第一个匹配项


"This is **bold** and this is also **BOLD**,finally this is also **Bold**" -match '**.*?**'

仅查找第一个匹配的

$Matches.count

仅返回1

-Replace执行相同操作在字符串中查找所有匹配项:

"This is **bold** and this is also **BOLD**,finally this is also **Bold**" -replace '**.*?**', 'Substring'

它匹配并替换所有实例:

This is Substring and this is also Substring,finally this is also Substring

如何让-Match运算符查找所有匹配项,并将它们作为属于$Matches变量的数组返回?谢谢

  • -match运算符确实在其输入中最多只找到一个匹配,而-replace总是找到并替换所有的匹配。

  • 从PowerShell 7.2.x开始,您需要使用底层。NET API直接查找多个匹配,即[regex]::Matches()方法。

    • GitHub问题#7867建议引入-matchall运算符来提供PowerShell本机实现-虽然该提议已获得批准,但尚未有人着手实施
[regex]::Matches(
'This is **bold** and this is also **BOLD**,finally this is also **Bold**',
'**.*?**'
).Value

请注意,[regex]::Matches()返回[System.Text.RegularExpressions.Match]实例的集合,其.Value属性包含匹配的文本。

最新更新