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

如何使用fnmatch匹配指定URL?现有匹配模式失效求解决方案

Ah, I see the issue here—you're mixing up regular expression syntax with shell-style wildcards, which is why your fnmatch pattern isn't working. Let me break this down for you.

Why Your Original Pattern Fails

fnmatch uses shell glob patterns, not PCRE regular expressions. The + character in your pattern user/[0-9]+ is treated as a literal plus sign, not a "one or more" quantifier. That's why it can't match URLs like http://deploy.local/user/12.

Working Patterns for Your URLs

Let's split this into two separate patterns for each of your target URLs:

1. Match http://deploy.local/user/[digits] (e.g., /user/12)

To match any sequence of one or more digits after /user/, use a glob pattern that targets digits and allows any length of them:

// Full pattern for the numeric ID URL
fnmatch("http://deploy.local/user/[0-9]*", $url);
  • [0-9] matches a single digit
  • * matches zero or more additional characters (so this covers 1-digit, 2-digit, etc., IDs)
  • If you need to ensure there are no extra characters after the digits (e.g., block /user/12abc), you could combine this with a check that the part after /user/ is purely numeric, but glob patterns alone can't enforce "only digits" for arbitrary lengths—they're less strict than regex here. For most use cases though, the above pattern works perfectly.

2. Match http://deploy.local/user/tree

For the fixed /tree path, you can use an exact glob pattern (or a wildcard if you need to allow query parameters):

// Exact match for the /tree URL
fnmatch("http://deploy.local/user/tree", $url);

// If you need to allow query parameters (e.g., /user/tree?foo=bar)
fnmatch("http://deploy.local/user/tree*", $url);
Quick Recap of fnmatch Glob Syntax

To avoid confusion in the future, remember these key glob rules:

  • *: Matches any number of any characters (including none)
  • ?: Matches exactly one arbitrary character
  • [chars]: Matches a single character from the set/range (e.g., [0-9], [a-z])
  • No regex-specific syntax like +, * (as a quantifier), (), or ^/$ anchors works here.

内容的提问来源于stack exchange,提问作者Florian Brandt

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:19:55