regex - 如何从一行中捕获多个正则表达式匹配到 Powershell 中的 $matches 魔术变量?

标签 regex powershell powershell-2.0

假设我有字符串 “等等等等F12等等等等F32等等等等”我想匹配 F12 和 F32,我将如何将两者都捕获到 Powershell 魔术变量 $matches?

如果我在 Powershell 中运行以下代码:

$string = "blah blah F12 blah blah F32 blah blah blah"
$string -match "F\d\d"

$matches 变量只包含 F12

我也试过:
$string -match "(F\d\d)"

这次 $matches 有两个项目,但都是 F12

我希望 $matches 包含 F12 和 F32 以进行进一步处理。我似乎无法找到一种方法来做到这一点。

所有帮助将不胜感激。 :)

最佳答案

您可以在 PowerShell 2.0 中使用 Select-String 执行此操作,如下所示:

Select-String F\d\d -input $string -AllMatches | Foreach {$_.matches}

前阵子我有 asked for a -matchall operator在 MS Connect 上,此建议已通过以下评论解决:

“这是通过选择字符串的 -allmatches 参数修复的。”

关于regex - 如何从一行中捕获多个正则表达式匹配到 Powershell 中的 $matches 魔术变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3141851/

相关文章:

regex - 匹配 perl 正则表达式中括号和方括号之外的所有逗号

regex - 缺少参数时重写 URL

powershell - 进入IF但退出到ELSE

powershell - 选择对象省略了选择字符串Powershell的输出

python - 使用可选字符串查找最接近的文本

javascript - 在 JavaScript 中 trim ?这段代码在做什么?

PowerShell 在使用 tee-object 时删除控制台消息颜色

windows - Jenkins 不会使用 Credential 参数运行 Start-Job

powershell - 修改函数中的 PowerShell 对象

powershell - 如何使用 Get-AdUser 获取特定属性