Ruby/Rails 3.1:给定URL字符串,删除path



给定任何有效的HTTP/HTTPS字符串,我想解析/转换它,使最终结果恰好是字符串的根。

给定url:

http://foo.example.com:8080/whatsit/foo.bar?x=y
https://example.net/

我想要结果:

http://foo.example.com:8080/
https://example.net/

我发现URI::Parser的文档不是很容易理解。

我最初的naïve解决方案将是一个简单的正则表达式,如:

/A(https?://[^/]+/)/

(即:匹配协议后的第一个斜杠)

的思想,解决方案的欢迎。如果这是重复的,很抱歉,但我的搜索结果并不相关。

With URI::join:

require 'uri'
url = "http://foo.example.com:8080/whatsit/foo.bar?x=y"
baseurl = URI.join(url, "/").to_s
#=> "http://foo.example.com:8080/"

使用URI.parse,然后将path设置为空字符串,query设置为nil:

require 'uri'
uri     = URI.parse('http://foo.example.com:8080/whatsit/foo.bar?x=y')
uri.path  = ''
uri.query = nil
cleaned   = uri.to_s # http://foo.example.com:8080

现在你在cleaned中有了清理后的版本。拿掉你不想要的东西有时比只拿你需要的东西更容易。

如果你只做uri.query = '',你最终会得到http://foo.example.com:8080?,这可能不是你想要的。

您可以使用uri.split()然后将部件重新组合在一起…

警告:有点草率。

url = "http://example.com:9001/over-nine-thousand"
parts = uri.split(url)
puts "%s://%s:%s" % [parts[0], parts[2], parts[3]]
=> "http://example.com:9001"

最新更新