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

后端 未结 4 1087
醉梦人生
醉梦人生 2021-01-12 21:07

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/
         


        
4条回答
  •  醉酒成梦
    2021-01-12 21:40

    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.

提交回复
热议问题