正则表达式 – 如何从Select-String获取捕获的组?

我正在使用Power shell(版本4)从 Windows上的一组文件提取文本:
PS > Select-String -AllMatches -Pattern <mypattern-with(capture)> -Path file.jsp | Format-Table

到现在为止还挺好.这给了一组很好的MatchInfo对象:

IgnoreCase                    LineNumber Line                          Filename                      Pattern                       Matches
----------                    ---------- ----                          --------                      -------                       -------
    True                            30   ...                           file.jsp                      ...                           {...}

接下来,我看到捕获是在比赛成员,所以我把他们:

PS > Select-String -AllMatches -Pattern <mypattern-with(capture)> -Path file.jsp | ForEach-Object -MemberName Matches | Format-Table

这使:

Groups        Success Captures                 Index     Length Value
------        ------- --------                 -----     ------ -----
{...}         True    {...}                    49        47     ...

或与…列表格式列表:

Groups   : {matched text,captured group}
Success  : True
Captures : {matched text}
Index    : 39
Length   : 33
Value    : matched text

这里是我停止的地方,我不知道如何进一步,并获得捕获的组元素的列表.

我试过添加一个| ForEach-Object -MemberName组,但它似乎返回与上述相同.

我最接近的是|选择对象 – 属性组,这确实给了我所期望的(集合列表):

Groups
------
{matched text,captured group}
{matched text,captured group}
...

但是,我无法从每个人中提取捕获的组,我尝试使用| Select-Object -Index 1我只得到其中一个集合.

更新:一个可能的解决方

似乎加入| ForEach-Object {$_.Groups.Groups [1] .Value}我得到了我正在寻找的东西,但是我不明白为什么 – 所以我无法确定我能够在扩展时获得正确的结果这种方法对整套文件.

为什么它工作?

作为附注,这个| ForEach-Object {$_.Groups [1] .Value}(即没有第二个.Groups)给出相同的结果.

我想补充一点,经过进一步的尝试,似乎可以通过删除管道缩短命令Select-Object -Property组.

看看下面的内容
$a = "http://192.168.3.114:8080/compierews/" | Select-String -Pattern '^http://(.*):8080/(.*)/$'

$a现在是一个MatchInfo($a.gettype()),它包含一个Matches属性.

PS ps:\> $a.Matches
Groups   : {http://192.168.3.114:8080/compierews/,192.168.3.114,compierews}
Success  : True
Captures : {http://192.168.3.114:8080/compierews/}
Index    : 0
Length   : 37
Value    : http://192.168.3.114:8080/compierews/

在小组成员中你会发现你正在寻找的,所以你可以写:

"http://192.168.3.114:8080/compierews/" | Select-String -Pattern '^http://(.*):8080/(.*)/$'  | % {"IP is $($_.matches.groups[1]) and path is $($_.matches.groups[2])"}

IP is 192.168.3.114 and path is compierews

相关文章

正则替换html代码中img标签的src值在开发富文本信息在移动端...
正则表达式
AWK是一种处理文本文件的语言,是一个强大的文件分析工具。它...
正则表达式是特殊的字符序列,利用事先定义好的特定字符以及...
Python界一名小学生,热心分享编程学习。
收集整理每周优质开发者内容,包括、、等方面。每周五定期发...