Today I Learned

hashrocket A Hashrocket project


You can generate a regular expression that matches URIs using URI from Ruby's stdlib:

require 'uri'

matcher = URI.regexp(["http"])
md = matcher.match("I like, for real")
#=> #<MatchData "" 1:"http" 2:nil 3:nil 4:"" 5:nil 6:nil 7:nil 8:nil 9:nil>
#=> ""

You can use this with String#scan to extract all URIs from a string:

urls= []
"I like, for real. Also, http://localhost:3000 is useful.".scan(matcher) { urls << Regexp.last_match[0] }
#=> ["", "http://localhost:3000"]

See for more information.

See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.