gpt4 book ai didi

python - 我可以使用 dotall 的非贪婪正则表达式吗?

转载 作者:太空狗 更新时间:2023-10-29 20:39:03 25 4
gpt4 key购买 nike

我想匹配 dotall 和非贪婪。这是我的:

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>

我不明白为什么。

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

start with "img", then allow 0 or more any character including new line, then look for at least 1 "onmouseover", then allow 0 or more any character including new line, then an "a"

为什么这不像我预期的那样工作?

要点:必须启用 dotall

最佳答案

它是非贪婪的。是你对非贪婪的理解不正确。

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

让我展示一个简化的示例,说明非贪婪的实际含义(如评论所建议的):

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

这将匹配:

  • 尽可能少地重复“a”(在本例中为 2 次)
  • 后跟一个'b'
  • 尽可能少地重复“c”(在本例中为 0)

所以唯一的匹配是'aab'

总结一下:

不要使用正则表达式来解析 HTML。有些库是为这项工作而设计的。 re不是其中之一。

关于python - 我可以使用 dotall 的非贪婪正则表达式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9507819/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com