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

标签 powershell

"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 原生实现 - 虽然该提议已获批准,但尚未有人加紧实现。
[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/

相关文章:

powershell - 使用导出 CSV

PowerShell,使用 Start-Job 和 Start-Process 测试异步任务的性能/效率

powershell - Windows 7上的Get-ComputerInfo失败

json - 无法使用Powershell提取json值

powershell - 在 Azure 中运行 powershell 脚本

powershell - 从单行文本中过滤多个值

Powershell dll加载

c# - Powershell vs C# EscapeUriString 不同的结果

xml - 如何从PowerShell New-WebServiceProxy获取XML响应

powershell - DSC 自定义资源依赖项