【发布时间】:2021-09-09 04:44:24
【问题描述】:
我正在尝试从文本文件中提取 html。这是它的样子:
<html>
<cool class="what"> idk1 </cool>
<lame id="hm">idc1 </lame>
<lame id="hm"> idc2 </lame>
<lame id="hm"> idc3</lame>
<lame id="hm"> idc4 </lame>
<confused id="allTheTime"> abc1 </confused>
<cool class="what"> idk2 </cool>
<lame id="hm"> </lame>
<lame id="hm"> idc2 </lame>
<lame id="hm"> </lame>
<lame id="hm"> idc4 </lame>
<confused id="allTheTime"> abc2 </confused>
<cool class="what"> idk3 </cool>
<confused id="allTheTime"> abc3 </confused>
</html>
下面是我的代码:
$html = Get-Content -path 'C:\Users\bob\Desktop\tester.txt' -Raw
$wantedData1 = ($html | select-string '(?<=<cool class="what">\s+)(.*?)(?=\s+</cool>)' -allMatches | foreach {$_.Matches} | Foreach {$_.Value})
$wantedData2 = ($html | select-string '(?<=<lame id="hm">\s+)(.*?)(?=\s+</lame>)' -allMatches | foreach {$_.Matches} | Foreach {$_.Value})
$wantedData3 = ($html | select-string '(?<=<confused id="allTheTime">\s+)(.*?)(?=\s+</confused>)' -allMatches | foreach {$_.Matches} | Foreach {$_.Value})
write-host $wantedData1
write-host $wantedData2
write-host $wantedData3
输出如下:
idk1 idk2 idk3
idc2 idc4 idc2 idc4
abc1 abc2 abc3
我正在尝试写一些东西给我这样的输出:
idk1
idc1
idc2
idc3
idc4
abc1
idk2
idc2
idc4
abc2
idk3
abc3
<cool> 和 <confused> 标记的数据在每次迭代中出现一次,但 <lame> 标记的值可能不存在,或者可能存在 1 到 5 个 <lame> 标记。我提到这一点是因为如果标签为空,我的其他查询之一会中断。任何帮助将不胜感激。谢谢。
【问题讨论】:
标签: regex string powershell loops