使用PowerShell提取HTML文本失败,正则匹配问题求助
问题描述
需要从指定HTML代码中提取以下文本内容:
Spectrum Mortis - Bit Meseri - The Incantation (2022) Hate Legions - Exitus Letalis (Tota Vita Nihil Aliud Quam Ad Mortem Iter Est) (2014)
对应的HTML代码如下:
<span id='tid-span-369523'><a id="tid-link-369523" href="http://metalarea.org/forum/index.php?showtopic=369523" title="This topic was started: Sep 16 2022, 04:18:47">Spectrum Mortis - Bit Meseri - The Incantation (2022)</a></span> <span id='tid-span-221568'><a id="tid-link-221568" href="http://metalarea.org/forum/index.php?showtopic=221568" title="This topic was started: Apr 11 2014, 14:31:18">Hate Legions - Exitus Letalis (Tota Vita Nihil Aliud Quam Ad Mortem Iter Est) (2014)</a></span>
编写了以下PowerShell代码尝试提取,但执行后output2.txt中无内容输出:
$html = Get-Content -Path 'C:\temp\html\metalarea2.html' -Raw $pattern = '<span id="tid-span-\\d+"><a id="tid-link-\\d+" href=".+" title=".">(.+?)</a></span>' $matches = Select-String -InputObject $html -Pattern $pattern -AllMatches $result = $matches | % { $_.Matches } | % { $_.Groups[1].Value } $result | Out-File -FilePath "C:\temp\html\output2.txt"
问题原因
原正则表达式匹配失败的核心原因:
- HTML中
span标签的id属性使用单引号包裹(如'tid-span-369523'),但原正则里写的是双引号(id="tid-span-\\d+"),导致无法匹配到目标span标签。 - 原正则中的
\\d+多了一层不必要的转义,在PowerShell的单引号字符串中,\d+即可匹配数字序列。
解决方案
可以使用以下两种修正后的正则表达式解决问题:
方案一:匹配完整标签结构
修正span标签的引号匹配逻辑,用\x27表示单引号(避免字符串转义问题):
$pattern = '<span id=\x27tid-span-\d+\x27><a id="tid-link-\d+" href=".+" title=".">(.+?)</a></span>'
方案二:简化匹配逻辑
跳过span标签的匹配,直接定位包含目标文本的a标签,表达式更简洁:
$pattern = '<a id="tid-link-\d+".+?>(.+?)</a>'
内容的提问来源于stack exchange,提问作者user3520363
相关产品推荐
相关产品推荐

