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

所以给定的网址:

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

我想要结果:
http://foo.example.com:8080/
https://example.net/

我发现 URI::Parser 的 documentation 不太平易近人。

我最初的天真解决方案是一个简单的正则表达式,如:
/\A(https?:\/\/[^\/]+\/)/

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

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

最佳答案

使用 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/"

关于ruby-on-rails - Ruby/Rails 3.1 : Given a URL string, 删除路径,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6755919/

10-16 23:39