【发布时间】:2013-06-29 02:49:15
【问题描述】:
我基本上有一个用 Python 编写的 RSS 索引应用程序,它将 RSS 内容作为简介存储在数据库中。应用最初处理文章内容时,会注释掉所有不符合特定条件的链接,例如:
<a href="http://google.com">Google</a>
成为:
<!--<a href="http://google.com">Google</a>--> Google
现在我需要处理所有这些旧文章并修改链接。所以使用 BeautifulSoup 4 我可以很容易地找到 cmets 使用:
links = soup.findAll(text=lambda text:isinstance(text, Comment))
for link in links:
text = re.sub('<[^>]*>', '', link.string)
# any html in the link tag was escaped by BS4, so need to convert back
text = text.replace('&lt;','<')
text = text.replace('&gt;','>')
find = link.string + " " + text
上面“find”的输出是:
<!--<a href="http://google.com">Google</a>--> Google
这样可以更轻松地对内容执行.replace()。
现在我遇到的问题(我相信这很简单)是多行查找/替换。当 Beautiful Soup 最初注释掉链接时,一些链接被转换为:
<!--<a href="http://google.com">Google
</a>--> Google
或
<!--<a href="http://google.com">Google</a>-->
Google
很明显,replace(old,new) 不起作用,因为replace() 不涵盖多行。
有人可以帮助我使用正则表达式多行查找/替换吗?它应该区分大小写。
【问题讨论】:
标签: python regex beautifulsoup