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

正则需求:匹配含X(邮编)不含Y(非邮路段)的URL路径

Solution to Match Postcode Path Segments & Exclude Non-Postcode Routes

Got it, let's fix this regex issue for your URL routes! The core problem with your current [0-9a-z\-]+ regex is that it’s too broad—it matches any lowercase alphanumeric string with hyphens, including non-postcode paths like in-a-25-km-radius. The key fix is leaning into the unique trait of your postcode format: it always starts with numbers (unlike the problematic non-postcode paths which start with letters).

Here's a refined regex that targets your postcode format while excluding unwanted paths:

^[0-9]+(?:-[a-z0-9]+)*$

What This Regex Does

Let’s break it down piece by piece:

  • ^: Anchors the match to the start of the path segment (ensures we don’t match partial strings)
  • [0-9]+: Requires the segment to start with one or more digits (immediately rules out letter-starting paths like in-a-25-km-radius)
  • (?:-[a-z0-9]+)*: Allows zero or more additional segments separated by hyphens. Each segment can include letters or digits (perfect for formats like 63000-cedex-01). The ?: makes this a non-capturing group (keeps the regex efficient, no need to store this part separately)
  • $: Anchors the match to the end of the path segment (ensures we don’t match partial postcodes or extra characters)

Alternative (Simpler) Version

If you don’t need to enforce the "hyphen-separated segments" structure and just want to exclude letter-starting paths, this simpler regex works too:

^[0-9][0-9a-z\-]*$

This just requires the segment to start with a digit, followed by any combination of digits, lowercase letters, or hyphens. It’s more flexible but still blocks the problematic in-a-25-km-radius path.

How to Use It in Your Routes

Replace your original regex [0-9a-z\-]+ with the refined version. For example:

  • For the route domain.tld/clermont-ferrand/{postcode}/, use the pattern:
    /clermont-ferrand/([0-9]+(?:-[a-z0-9]+)*)/
    
  • This will correctly match 63000 and 63000-cedex-01, but ignore in-a-25-km-radius.

Test Cases

Let’s verify it works as expected:

  • ✅ Matches valid postcodes: 63000, 63000-cedex-01, 75001-paris
  • ❌ Rejects non-postcode paths: in-a-25-km-radius, search-results, filter-by-price

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:30:18