Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 替换URL字符串中的主机名_Ruby_Regex - Fatal编程技术网

Ruby 替换URL字符串中的主机名

Ruby 替换URL字符串中的主机名,ruby,regex,Ruby,Regex,原始问题 我有一个字符串URL,我需要提取URL的子域。 我的URL看起来像: user[:href] = "https://www.example.com/user-detail/1231-N-F-Albert" 我需要摘录: "https://www.example.com/" "https://www.example.com/user-detail" 并返回: "/user-detail/1231-N-F-Albert" "1231-N-F-Albert" 是否有任何方法删除主机

原始问题

我有一个字符串URL,我需要提取URL的子域。 我的URL看起来像:

user[:href] = "https://www.example.com/user-detail/1231-N-F-Albert"
我需要摘录:

"https://www.example.com/"
"https://www.example.com/user-detail"
并返回:

"/user-detail/1231-N-F-Albert"
"1231-N-F-Albert"
是否有任何方法删除主机名并仅返回子域?我试过:

URI.parse(user[:href]).host.replace("")
但它还是空的。还有其他的方法吗

新问题

我已经改变了问题。我需要摘录:

"https://www.example.com/"
"https://www.example.com/user-detail"
并返回:

"/user-detail/1231-N-F-Albert"
"1231-N-F-Albert"

有没有办法做到这一点?我尝试使用正则表达式,但没有成功。

使用URI解析器并返回路径:

URI.parse("https://www.example.com/user-detail/1231-N-F-Albert").path
#=> "/user-detail/1231-N-F-Albert"

使用以下代码。希望它干净易懂

require 'uri'
URI("http://www.mydomain.qwe/directory").path
# => "/directory"
使用


或者,如果您需要更好的UTF-8支持,请使用Addressable::URI。@rubyst:请查看我的答案以了解更新的问题