2011-06-20 42 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