2011-06-20 48 views
2

我正在使用Ruby on Rails 3.0.7,並且我想從字符串「exctract」(或文本)中存在的所有鏈接。構建一個匹配鏈接數組

這時我已經爲了匹配網址和電子郵件地址以下的正則表達式*:

/((\S+)?(@|mailto\:)|((ht|f)tp(s?)\:\/\/)|([www]))\S+/ 

如果我有以下字符串

text here http://www.sitename.com and text here www.sitename.com and text here [email protected] and text here 

我想獲取上面字符串中存在的鏈接所組成的數組(或其他數據結構)。

我該怎麼辦?


* BTW:是對正則表達式 「好」 就夠了嗎?

回答

0

也許是這樣的:

text = 'text here http://www.sitename.com and text here www.sitename.com and text here [email protected] and text here' 
links = [] 
text.split.each do |word| 
    links << word if word.match(/(((\S+)?)((@|mailto\:)|(((ht|f)tp(s?))\:\/\/)|([www]))\S+)/) 
end 
puts links