如何从 Ruby 中的 URL 中删除多个尾部斜杠

编程入门 行业动态 更新时间:2024-10-24 02:33:37
本文介绍了如何从 Ruby 中的 URL 中删除多个尾部斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想在这里实现的是假设我们有两个示例 URL:

What I'm trying to achieve here is lets say we have two example URLs:

url1 = "emy.dod/kaskaa/dkaiad/amaa//////////" url2 = "www.example/"

我如何提取条带化的 URL?

How can I extract the striped down URLs?

url1 = "emy.dod/kaskaa/dkaiad/amaa" url2 = "www.example"

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?

这里的重点是我不希望我的系统有 www.example/ 和 www.example被视为两个不同的 URL.emy.dod/kaskaa/dkaiad/amaa//// 和 emy.dod/kaskaa/dkaiad/amaa/也是如此.

The point here is I don't want my system to have www.example/ and www.example being treated as two different URLs. And same goes for emy.dod/kaskaa/dkaiad/amaa//// and emy.dod/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:

"emy.dod/kaskaa/dkaiad/amaa//////////".sub(/(\/)+$/,'') "www.example/".sub(/(\/)+$/,'')

/(\/)+$/ - 此正则表达式在字符串末尾找到一个或多个斜杠.然后我们用空字符串替换这个匹配.

/(\/)+$/ - this regex finds one or more slashes at the end of the string. Then we replace this match with empty string.

希望这会有所帮助.

更多推荐

如何从 Ruby 中的 URL 中删除多个尾部斜杠

本文发布于:2023-11-01 23:09:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1550680.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:斜杠   多个   尾部   Ruby   URL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!