python - re.findall -> Python 中的正则表达式
问题描述
import regex
frase = "text https://www.gamivo.com/product/sea-of-thieves-pc-xbox-one other text https://www.gamivo.com/product/fifa-21-origin-eng-pl-cz-tr"
x = regex.findall(r"/((http[s]?:\/\/)?(www\.)?(gamivo\.com\S*){1})", frase)
print(x)
结果:
[('www.gamivo.com/product/sea-of-thieves-pc-xbox-one', '', 'www.', 'gamivo.com/product/sea-of-thieves-pc-xbox-one'), ('www.gamivo.com/product/fifa-21-origin-eng-pl-cz-tr', '', 'www.', 'gamivo.com/product/fifa-21-origin-eng-pl-cz-tr')]
我想要类似的东西:
[('https://www.gamivo.com/product/sea-of-thieves-pc-xbox-one', 'https://gamivo.com/product/fifa-21-origin-eng-pl-cz-tr')]
我怎样才能做到这一点?
解决方案
你需要
- 删除使/
/
的匹配无效的初始字符,因为出现在之后https://
http://
/
http
- 删除不必要的捕获组和
{1}
量词 - 将可选捕获组转换为非捕获组。
请参阅此 Python 演示:
import re
frase = "text https://www.gamivo.com/product/sea-of-thieves-pc-xbox-one other text https://www.gamivo.com/product/fifa-21-origin-eng-pl-cz-tr"
print( re.findall(r"(?:https?://)?(?:www\.)?gamivo\.com\S*", frase) )
# => ['https://www.gamivo.com/product/sea-of-thieves-pc-xbox-one', 'https://www.gamivo.com/product/fifa-21-origin-eng-pl-cz-tr']
也请参阅正则表达式演示。另外,请参阅相关的re.findall 行为怪异的帖子。
推荐阅读
- ios - 将约束添加到底部锚点正在添加到超级视图底部的约束
- c++11 -
没有这样的文件或目录 - java - 为什么我会在 Spring 实例化的组件中找到静态字段?
- reactjs - 如何保护中继中的查询节点(id:ID!)?
- java - 有没有办法让按钮对对象执行操作而不创建实现 ActionListener 的新类?
- angular - 用户登录后,Angular 8 和 Firebase AuthGuard 仍然重定向到登录
- excel - 想要在 n 次复制功能中复制单元格值而不是公式
- javascript - P5 绕圈移动物体未能破坏旧物体
- python - 用返回值替换参数值
- python - 获取设备名称python