Powershell Select-String:按命名正则表达式组获取结果

Ger*_*eld 6 powershell

我有这个 Select-String 使用包含命名组的正则表达式

$m=Select-String -pattern '(?<mylabel>error \d*)' -InputObject 'Some text Error 5 some text'
Run Code Online (Sandbox Code Playgroud)

Select-String 完成其工作:

PS > $m.Matches.groups


Groups   : {0, mylabel}
Success  : True
Name     : 0
Captures : {0}
Index    : 10
Length   : 7
Value    : Error 5

Success  : True
Name     : mylabel
Captures : {mylabel}
Index    : 10
Length   : 7
Value    : Error 5
Run Code Online (Sandbox Code Playgroud)

我可以通过使用组的索引来获取匹配的命名组的值,没问题:

PS > $m.Matches.groups[1].Value
Error 5
Run Code Online (Sandbox Code Playgroud)

但我通过使用命名的正则表达式组(mylabel)没有成功获得相同的结果。我发现类似的语句$m.Matches.groups["mylabel"].Value但在我的机器上不起作用(W10/W2012,PS 5.1)

Ben*_*rds 2

您在上面的评论中得到了一个正确答案,但以下是如何在不使用 0 匹配索引的情况下做到这一点:

$m.Matches.groups | ? { $_.Name -eq 'mylabel' } | Select-Object -ExpandProperty Value
Run Code Online (Sandbox Code Playgroud)