【问题标题】:Iterate through file with regex and multiple variables使用正则表达式和多个变量遍历文件
【发布时间】: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

&lt;cool&gt; 和 &lt;confused&gt; 标记的数据在每次迭代中出现一次,但 &lt;lame&gt; 标记的值可能不存在,或者可能存在 1 到 5 个 &lt;lame&gt; 标记。我提到这一点是因为如果标签为空,我的其他查询之一会中断。任何帮助将不胜感激。谢谢。

【问题讨论】:

    标签: regex string powershell loops


    【解决方案1】:

    看起来您的 HTML 文本也是有效的 XML,这使得解析更容易:

    # Simulate reading from an XML file.
    # To read from an actual file, use:
    #    ($xmlDoc = [xml]::new()).Load((Convert-Path file.xml))
    [xml] $xmlDoc = @'
    <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>
    '@
    
    # Get the inner text from all <html> child nodes and
    # trim surrounding whitespace from each.
    $xml.html.ChildNodes.InnerText.Trim()
    

    以上产生以下内容(与您在问题中陈述的内容不完全匹配,但我认为您的意思是);您可以通过在 $strings = 语句之前添加类似 $strings = 的内容将其捕获到字符串数组中:

    idk1
    idc1
    idc2
    idc3
    idc4
    abc1
    idk2
    
    idc2
    
    idc4
    abc2
    idk3
    abc3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-25
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多