如何从 Ruby 中的 URL 中删除多个尾部斜杠 [英] How can multiple trailing slashes can be removed from a URL in Ruby
问题描述
我想在这里实现的是假设我们有两个示例 URL:
What I'm trying to achieve here is lets say we have two example URLs:
url1 = "http://emy.dod.com/kaskaa/dkaiad/amaa//////////"
url2 = "http://www.example.com/"
我如何提取条带化的 URL?
How can I extract the striped down URLs?
url1 = "http://emy.dod.com/kaskaa/dkaiad/amaa"
url2 = "http://http://www.example.com"
Ruby 中的
URI.parse
清理了某些类型的格式错误的 URL,但在这种情况下无效.
URI.parse
in Ruby sanitizes certain type of malformed URL but is ineffective in this case.
如果我们使用正则表达式,则 /^(.*)\/$/
从 url1
中删除一个斜线 /
并且对于url2
.
If we use regex then /^(.*)\/$/
removes a single slash /
from url1
and is ineffective for url2
.
有人知道如何处理这种类型的 URL 解析吗?
Is anybody aware of how to handle this type of URL parsing?
这里的重点是我不希望我的系统有 http://www.example.com/
和 http://www.example.com
被视为两个不同的 URL.http://emy.dod.com/kaskaa/dkaiad/amaa////
和 http://emy.dod.com/kaskaa/dkaiad/amaa/也是如此代码>.
The point here is I don't want my system to have http://www.example.com/
and http://www.example.com
being treated as two different URLs. And same goes for http://emy.dod.com/kaskaa/dkaiad/amaa////
and http://emy.dod.com/kaskaa/dkaiad/amaa/
.
推荐答案
如果您只需要删除 url 字符串末尾的所有斜杠,那么您可以尝试以下正则表达式:
If you just need to remove all slashes from the end of the url string then you can try the following regex:
"http://emy.dod.com/kaskaa/dkaiad/amaa//////////".sub(/(\/)+$/,'')
"http://www.example.com/".sub(/(\/)+$/,'')
/(\/)+$/
- 此正则表达式在字符串末尾找到一个或多个斜杠.然后我们用空字符串替换这个匹配.
/(\/)+$/
- this regex finds one or more slashes at the end of the string. Then we replace this match with empty string.
希望这会有所帮助.
这篇关于如何从 Ruby 中的 URL 中删除多个尾部斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!