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

问题描述 投票:12回答:3

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

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

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

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

谢谢。

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

ruby parsing
3个回答
25
投票

我这样做:

require 'uri'

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

URI内置于Ruby中。它不是功能最齐全的,但它足以为大多数URL执行此任务。如果你有IRIs然后看看Addressable::URI


8
投票

您可以使用URI

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

然后你就可以在主机上工作了。 或者有来自domainatrix的宝石Remove subdomain from string in ruby

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"

你可以拿走子域名。


2
投票

好吧,你可以使用正则表达式。像/http:\/\/([^\.]+)/这样的东西,也就是第一组非'''。 http之后的字母。

看看http://rubular.com/。您也可以针对一组测试测试正则表达式,这对于学习此工具非常有用。

© www.soinside.com 2019 - 2024. All rights reserved.