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

求助:正则表达式匹配含3个斜杠的指定URL模式

Fixing Your URL Matching Regex

Got it, let's break down what's going wrong with your current regex and build the correct pattern for your needs.

Your Requirements Recap

You want to match URLs that:

  • Start with abc.org/top/
  • Follow with one or more digits
  • End with a final segment with no extra slashes (exactly 3 slashes total in the URL, like your valid examples)
  • Reject URLs with extra path segments (more than 3 slashes) or that start with a different base path like bottoms

The Issue With Your Current Regex

Your pattern abc\.org\/top\/[0-9]+\/(.*)$ has one critical flaw: the (.*) will match any character, including slashes. That means it would accidentally match URLs with extra path segments (like your failed example abc.org/top/1567/gree-0109/size), and depending on your testing setup, might not anchor the match correctly to the start/end of the URL.

The Corrected Regex

Here's the pattern that will work exactly as you need:

^abc\.org\/top\/[0-9]+\/[^\/]+$

Let's break down each part:

  • ^: Anchors the match to the start of the string, ensuring there's no extra content before abc.org
  • abc\.org: Matches the domain (the backslash escapes the dot, which otherwise matches any character in regex)
  • \/top\/: Matches the /top/ path segment (slashes are escaped for compatibility with most regex engines)
  • [0-9]+: Matches one or more digits (you can also use \d+ as a shorthand here)
  • \/: Matches the third slash
  • [^\/]+: Matches one or more characters that are NOT slashes — this ensures the final segment has no extra path parts
  • $: Anchors the match to the end of the string, so no extra characters (like another slash or path segment) can come after

Testing the Pattern

Let's verify against your examples:

  • ✅ Matches: abc.org/top/1010/red-shirt-plus → fits the exact structure
  • ✅ Matches: abc.org/top/1567/gree-0109 → fits the exact structure
  • ❌ Rejects: abc.org/top/1567/gree-0109/size → has an extra slash and segment, which [^\/]+ won't match (since it hits a slash before the end of the string)
  • ❌ Rejects: abc.org/bottoms/1567/red-skirt-plus → doesn't start with /top/

Bonus: Matching Full URLs (with HTTP/HTTPS)

If you need to match full URLs with http:// or https:// prefixes, add an optional protocol segment at the start:

^(https?:\/\/)?abc\.org\/top\/[0-9]+\/[^\/]+$

The (https?:\/\/)? part matches an optional http:// or https:// (the ? makes the whole group optional, and s? makes the s in https optional).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:47:41