python - 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', '']
解决方案
尝试:
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,.:;]
到比赛结束。如果它是任何指定的字符,则^
确保我们将避免匹配最终字符。这样可以避免链接直接在它们之后吞噬标点符号,例如逗号。
推荐阅读
- mysql - Django Google App Engine 服务器错误 500
- angular - 无法在 Angular 8 HttpClient 的帮助下接收 XML 响应
- spacy - Windows 10下安装spacy的问题
- php - 如何在php中的递归函数中返回数组
- r - 在 R 中有没有办法逃避替代()函数?
- postgresql - POSTGRES 检查提供的值是否存在于数组类型的列中
- android - 如果数量增加或减少,总体效果如何?
- javascript - 当单击外部/其他单选按钮时,Bootstrap 4 删除折叠
- javascript - 将逗号分隔值附加到 url 作为搜索参数
- php - 如何在 php 中强制重新连接到我的数据库?