gpt4 book ai didi

Python 正则表达式返回空字符串而不是结果

转载 作者:太空宇宙 更新时间:2023-11-03 18:39:21 25 4
gpt4 key购买 nike

我一直在尝试使用 Python 的正则表达式模块:Re。

我决定编写一个简单的表达式来搜索文件中的链接 (href="url")。

这是我的正则表达式:href *= *(\"|\').*\1

当我使用名为 GSkinner 的网站时,我决定尝试一下我的表达方式。结果是here ,以及代码。

当我决定在 python 正则表达式上尝试时,我使用了以下代码:

lines = """Code found in link"""
results = re.findall(r"href *= *(\"|\').*\1", lines)
print results # Ouputs: ['"', '"'] instead of two provided links

为什么结果输出为空字符串?

最佳答案

findall 将仅返回捕获的内容(除非没有捕获任何内容)。您还必须捕获您想要的值(value):

r"href *= *(\"|\')(.*?)\1

总的来说,您可能想使用类似的东西:

results = [x[1] for x in re.findall(r"href *= *(\"|\')(.*?)\1", lines)]

关于Python 正则表达式返回空字符串而不是结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20891981/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com