我有一个HTML字符串
I was surfing http://www.google.com, where I found my tweet,
check it out <a href="http://tinyurl.com/blah">http://tinyurl.com/blah</a>
<span>http://www.google.com</span>
对此
^{pr2}$我试试这个Demo
我的python代码是
import re
p = re.compile(ur'<a\b[^>]*>.*?</a>|((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)', re.MULTILINE)
test_str = u"I was surfing http://www.google.com, where I found my tweet, check it out <a href=\"http://tinyurl.com/blah\">http://tinyurl.com/blah</a>"
for item in re.finditer(p, test_str):
print item.group(0)
输出:
>>> http://www.google.com,
>>> <a href="http://tinyurl.com/blah">http://tinyurl.com/blah</a>
好吧,我想我终于找到你想要的了。基本思想是尝试匹配
<a href
和一个URL。如果有一个<a href
,那么不要做任何事情,但是如果没有,则添加链接。代码如下:输出:
^{pr2}$主要思想来自https://stackoverflow.com/a/3580700/5100564。我还借用了https://stackoverflow.com/a/6718696/5100564。在
您可以使regex更加复杂,但正如mikus建议的那样,执行以下操作似乎更容易:
我希望这能帮助你。在
代码:
输出:
^{pr2}$相关问题 更多 >
编程相关推荐