84

Powershell (バージョン 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                      ...                           {...}

次に、キャプチャがmatchesメンバーにあることがわかったので、それらを取り出します:

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     ...

またはリストとして| Format-List

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

ここで停止します。さらに進んで、キャプチャされたグループ要素のリストを取得する方法がわかりません。

別の を追加してみまし| ForEach-Object -MemberName Groupsたが、上記と同じものを返すようです。

私が得る最も近い| Select-Object -Property Groupsものは、実際に私が期待するもの(セットのリスト)を提供します:

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

しかし、それらのそれぞれからキャプチャされたグループを抽出することはできません。私| Select-Object -Index 1はそれらのセットの 1 つだけを取得しようとしました。


更新:可能な解決策

追加すること| ForEach-Object { $_.Groups.Groups[1].Value }で探していたものが得られたようですが、その理由がわかりません。そのため、このメソッドをファイルのセット全体に拡張したときに正しい結果が得られるかどうかはわかりません。

なぜ機能しているのですか?

補足として、これ| ForEach-Object { $_.Groups[1].Value }(つまり、2 番目の なし.Groups) は同じ結果になります。

さらに試してみると、パイプを削除することでコマンドを短縮できるよう| Select-Object -Property Groupsです。

4

5 に答える 5

93

Have a look at the following

$a = "http://192.168.3.114:8080/compierews/" | Select-String -Pattern '^http://(.*):8080/(.*)/$' 

$a is now a MatchInfo ($a.gettype()) it contain a Matches property.

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/

in the groups member you'll find what you are looking for so you can write :

"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
于 2015-11-25T12:54:33.970 に答える