我有一个这样的字符串
http://example.com/path/topage.htmlhttp://twitter.com/p/xyanhshttp://httpget.org/get.zipwww.google.com/privacy.htmlhttps://goodurl.net/
我想提取所有的网址/网页地址到一个数组。例如
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]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', strings)
print links
// result always same as strings
发布于 2016-08-03 05:39:15
问题是您的正则表达式模式包含太多。它包括所有urls。您可以通过使用(?=)来使用lookahead
试试这个:
re.findall("((www\.|http://|https://)(www\.)*.*?(?=(www\.|http://|https://|$)))", strings)
发布于 2016-08-03 05:46:36
您的问题是http://
已被接受为url的有效部分。这是因为这里有这个标记:
[$-_@.&+]
或者更具体地说:
$-_
这将匹配从$
到_
范围内的所有字符,其中包含的字符可能比您预期的要多得多。
您可以将其更改为[$\-_@.&+]
,但这会导致问题,因为现在,/
字符将不匹配。因此,可以使用[$\-_@.&+/]
添加它。但是,这将再次导致问题,因为http://example.com/path/topage.htmlhttp
将被视为有效匹配。
最后添加的是添加一个先行检查,以确保您不匹配http://
或https://
,这恰好是您的正则表达式的第一部分!
http[s]?://(?:(?!http[s]?://)[a-zA-Z]|[0-9]|[$\-_@.&+/]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+
测试过的here
发布于 2016-08-03 06:02:54
一个简单的答案,不用太复杂:
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://
追加回urls,请对代码进行适当的更改。希望我能传达出我的想法。
https://stackoverflow.com/questions/38730782
复制相似问题