开发者

Build an array of matching links

开发者 https://www.devze.com 2023-03-14 17:42 出处:网络
I am using Ruby on Rails 3.0.7 and I would like to \"exctract\" from a string (or a text) all links present in that.

I am using Ruby on Rails 3.0.7 and I would like to "exctract" from a string (or a text) all links present in that.

At this time I have the following regex* in order to match URL and e-mail addresses:

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

If I have the following st开发者_StackOverflow社区ring:

text here http://www.sitename.com and text here www.sitename.com and text here email@sitename.com and text here

I would like to get an array (or some other data structure) populated of links present in the above string.

How can I do?


*BTW: Is the regex "good" enough?


Maybe something like this:

text = 'text here http://www.sitename.com and text here www.sitename.com and text here email@sitename.com 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
0

精彩评论

暂无评论...
验证码 换一张
取 消