Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What regex can I use to get the domain name from a url in Ruby?

Tags:

regex

ruby

I am trying to construct a regex to extract a domain given a url.

for:

http://www.abc.google.com/
http://abc.google.com/
https://www.abc.google.com/
http://abc.google.com/

should give:

abc.google.com
like image 991
anusuya Avatar asked Jul 24 '10 08:07

anusuya


2 Answers

URI.parse('http://www.abc.google.com/').host
#=> "www.abc.google.com"

Not a regex, but probably more robust then anything we come up with here.

URI.parse('http://www.abc.google.com/').host.gsub(/^www\./, '')

If you want to remove the www. as well this will work without raising any errors if the www. is not there.

like image 101
Alex Wayne Avatar answered Sep 20 '22 12:09

Alex Wayne


Don't know much about ruby but this regex pattern gives you the last 3 parts of the url excluding the trailing slash with a minumum of 2 characters per part.

([\w-]{2,}\.[\w-]{2,}\.[\w-]{2,})/$
like image 31
Fabian Avatar answered Sep 16 '22 12:09

Fabian