首页 > 解决方案 > 如何获取多个正则表达式匹配捕获组

问题描述

我正在尝试访问([^ ]+)数组中我的第一个捕获组的所有匹配项,以便我可以访问foreach它,但是我在输出中看不到它:

$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

产量:

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

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

标签: regexpowershell

解决方案


在我们得到真正的答案之前,请考虑重命名你的变量——两者$Matches都是$Input自动的,并且可以被运行时覆盖


为了获取第一个捕获组的值,您需要处理属性中的索引 1或每个匹配项Groups的属性中的索引 0 :Captures

$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 }

推荐阅读