简体   繁体   English

从选择字符串将Powershell正则表达式分组

[英]Powershell Regex Grouping from Select-String

I am scraping a web request response to pull information held within html code which repeats a few times so using select-string rather than match. 我正在抓取一个Web请求响应以提取html代码中包含的拉信息,该信息重复了几次,因此使用选择字符串而不是match。 My code looks like 我的代码看起来像

$regexname = '\(\w{0,11}).{1,10}\'
$energenie.RawContent | select-string $regexname -AllMatches | % {$_.matches}

The return looks something like: 回报看起来像:

Groups : {<h2 class="ener">TV </h2>, TV}
Success : True
Captures : {<h2 class="ener">TV </h2>}
Index : 1822
Length : 33
Value : <h2 class="ener">TV </h2>

Groups : {<h2 class="ener">PS3 </h2>, PS3}
Success : True
Captures : {<h2 class="ener">PS3 </h2>}
Index : 1864
Length : 33
Value : <h2 class="ener">PS3 </h2>

I can't workout a way to grab the second element of groups eg TV or PS3 as: 我无法锻炼一种方法来抓取组的第二个元素,例如电视或PS3,例如:

$energenie.RawContent | select-string $regexname -AllMatches | % {$_.matches.groups}

Gives a strange output 提供奇怪的输出

Paul 保罗

This should work: 这应该工作:

$energenie.RawContent | $ energenie.RawContent | select-string $regexname -AllMatches | 选择字符串$ regexname -AllMatches | ForEach-Object { Write-Host $_.Matches.Groups[1].Value } ForEach-Object {写入主机$ _。Matches.Groups [1] .Value}

To get the second item in a collection, use the array index operator: [n] where n is the index from which you want a value. 要获取集合中的第二项,请使用数组索引运算符: [n]其中n是要从中获取值的索引。

For each entry in Matches , you want the second entry in the Groups property so that would be: 对于Matches每个条目,您都希望Groups属性中的第二个条目是:

$MyMatches = $energenie.RawContent | select-string $regexname -AllMatches | % {$_.Matches}
$SecondGroups = $MyMatches | % {$_.Groups[1]}

To get just the captured value, use the Value property: 要仅获取捕获的值,请使用Value属性:

$MyMatches | % { $_.Groups[1].Value }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM