正则需求:匹配含X(邮编)不含Y(非邮路段)的URL路径
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).
Recommended Regex
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 likein-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 like63000-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
63000and63000-cedex-01, but ignorein-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

