登录
首页 >  Golang >  Go问答

正则表达式从斜杠提取内容到行尾、斜杠或查询字符串

来源:stackoverflow

时间:2024-03-20 09:56:09 467浏览 收藏

本指南提供了从斜杠提取内容到行尾、斜杠或查询字符串的正则表达式。该指南包括了以下示例: - https://www.somedomain/path/some-slug-94690(不匹配) - https://www.somedomain.com/one/somepath/another-slug?test(another-slug) - https://www.anotherdomain.com/somepath/another-slug/?test(another-slug) - https://www.anotherdomain.com/path/another_slug.html?test=true (another-slug) 指南还提供了两个正则表达式,可以用于从斜杠提取内容: - /[^?/]*/?(?=\?|$) - /[^?/]*/?(?:\?|$)

问题内容

我试图将任意深度的路径中的最后一个斜杠与路径的末尾相匹配。我如何调整这个以便示例匹配?

([^/]+[.html]?)/?\?
  1. https://www.somedomain/path/some-slug-94690(不匹配)
  2. https://www.somedomain.com/one/somepath/another-slug?test(another-slug)
  3. https://www.anotherdomain.com/somepath/another-slug/?test(another-slug)
  4. https://www.anotherdomain.com/path/another_slug.html?test=true (another-slug)

https://regex101.com/r/bfz9mw/1


解决方案


以下模式似乎有效:

/[^?/]*/?(?=\?|$)

Demo

这是正则表达式的解释:

/         match a (possibly) final path separator
[^?/]*    match zero or more non / or ? characters
/?        optionally match one more path separator
(?=\?|$)  which is followed by either `?` or the end of the string

编辑:

如果您的正则表达式版本不支持前瞻,请改用以下类似的模式:

/[^?/]*/?(?:\?|$)

然后,修剪掉尾随的 ?(如果存在)。在 go 上,您可以使用 strings.trimright,其中 ? 作为要修剪的字符。

终于介绍完啦!小伙伴们,这篇关于《正则表达式从斜杠提取内容到行尾、斜杠或查询字符串》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>