【问题标题】:Regex to find anchor tags which are without http or https in the href attribute正则表达式查找在 href 属性中没有 http 或 https 的锚标记
【发布时间】:2013-03-31 17:21:16
【问题描述】:

我有这个示例文本,我想在上面运行正则表达式来拉取地址部分中 href 不包含 http|https 的锚标记。

我正在尝试使用这个正则表达式,但它还没有完成。当锚不是以 http 或 https 开头时,我无法拔出锚。

链接到 gskinner 网站 - http://regexr.com?34ev0

<a.*?href=[""|'](http|https:\/\/)(?<link>[^""|']*)[""|'].*?>

这里是示例字符串:-

<br /><span style="font-size: 16px;"><strong><a target="_blank" href="http://www.yahoo.com">Good Link (Yahoo)</a><br /><br /><a target="_blank" href="www.bbc.com">Bad Link (BBC)</a><br /><br /><a href="" id="anchorSocialMedia" onclick="ShowModalPopup('anchorSocialMedia','/Events/Popup/SocialMediaShareModal.aspx','650px','500px');">Share This Event</a><br />Badge Perf Testing<br /><br /></strong></span>

谢谢。

【问题讨论】:

    标签: regex regex-negation regex-lookarounds


    【解决方案1】:

    使用 JavaScript 正则表达式方法(几乎所有语言都有等效方法):

    <your string>.match(/<a\s[^>]*href\s*=\s*"[^"]*"[^>]*>/g)
    .join('')
    .match(/href\s*=\s*"(?!https?:\/\/)[^"]*"/g);
    

    <your string>.match(/<a\s[^>]*href\s*=\s*"(?!https?:\/\/)[^"]*"[^>]*>/g)
    .map(function(x){return x.replace(/.*(href\s*=\s*"[^"]*").*/,'$1');})
    

    你选择!

    【讨论】:

    • 我认为贪婪的[^&lt;]+ 是有问题的。
    • 怎么来的?是当时我能想到的将捕获保持在 本身内的唯一可靠的..
    • 考虑:&lt;a img="abc.gif"&gt; href="ftp://example.com" &lt;/a&gt;
    • @JonathanLeffler 我认为将 [^] 可以解决这个问题吗?
    • 这当然是一种改进。我可能是个混蛋并设计:&lt;alarm href="ftp://example.com"&gt;,我想,但我还是给了你一个 +1
    猜你喜欢
    • 1970-01-01
    • 2011-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多