最佳答案
我正在尝试使用 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 ... {...}
接下来,我看到捕捉到的内容在 match 成员中,所以我把它们取出来:
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
,我只能得到其中的一组。
似乎通过添加 | ForEach-Object { $_.Groups.Groups[1].Value }
我得到了我想要的结果,但是我不明白为什么——所以我不能确定在将这个方法扩展到整个文件集时能否得到正确的结果。
为什么有用?
值得注意的是,这个 | ForEach-Object { $_.Groups[1].Value }
(即没有第二个 .Groups
)给出了相同的结果。
我想补充的是,在进一步的尝试中,似乎该命令可以通过删除管道 | Select-Object -Property Groups
来缩短。