删除段并用正则表达式替换 url

Remove segments and replaces in url with regex

我有这个练习:

有这些链接

1. http://example.com/cat1/subcat3/subcat4/tag/this%20is%20page/asdasda?start=130
2. http://example.com/cat1/subcat3/subcat4/tag/this%20is%20pageasdasd
3. example.it/news/tag/this%is%20n%page?adsadsadasd
4. http://example.com/tag/thispage/asdasdasd.-?asds=
5. http://example.com/tag/this%20is%20page/asdasd
6. /tag/this/asdasdasd
7. /tag/asd-asd/feed/this-feed
8. /tag/sd-asd

但是第八个不能被正则表达式考虑。域名也一样。

我试图做到:https://regex101.com/r/aB5mPn/5 但我无法不考虑最后一种情况。

谁能帮帮我?

如果我没记错的话,你可以在匹配 /tag...etc 之前添加一个否定前瞻,以断言后面的八种情况不是 /tag/sd-asd 直到字符串结尾 (?!\/tag\/[^\/]+$)

您的正则表达式可能如下所示:

(?:(?:\/[A-Za-z0-9-]+)?)+(?!\/tag\/[^\/]+$)(\/tag\/[A-Za-z0-9-%]+)(.*)