正则表达式匹配需求咨询:仅匹配产品分类页,排除产品页及带参页
Hey there! Let's work through each of your URL matching requirements with targeted regex patterns and clear explanations to fix those edge cases you're hitting.
1. Match Product Category Pages, Exclude Product Pages & Parameter-Free Pages
Requirement Breakdown:
You want to target URLs pointing to a product category (with a category name present), while excluding:
- Specific product pages (e.g.,
/products/category_name/product_name) - Empty/parameter-free pages (e.g.,
/productsor/products/)
Solution Regex:
^www\.site\.com/products/[^/]+/?$
Explanation:
^anchors the match to the start of the URLwww\.site\.com/products/matches the base path (note escaped dots\.to match literal dots)[^/]+matches one or more characters that are not a slash — this ensures we only capture a single category name (no nested product paths)/?$allows an optional trailing slash and anchors the match to the end of the URL, so no extra paths (like product names) can follow
2. Explicitly Match Only Category URLs, Exclude Product URLs
Requirement Breakdown:
You need to match these two URLs exclusively:
www.site.com/products/category_namewww.site.com/products/category_name/
And exclude this URL:
www.site.com/products/category_name/product_name
The Problem with Your Current Regex:
Your pattern ^www.site.com/products/(.*)[^/]$ fails because .* is a greedy match — it will consume all characters up to the final non-slash character, including category_name/product_name. That's why it incorrectly matches the product URL.
Fixed Solution Regex:
^www\.site\.com/products/[^/]+/?$
Explanation:
[^/]+is the key fix here: it only matches characters until the next slash. So it will stop atcategory_nameinstead of continuing toproduct_name.- The
/?$ensures both URLs with and without a trailing slash are matched, while any URL with an extra path segment (like/product_name) will fail to reach the$anchor.
3. Match a Specific Category Path, Exclude URLs with Query Parameters
Requirement Breakdown:
Match www.example.com/en-gb/category/example-of-product (with or without trailing slash), but exclude URLs in the same path that have query parameters (e.g., www.example.com/en-gb/category/example-of-product?filter=price)
Solution Regex:
If targeting the exact URL:
^www\.example\.com/en-gb/category/example-of-product/?$
If example-of-product is a variable category name (match any valid category here):
^www\.example\.com/en-gb/category/[^/?]+/?$
Explanation:
$anchors the match to the end of the URL. Any URL with query parameters will have characters after the base path (starting with?), so they won't reach the$anchor and will be excluded.[^/?]+(for the variable case) matches one or more characters that are neither slashes nor question marks — this prevents capturing query parameters or nested paths.
内容的提问来源于stack exchange,提问作者Anabella R

