说我有这样的字符串: "http://something.example.com/directory/"
我想要做的是解析这个字符串,并"something"从字符串中提取.
第一步,显然要检查以确保字符串包含"http://"- 否则,它应该忽略该字符串.
但是,我如何才能"something"在该字符串中提取?假设所有将要评估的字符串将具有类似的结构(即我正在尝试提取URL的子域 - 如果正在检查的字符串确实是有效的URL - 其中有效的开头"http://").
谢谢.
PS我知道如何检查第一部分,即我可以简单地将字符串拆分,"http://"但这并不能解决完整的问题,因为这会产生"http://something.example.com/directory/".我只想要的是"something",没有别的.
the*_*Man 25
我这样做:
require 'uri'
uri = URI.parse('http://something.example.com/directory/')
uri.host.split('.').first
=> "something"
Run Code Online (Sandbox Code Playgroud)
URI内置于Ruby中.它不是功能最齐全的,但它足以为大多数URL执行此任务.如果你有IRI,那么看看Addressable :: URI.
您可以使用URI
uri = URI.parse("http://something.example.com/directory/")
puts uri.host
# "something.example.com"
Run Code Online (Sandbox Code Playgroud)
然后你就可以在主机上工作了.
或者是有宝石domainatrix从删除的子域从红宝石串
require 'rubygems'
require 'domainatrix'
url = Domainatrix.parse("http://foo.bar.pauldix.co.uk/asdf.html?q=arg")
url.public_suffix # => "co.uk"
url.domain # => "pauldix"
url.subdomain # => "foo.bar"
url.path # => "/asdf.html?q=arg"
url.canonical # => "uk.co.pauldix.bar.foo/asdf.html?q=arg"
Run Code Online (Sandbox Code Playgroud)
你可以拿走子域名.