Deekor Deekor - 6 months ago 9
Ruby Question

Find a url in a string

Is there a pre-built way to find a url in a string in

ruby
? I have heard of
URI::Extract
but playing around with it, it only seems to find urls prefixed with
http://


I need to able to find any url in a string, for example:

http://test.com
http://www.test.com
www.test.com
test.com


Should all be found and returned to me.

I know I could tackle this in regex but I would much rather use anything prebuilt if there it exists. Especially as it should find
.net
,
.org
,
.edu
etc.

Answer

I don't think there is anything pre-built for finding "strings with dots in them". Here's a start for a regex:

str =<<END_OF_STRING
http://test.com
hello.
hello http://www.test.com world
.world
hi www.test.com world
test.com
END_OF_STRING


results = str.scan(/
  \S+
  [.]
  \S+
/xms)

--output:--
["http://test.com", "http://www.test.com", "www.test.com", "test.com"]
Comments