我有这个 Select-String 使用包含命名组的正则表达式
$m=Select-String -pattern '(?<mylabel>error \d*)' -InputObject 'Some text Error 5 some text'
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
我可以通过使用组的索引来获取匹配命名组的值,没问题:
PS > $m.Matches.groups[1].Value
Error 5
但是我没有通过使用命名的正则表达式组(mylabel)获得相同的结果。我发现类似
$m.Matches.groups["mylabel"].Value
的声明但这在我的机器上不起作用(W10/W2012,PS 5.1)
最佳答案
您在上面的评论中得到了一个正确答案,但这里是不使用 0 匹配索引的方法:
$m.Matches.groups | ? { $_.Name -eq 'mylabel' } | Select-Object -ExpandProperty Value
关于Powershell 选择字符串 : Get results by named regex group,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54825202/