【问题标题】:A lookaround regex to find html tags without both attributes查找没有这两个属性的 html 标记的环视正则表达式
【发布时间】:2014-03-21 13:59:04
【问题描述】:

我需要一个正则表达式来搜索一些 HTML 并找到所有具有此属性的 <img> 标记:class="lazy" 而不是那个:data-original="..."

这是我的示例测试标记:

<!-- Must match : -->
<img class="lazy" src="http://lorempicsum.com/futurama/350/200/1" alt="Lorem ipsum" />
<img class="lazy" src="http://placehold.it/640x360/abd125/fff" />
<img class="lazy" src="http://placehold.it/640x360/000/fff"
alt="Blabla" />

<!-- Must not match : -->
<img class="lazy" src="http://placehold.it/255x200/111/fff&text=loading" data-original="http://lorempicsum.com/futurama/255/200/2" width="255" height="200" alt="" />
<img src="http://placehold.it/640x360/111/fff" alt="Blabla" />
<img src="http://placehold.it/640x360/333/fff"
alt="Blabla" />

我写了这个:&lt;img[^&gt;]*class\s*=\s*["']lazy["'][^&gt;]*(?!data-original)[^&gt;]*&gt;

这不起作用,因为它匹配第 4 个标签并且它不能匹配。

你能帮帮我吗?谢谢。

附:兄弟们别着急,我不是要parse html the Cthulhu Way,我只需要快速找到这些标签来修复大量的网页模板,这是一招鲜...

【问题讨论】:

    标签: html regex regex-negation regex-lookarounds


    【解决方案1】:

    您必须在img 标记之后检查负前瞻(?![^&gt;]*data-original)

    <img(?![^>]*data-original)[^>]*class\s*=\s*["']lazy["'][^>]*>
    

    【讨论】:

      【解决方案2】:

      您需要以某种方式修复前瞻,因为如果它移动,您可能会错过“匹配失败”部分,并且将 class='lazy' 也放在前瞻中也是一个好主意,您可以也许这样做:

      <img(?=[^>]*class\s*=\s*(["'])lazy\1)(?![^>]*data-original)[^>]*>
      

      这样,您也不必担心出现data-originalclass='lazy' 的顺序。

      regex101 demo

      【讨论】:

        猜你喜欢
        • 2010-12-10
        • 2013-06-16
        • 1970-01-01
        • 1970-01-01
        • 2013-03-31
        • 1970-01-01
        • 1970-01-01
        • 2019-04-12
        • 1970-01-01
        相关资源
        最近更新 更多