You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写正则匹配/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.

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 /foo or /foo/bar/baz)
    • ?: Makes this entire group optional, so the base path /path/subpath itself 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 after subpath. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:07:12