微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

正则表达式向 URL 添加尾部斜杠,除非 URL 后跟特定的子文件夹

如何解决正则表达式向 URL 添加尾部斜杠,除非 URL 后跟特定的子文件夹

如果不存在尾随斜杠,我想向特定 URL 结构添加尾随斜杠。此网址应为:

/product/product-#/

一个条件是,如果 URL 具有后续子文件夹,则不应将尾部斜杠添加到 URL。此网址应为:

/product/product-#/subfolder/subpage

因此,以下示例网址应以斜杠结尾:

/product/product-1 becomes /product/product-1/
/product/product-2 becomes /product/product-2/
/product/product-3 becomes /product/product-3/
/product/product-4/ remains /product/product-4/

因此,以下示例网址不应以斜杠结尾:

/product/product-1/subfolder/1456 remains /product/product1/subfolder/1456
/product/product-2/subfolder/6789 remains /product/product-2/subfolder/6789

我的尝试 here 不起作用,子文件夹后面的斜杠未在非捕获组中注册

\/(?!.*(?:subfolder\/[0-9]{4})$)[^\/]+$

解决方法

对于您显示的示例,请尝试以下正则表达式。

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

您在进行 url-rewriting 时需要在替换部分使用 $1/

Online demo for above regex

说明:为以上添加详细说明。

^                   ##Matching from starting of value here.
(                   ##Starting capturing group from here.
  \/[^\/]*\/[^\/]*  ##Matching 1 slash followed by values till next slash comes.
                    ##Followed by slash and match all values till next slash comes
)                   ##Closing capturing group here.
\/?$                ##Matching optional / at the end of value here.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。