2011-03-30 90 views
0

可能重複:
What is the best regular expression to check if a string is a valid URL正則表達式找到的URL字符串中的

我想找到的網址,例如從字符串http://www.google.comhttp://mail.yahoo.com.uk。達到此目的的最佳方法是什麼?

+1

這是一個子字符串搜索或驗證問題? – 2011-03-30 21:22:45

+1

你知道幾乎任何東西都是有效的URL嗎?語法非常靈活。 http://tools.ietf.org/html/rfc3986。該方案和路徑組件是必需的,儘管路徑可能爲 爲空。所以'ftp:'是一個合法的URL。 – 2011-03-30 21:44:29

回答

1
>>> text = """I want to find url this "http://www.google.com" or "http://mail.yahoo.com.uk" from a string. 

I tried different exprs but no one correct. Could anyone help me? Thanks 
""" 
>>> import re 
>>> re.search('(http://www\\.google\\.com)', text) 
<_sre.SRE_Match object at 0x02183060> 
>>> _.groups() 
('http://www.google.com',) 
>>> re.search('(http://mail\\.yahoo\\.com\\.uk)', text) 
<_sre.SRE_Match object at 0x021830A0> 
>>> _.groups() 
('http://mail.yahoo.com.uk',) 
>>> re.findall('(http://[^"\' ]+)', text) 
['http://www.google.com"', 'http://mail.yahoo.com.uk"'] 

請注意,最後一個例子是非常簡化,不應該在實踐中使用。谷歌正則表達式的網址,如果你想這樣做。

相關問題