我有一根这样的绳子
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]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', strings)
print links
// result always same as strings
您的问题是,
http://
被接受为url的有效部分。这是因为这里的代币:或者更具体地说:
^{pr2}$这将匹配范围从
$
到_
的所有字符,其中包含的字符可能比您预期的要多得多。在您可以将其更改为
[$\-_@.&+]
,但这会导致问题,因为现在,/
字符将不匹配。所以用[$\-_@.&+/]
添加它。但是,这将再次导致问题,因为http://example.com/path/topage.htmlhttp
将被视为有效匹配。在最后添加的是添加一个lookahead以确保您没有匹配},这恰好是regex的第一部分!在
http://
或{测试here
问题是你的regex模式太包容了。它包括所有的url。可以通过使用(?)来使用lookahead?=)
试试这个:
一个简单而又不复杂的答案:
如果要将字符串
http://
和https://
追加回url,请对代码进行适当的更改。希望我能传达这个想法。在相关问题 更多 >
编程相关推荐