如何编写正则匹配/path/subpath及其子目录但排除无关路径?
Fixing Your Path Matching Regex Issue
I get it, that greedy .* wildcard is causing unintended matches—let's tweak this regex to get exactly the behavior you want.
The Problem with Your Current Regex
/path/subpath.* matches any character(s) right after subpath, including random letters appended directly to it (like subpathrandomcharacters). That's because .* doesn't respect path structure (like slashes) and just gobbles up everything in its path.
Solution 1: Explicit Path Structure Match (Recommended for Routes)
This regex will match your base path or any valid subpath that starts with a slash after it:
^/path/subpath(/.*)?$
Breakdown of the regex:
^: Anchors the match to the start of the string (prevents matching paths that contain this sequence somewhere in the middle)/path/subpath: Your exact base path(/.*)?: An optional group that handles subpaths:/: The required slash that separates the base path from subpaths.*: Matches any characters after the slash (for subpaths like/fooor/foo/bar/baz)?: Makes this entire group optional, so the base path/path/subpathitself is still matched
$: Anchors the match to the end of the string (ensures no extra, unapproved characters are appended)
Solution 2: Negative Lookahead (For Precise Control)
If you want to explicitly block any non-slash characters immediately after subpath, use this regex:
^/path/subpath(?![^/])
Breakdown:
(?![^/]): A negative lookahead that fails the match if there's any character other than a slash right aftersubpath. This means:/path/subpath(nothing after) is allowed/path/subpath/(slash after) is allowed/path/subpath/foo(slash + subpath) is allowed/path/subpathrandomcharacters(non-slash characters after) is blocked
Test Case Results
✅ Matches:
/path/subpath/path/subpath//path/subpath/foo/path/subpath/foo/bar/baz
❌ Doesn't Match:
/path/subpathrandomcharacters/path/subpathXYZ/other/path/subpath
内容的提问来源于stack exchange,提问作者darkermuffin
相关产品推荐
相关产品推荐

