Skip to main content
 首页 » 编程设计

Python 正则表达式交替

2025年05月04日23langtianya

我正在尝试以 "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/']