如何匹配img标签-否定前瞻


how to match img tag - negate lookahead

如何匹配一个img标记与一个否定的前瞻性?

/(<img (?!.*'/>).*'/>)/i

那就是:

/(<img(?:.(?!'/>))+'/>/i

但这不是最有效的解决方案。使用向前看,最有效的是:

/(<img[^>]+(?:'/(?!>)[^>]*)*'/>)/i

将其分解,得到:

(              # begin capture
    <img       # literal "<img", followed by
    [^>]+      # everything but ">", once or more, followed by
    (?:        # begin non capturing group
      /(?!>)   # a "/", as long as it is not followed by a ">", followed by
      [^>]*    # everything but ">", zero or more times,
    )*         # zero or more times, followed by
    />         # literal "/>"
)              # end capture

这是normal* (special normal*)*的另一种应用,其中normal[^>], special/(?!>):

$ perl -ne 'm,(<img[^>]+(?:/(?!>)[^>]*)*/>), and print "-->$1<--'n"' <<EOF
no image tag here
Here there is one: <img src="foo/bar.gif"/>
<img whatever bla bla> (no match, no / before >)
EOF
--><img src="foo/bar.gif"/><--

你为什么要在这里向前看呢?

/(<img's[^>]+>)/i

然而,允许我强烈建议你在这里使用DOM解析器而不是RegEx,因为使用RegEx可能容易出错的image标签,像这样:

<img src="greater.jpg" alt="x > y" height="10" width="10">

使用非贪婪模式修饰符U

U (PCRE_UNGREEDY)

这个修饰符反转了"贪婪"。使它们在默认情况下不是贪婪的,但如果后跟?则变为贪婪的。它与Perl不兼容。也可以通过模式内的(?U)修饰语设置或量词后面的问号(例如.*?)来设置。

这将抓取所有内容,直到遇到/> (img标记的末尾)。

'/(<img(.*)/>)/Ui'