如何使用正则表达式仅从以下字符串中提取URL?

时间:2018-12-29 03:32:19

标签: python regex python-3.x python-2.7

我正在从一组原始数据中提取URL,我打算使用python正则表达式来做到这一点。

我尝试了

http://dcwweb.azurewebsites.net/ 
   username: sw password: sw

但是它整个部分都从http开始。

输入

  

href =“ http://twitter.com/download/iphone” rel =“ nofollow”>适用于iPhone的Twitter

     

https://vine.co/v/i6iIrBwnTFI

预期产量

  
    

http://twitter.com/download/iphone

         

https://vine.co/v/i6iIrBwnTFI

  

2 个答案:

答案 0 :(得分:0)

尝试以下操作:http[^\"^\s]*

这假定您的所有链接都将以http开头,并且如果遇到空格或"

,它将破坏表达式

这里是您如何使用它:

import re
regexp = '''http[^\"^\s]*'''
urls = '''href="http://twitter.com/download/iphone" rel="nofollow">Twitter for iPhone https://vine.co/v/i6iIrBwnTFI'''
output = re.findall(regexp, urls)
output
  

['http://twitter.com/download/iphone',   'https://vine.co/v/i6iIrBwnTFI']

答案 1 :(得分:0)

首先,您应该找到what-characters-are-valid-in-a-url

然后,正则表达式可以是:

(http://|https://)([a-zA-Z0-9\-\._~:/\?\#\[\]@!$&'\(\)\*\+,;=]+)

在我的python解释器中,它看起来像:

>>> import re
>>> regexp = '''(http://|https://)([a-zA-Z0-9\-\._~:/\?\#\[\]@!$&'\(\)\*\+,;=]+)'''
>>> url = '''href="http://twitter.com/download/iphone" rel="nofollow">Twitter for iPhone https://vine.co/v/i6iIrBwnTFI'''
>>> r = re.findall(regexp, url)
>>> r
[('http://', 'twitter.com/download/iphone'), ('https://', 'vine.co/v/i6iIrBwnTFI')]
>>> [x[0]+x[1] for x in r]
['http://twitter.com/download/iphone', 'https://vine.co/v/i6iIrBwnTFI']
相关问题