我想搭配dotall和non-greedy。这就是我所拥有的:

img(.*?)(onmouseover)+?(.*?)a

但是,这并非是贪婪的。该数据与我预期的不匹配:
<img src="icon_siteItem.gif" alt="siteItem" title="A version of this resource is available on siteItem" border="0"></a><br><br></td><td rowspan="4" width="20"></td></tr><tr><td>An activity in which students find other more specific adjectives to
describe a range of nouns, followed by writing a postcard to describe a
nice holiday without using the word 'nice'.</td></tr><tr><td>From the resource collection: <a href="http://www.siteItem.co.uk/index.asp?CurrMenu=searchresults&amp;tag=326" title="Resources to help work">Drafting </a></td></tr><tr><td><abbr style="border-bottom:0px" title="Key Stage 3">thing</abbr> | <abbr style="border-bottom:0px" title="Key Stage 4">hello</abbr> | <abbr style="border-bottom:0px" title="Resources">Skills</abbr></td></tr></tbody></table></div></div></td></tr><tr><td><div style="padding-left: 30px"><div><table style="" bgcolor="#DFE7EE" border="0" cellpadding="0" cellspacing="5" width="100%"><tbody><tr valign="top"><td rowspan="4" width="60"><a href="javascript:requiresLevel0(350,350);"><img name="/attachments/3700.pdf" onmouseover="ChangeImageOnRollover(this,'/application/files/images/attach_icons/rollover_pdf.gif')" onmouseout="ChangeImageOnRollover(this,'/application/files/images/attach_icons/small_pdf.gif')" src="small_pdf.gif" alt="Download Recognising and avoiding ambiguity in PDF format" title="Download in PDF format" style="vertical-align: middle;" border="0"></a><br>790.0 k<br>

我不明白为什么。

我想在上述正则表达式中说明的是:



为什么这没有按我预期的那样工作?

重点:必须启用dotall

最佳答案

这是非贪婪的。
您对非贪婪的理解是不正确的。

正则表达式将总是尝试匹配。

让我展示一个非贪婪实际上意味着什么的简化示例(如评论所建议):

re.findall(r'a*?bc*?', 'aabcc', re.DOTALL)

这将匹配:
  • 尽可能少重复“a”(在这种情况下为2)
  • 后跟一个'b'
  • 和“c”的尽可能少的重复(在这种情况下为0)

  • 因此,唯一的匹配项是'aab'

    并得出以下结论:
    不要使用正则表达式来解析HTML。有专门为这项工作准备的图书馆。 re 不是其中之一。

    10-06 07:51
    查看更多