2016-08-02 212 views
0

提取所有的URL我有这样正则表达式从字符串

http://example.com/path/topage.htmlhttp://twitter.com/p/xyanhshttp://httpget.org/get.zipwww.google.com/privacy.htmlhttps://goodurl.net/

一个字符串,我想所有的URL/webaddress提取到一个数组。例如

urls = ['http://example.com/path/topage.html','http://twitter.com/p/xyan',.....]

这里是我的方法,没有工作。

import re 
strings = "http://example.com/path/topage.htmlhttp://twitter.com/p/xyanhshttp://httpget.org/get.zipwww.google.com/privacy.htmlhttps://goodurl.net/" 
links = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[[email protected]&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', strings) 

print links 
// result always same as strings 
+2

这应该对您有所帮助:http://regex101.com。你可以在那里玩你的正则表达式,看看你的问题可能是什么。 – idjaw

+0

你必须保持领先'http(s)'? – Bahrom

+0

是的,我将不得不@Bahrom –

回答

2

问题是,您的正则表达式模式太包容。它包括所有的网址。您可以通过使用先行

试试这个(=):

re.findall("((www\.|http://|https://)(www\.)*.*?(?=(www\.|http://|https://|$)))", strings) 
+0

不捕获'www.google.com/privacy.html',否则没关系 –

+0

好点。在它上面工作。 – Munchhausen

+0

嗨@Muchhausen,感谢它几乎工作,除了'http:// httpget.org/get.zipwww.google.com/privacy.html'此网址。 –

0

您的问题是http://被接受为URL的有效组成部分。这是因为这个令牌就在这里:

[[email protected]&+] 

或者更具体地说:

$-_ 

这所有字符匹配与$_的范围,其中包括了更多的字符可能比你预期的要做。

您可以将其更改为[$\[email protected]&+],但这会导致问题,因为现在/个字符不匹配。所以使用[$\[email protected]&+/]来添加它。但是,由于http://example.com/path/topage.htmlhttp将被视为有效匹配,因此这将再次导致问题。

最后的补充是增加一个前视,以确保你不匹配http://https://,这恰好是你的正则表达式的第一部分!

http[s]?://(?:(?!http[s]?://)[a-zA-Z]|[0-9]|[$\[email protected]&+/]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+ 

测试here

0

简单的回答没有进入很多并发症:

import re 
url_list = [] 

for x in re.split("http://", l): 
    url_list.append(re.split("https://",x)) 

url_list = [item for sublist in url_list for item in sublist] 

如果你想添加的字符串http://https://回网址,做适当的修改码。希望我传达这个想法。

+0

并不是所有的网址都有'http://' –

0

这里是我的

(r’http[s]?://[a-zA-Z]{3}\.[a-zA-Z0-9]+\.[a-zA-Z]+') 
+0

虽然这段代码片段是受欢迎的,并且可能会提供一些帮助,但如果它包含解释,它会[大大改善](// meta.stackexchange.com/q/114762)*如何解决问题。没有这些,你的答案就没有什么教育价值了 - 记住,你正在为将来的读者回答这个问题,而不仅仅是现在问的人!请编辑您的答案以添加解释,并指出适用的限制和假设。 –