您将如何在 Ruby 中解析 url 以获取主域? [英] How would you parse a url in Ruby to get the main domain?

查看:33
本文介绍了您将如何在 Ruby 中解析 url 以获取主域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够使用 Ruby 解析任何 URL 以获取域的主要部分,而无需 www(只是 example.com)

I want to be able to parse any URL with Ruby to get the main part of the domain without the www (just the example.com)

推荐答案

这几乎适用于任何 URL:

This should work with pretty much any URL:

# URL always gets parsed twice
def get_host_without_www(url)
  url = "http://#{url}" if URI.parse(url).scheme.nil?
  host = URI.parse(url).host.downcase
  host.start_with?('www.') ? host[4..-1] : host
end

或者:

# Only parses twice if url doesn't start with a scheme
def get_host_without_www(url)
  uri = URI.parse(url)
  uri = URI.parse("http://#{url}") if uri.scheme.nil?
  host = uri.host.downcase
  host.start_with?('www.') ? host[4..-1] : host
end

您可能必须要求'uri'.

这篇关于您将如何在 Ruby 中解析 url 以获取主域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆