如何将单行中的多个正则表达式匹配捕获到 Powershell 中的 $matches 魔术变量中?
假设我有字符串 "blah blah F12 blah blah F32 blah blah blah" 并且我想匹配 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
我想要 $匹配同时包含 F12 和 F32 以便进一步处理。我似乎找不到办法做到这一点。
我们将不胜感激所有帮助。 :)
Let's say I have the string "blah blah F12 blah blah F32 blah blah blah" and I want to match the F12 and F32, how would I go about capturing both to the Powershell magic variable $matches?
If I run the following code in Powershell:
$string = "blah blah F12 blah blah F32 blah blah blah"
$string -match "F\d\d"
The $matches variable only contains F12
I also tried:
$string -match "(F\d\d)"
This time $matches had two items, but both are F12
I would like $matches to contain both F12 and F32 for further processing. I just can't seem to find a way to do it.
All help would be greatly appreciated. :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用 PowerShell 2.0 中的 Select-String 来执行此操作,如下所示:
不久前我有 在 MS Connect 上请求
-matchall
运算符,此建议已作为修复关闭带有此注释:“这是通过选择字符串的 -allmatches 参数修复的。”
You can do this using Select-String in PowerShell 2.0 like so:
A while back I had asked for a
-matchall
operator on MS Connect and this suggestion was closed as fixed with this comment:"This is fixed with -allmatches parameter for select-string."
我建议使用此语法,因为这样可以更轻松地处理匹配数组:
I suggest using this syntax as makes it easier to handle your array of matches:
我看到两种处理方式不同的场景:
1. 提取一个模式的所有匹配: select-string + -allmatches
(?<=jobs).*
Select-String
来处理这个问题,就像我从输出示例如下2. 提取一个/多个模式的单个/第一个匹配:捕获组和 $Match[]
I see 2 scenarios that are handled differently:
1. extract all matches of one pattern: select-string + -allmatches
(?<=jobs).*
Select-String
to handle this like I am to get ids of nomad jobs from the output exemplified below2. extract a single/first match of one/multiple patterns: capture groups and $Match[]