首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何获得多个regex匹配捕获组

如何获得多个regex匹配捕获组
EN

Stack Overflow用户
提问于 2020-04-09 14:55:11
回答 1查看 105关注 0票数 2

我试图在数组中访问第一个捕获组([^ ]+)的所有匹配,这样我就可以在输出中看到foreach

代码语言:javascript
运行
复制
$input = "Row 1:
Computer: xxx
Last Heartbeat: 4/9/2020 11:27:24 AM

Row 2:
Computer: yyy
Last Heartbeat: 4/9/2020 11:27:37 AM"

$matches = ([regex]'Computer: ([^ ]+)').Matches($input)
$matches

产量:

代码语言:javascript
运行
复制
Groups   : {0, 1}
Success  : True
Name     : 0
Captures : {0}
Index    : 7
Length   : 13
Value    : Computer: xxx

Groups   : {0, 1}
Success  : True
Name     : 0
Captures : {0}
Index    : 66
Length   : 13
Value    : Computer: yyy

诚然,我有很多关于数据结构和如何访问它们的知识要学。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-09 15:02:54

在我们找到真正的答案之前,请考虑重新命名变量-- $Matches$Input都是https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_automatic_variables

为了获取第一个捕获组的值,您需要在每个匹配的Groups属性中定位索引1或在Captures属性中寻址索引0:

代码语言:javascript
运行
复制
$string = "Row 1:
Computer: xxx
Last Heartbeat: 4/9/2020 11:27:24 AM

Row 2:
Computer: yyy
Last Heartbeat: 4/9/2020 11:27:37 AM"

$results = ([regex]'Computer: ([^ ]+)').Matches($string)
$results | ForEach-Object { $_.Groups[1].Value }
# or 
$results | ForEach-Object { $_.Captures[0].Value }
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61124040

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档