如何解析URL并提取所需的子字符串

说我有这样的字符串: "http://something.example.com/directory/"

我想要做的是解析这个字符串,并从字符串中提取"something"

第一步,显然是检查以确保字符串包含"http://" – 否则,它应该忽略该字符串。

但是,我如何才能在该字符串中提取"something" ? 假设将要评估的所有字符串都具有类似的结构(即我正在尝试提取URL的子域 – 如果正在检查的字符串确实是有效的URL – 其中有效的以"http://"开头)。

谢谢。

PS我知道如何检查第一部分,即我可以简单地将字符串拆分为"http://"但这并不能解决完整的问题,因为这会产生"http://something.example.com/directory/" 。 我想要的只是"something" ,没有别的。

我这样做:

 require 'uri' uri = URI.parse('http://something.example.com/directory/') uri.host.split('.').first => "something" 

URI内置于Ruby中。 它不是function最齐全的,但它足以为大多数URL执行此任务。 如果您有IRI,那么请查看Addressable :: URI 。

您可以使用URI

 uri = URI.parse("http://something.example.com/directory/") puts uri.host # "something.example.com" 

然后你就可以在主机上工作了。
或者从ruby中的字符串中删除子域中有一个gem 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" 

你可以采取子域名。

好吧,你可以使用正则表达式。 像/ /http:\/\/([^\.]+)/ 。] +)/,就是第一组非”。 http之后的字母。 查看http://rubular.com/ ,您也可以针对一组测试测试正则表达式,这对学习这个工具很有帮助:)