仅当前面有 (\d2 -) 时才在 html 中查找链接 (href) [重复]

Posted

技术标签:

【中文标题】仅当前面有 (\\d2 -) 时才在 html 中查找链接 (href) [重复]【英文标题】:Find link (href) in html only if preceded by (\d2 -) [duplicate]仅当前面有 (\d2 -) 时才在 html 中查找链接 (href) [重复] 【发布时间】:2020-08-03 20:23:29 【问题描述】:

我有大量的 html,我想在其中查找 href 链接。href 位于包含有关 href 信息的表中。仅当该行中的信息包含 (\d2 -) 两位数字后跟空格和连字符时,我才需要减去 href。

我将在 C# 中使用正则表达式

我试过正则表达式:

((a|link).*?href=(\"|')(.+?)(\"|').*?)

但是这太过分了……

这是 html 的一部分:

<td style="vertical-align: top; width: 375px"><h1 id="H_67e23f29-bb69-46eb-b15c">00 - <a class="Hyperlink" href="http://xxxx.xxxxxxx.com/Management/HyperlinkLoader.aspx?HyperlinkID=c64b7052-4229-4169-b8a2" class="Hyperlink" onmouseover="HyperlinkLoader.showTooltip(event,'c64b7052-4229-4169-b8a2')" onclick="HyperlinkLoader.followHyperlink(event,'HyperlinkID':'c64b7052-4229-4169-b8a2','ReturnURL':'');return false">Algemeen</a></h1></td>
<td style="width: 292px; vertical-align: top; background-color: rgb(255, 255, 255); text-align: left"><a class="Hyperlink" href="http://xxxx.xxxxxxx.com/Management/HyperlinkLoader.aspx?HyperlinkID=29517117-26ce-4004-88ed" class="Hyperlink" onmouseover="HyperlinkLoader.showTooltip(event,'29517117-26ce-4004-88ed')" onclick="HyperlinkLoader.followHyperlink(event,'HyperlinkID':'29517117-26ce-4004-88ed','ReturnURL':'');return false">Asbestbeheersplan</a></td>
<td style="vertical-align: top; width: 375px"><h1 id="H_f534b7b2-a8f5-41b0-9aa8">01 - <a class="Hyperlink" href="http://xxxx.xxxxxxx.com/Management/HyperlinkLoader.aspx?HyperlinkID=7af55197-d865-4cb2-bb9c" class="Hyperlink" onmouseover="HyperlinkLoader.showTooltip(event,'7af55197-d865-4cb2-bb9c')" onclick="HyperlinkLoader.followHyperlink(event,'HyperlinkID':'7af55197-d865-4cb2-bb9c','ReturnURL':'');return false">Voor werken geldende voorwaarden</a></h1></td>

这就是我想要捕捉的:

match 1(href for "00 - Algemeen"): 
http://xxxx.xxxxxxx.com/Management/HyperlinkLoader.aspx?HyperlinkID=c64b7052-4229-4169-b8a2

match 2(href for "01 - Voor werk geldende voorwaarden"):
http://xxxx.xxxxxxx.com/Management/HyperlinkLoader.aspx?HyperlinkID=7af55197-d865-4cb2-bb9c

【问题讨论】:

如果可能,请使用html-agility-pack.net 之类的工具,而不是正则表达式 【参考方案1】:

您需要使用 lookaheadlookbehind 正则表达式功能。

我试过了,发现这个正则表达式很不错。

(?&lt;=Hyperlink" href=")((http)(.+?)(\"|').*?)

更多信息可以在here找到。

【讨论】:

Lookarounds 仅在此处设置匹配的上下文,但问题在于用特定模式分隔的两个非贪婪 .*? / .+?。第一个需要回火。

以上是关于仅当前面有 (\d2 -) 时才在 html 中查找链接 (href) [重复]的主要内容,如果未能解决你的问题,请参考以下文章