首页 > 解决方案 > Python 通过带有和不带有 href 的 url 拆分字符串

问题描述

实际上我的脚本按预期工作(按 url 拆分字符串并维护其他文本)并放入列表中:

import re
s = 'This is my tweet check it out http://www.example.com/blah and http://blabla.com'
result = re.split(r'(https?://\S+)', s)
print(result)

输出:

['This is my tweet check it out ', 'http://www.example.com/blah', ' and ', 'http://blabla.com', '']

现在我陷入了另一个问题:有时我将 url 作为 html 或混合文本 + html 获取,并且 url 是这样的:

<a href="http://www.example.com/full/path/to/product/">https://shorted.com/FJAKS</a>

href完整的 url,缩短的 url之间<a>...</a>的值。

所以我可以接收这样的字符串来操作:

s = 'This is an html link: <a href="http://www.example.com/full/path/to/product/">https://shorted.com/FJAKS</a> and this is a text url: http://blabla.com'

我想为我的函数获得相同的逻辑,但如果我使用:

result = re.split(r'(https?://\S+)', s)
print(result)

像以前一样,我明白了(错误):

['This is an html link: <a href="', 'http://www.example.com/full/path/to/product/">https://shorted.com/FJAKS</a>', ' and this is a text url: ', 'http://blabla.com', '']

但我想得到这样的情况(如果是 HTML,则获取所有a标签):

预期输出:

['This is an html link: ', '<a href="http://www.example.com/full/path/to/product/">https://shorted.com/FJAKS</a>', ' and this is a text url: ', 'http://blabla.com', '']

标签: pythonsplit

解决方案


尝试:

s = 'This is an html link: <a href="http://www.example.com/full/path/to/product/">https://shorted.com/FJAKS</a> and this is a text url: http://blabla.com'
result = re.split(r'((?:<a href=")?https?://\S+[^\s,.:;])', s)
print(result)

关键是添加(?:<a href=")?(?:)指未被捕获的组;它很有用,因此?适用于整个单元而不是单个字符。

注意:开头或结尾的 URL 会创建一个空白列表项。如果您想删除这些,请尝试:

result = list(filter((None, result)))

编辑:添加[^\s,.:;]到比赛结束。如果它是任何指定的字符,则^确保我们将避免匹配最终字符。这样可以避免链接直接在它们之后吞噬标点符号,例如逗号。


推荐阅读