"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 issue #7867 建议引入
-matchall
运算符来提供 PowerShell 原生实现 - 虽然该提议已获批准,但尚未有人加紧实现。
- GitHub issue #7867 建议引入
[regex]::Matches(
'This is **bold** and this is also **BOLD**,finally this is also **Bold**',
'\*\*.*?\*\*'
).Value
请注意,[regex]::Matches()
返回 [System.Text.RegularExpressions.Match]
实例的集合,其 .Value
属性包含匹配的文本。
关于Powershell - 匹配运算符仅查找第一个匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73100135/