首页 > 解决方案 > JS 正则表达式匹配 URL 的所有部分,忽略由该 URL 中的动态值组成的特定路径

问题描述

正则表达式应匹配的示例 URL:

https://domain/a/b/c/d/e/i39m33rgp5jcrohl5atwe4c9/g/h.file

这不应该匹配:i39m33rgp5jcrohl5atwe4c9

我在想一些类似的事情,但https://regex101.com/上的测试似乎与它不匹配。任何指针?

^/a/([^/]+/)?([^/]+/)?([^/]+/)?([^/]+/)?([^/]+/)?([^/]+/)(\.file)?$

标签: regex

解决方案


使用您显示的示例,您能否尝试以下操作。

(^https?:\/\/(?:.*?\/){6}).*?\/(.*)$

上述正则表达式的在线演示

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

(               ##Starting 1st capturing group here.
  ^https?:\/\/  ##Checking condition if value starts from http/https://
  (?:.*?\/){6}  ##In a non-capturing group doing non-greedy match till / up to 6 times, just before dynamic value in URL.
)               ##Closing 1st capturing group here.
.*?\/           ##Again going non-greedy match till next occurrence of / here.
(.*)$           ##In 2nd capturing group having everything, rest of URL here.

推荐阅读