Python中使用re.findall正则提取完整Gamivo链接的实现问题
Python正则提取gamivo域名完整链接解决方案
问题根因
- 原正则开头多余的
/符号,导致无法匹配到https://开头的完整链接前缀 - 正则内包含多个捕获组,
findall方法遇到多捕获组时会返回所有组的匹配结果元组,而非完整匹配内容 http[s]?:\/\/被设为可选匹配,导致完整前缀未被捕获
基础修改方案(匹配原文本原生带www的链接)
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" # 正则使用非捕获组处理www可选逻辑,仅保留1个捕获组返回完整链接 x = regex.findall(r"(https?://(?:www\.)?gamivo\.com\S*)", frase) # 转换为列表嵌套元组的目标输出格式 output = [tuple(x)] print(output)
运行输出:
[('https://www.gamivo.com/product/sea-of-thieves-pc-xbox-one', 'https://www.gamivo.com/product/fifa-21-origin-eng-pl-cz-tr')]
完全匹配期望输出方案(统一去掉链接中的www前缀)
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"https?://(?:www\.)?gamivo\.com\S*", frase) # 替换www前缀后转换格式 output = [tuple(url.replace("www.", "") for url in x)] print(output)
运行输出:
[('https://gamivo.com/product/sea-of-thieves-pc-xbox-one', 'https://gamivo.com/product/fifa-21-origin-eng-pl-cz-tr')]
内容的提问来源于stack exchange,提问作者Diego
相关产品推荐
相关产品推荐

