gpt4 book ai didi

Python 正则表达式交替

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

我正在尝试以 "http://something"https://something. 的形式查找网页上的所有链接。我制作了一个正则表达式它有效:

L = re.findall(r"http://[^/\"]+/|https://[^/\"]+/", site_str)

但是,有没有更短的写法?我重复了 ://[^/\"]+/两次,可能不需要。我尝试了各种方法,但没有用。我试过:

L = re.findall(r"http|https(://[^/\"]+/)", site_str)
L = re.findall(r"(http|https)://[^/\"]+/", site_str)
L = re.findall(r"(http|https)(://[^/\"]+/)", site_str)

很明显我在这里遗漏了一些东西,或者我只是不太了解 python 正则表达式。

最佳答案

您正在使用捕获组,并且 .findall() alters behaviour when you use those (它只会返回捕获组的内容)。您的正则表达式可以简化,但如果您改用捕获组,您的版本将有效:

L = re.findall(r"(?:http|https)://[^/\"]+/", site_str)

如果在表达式周围使用单引号,则不需要对双引号进行转义,只需改变表达式中的 s,so s? 也可以:

L = re.findall(r'https?://[^/"]+/', site_str)

演示:

>>> import re
>>> example = '''
... "http://someserver.com/"
... "https://anotherserver.com/with/path"
... '''
>>> re.findall(r'https?://[^/"]+/', example)
['http://someserver.com/', 'https://anotherserver.com/']

关于Python 正则表达式交替,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16875404/

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