如何修改URL路径匹配正则表达式以排除特定格式URL
Let's break down how to modify your existing regex to exclude the unwanted URLs while keeping the valid matches intact.
Original Regex Recap
Your original pattern matches URLs with regional segments, a post name, and an optional reviews section (including empty reviews paths):
listing/(.+?)/([^\/.]+)/?(reviews/?(.+?)?/?)?/?$
Key Changes Needed
We need to address two exclusion cases:
- URLs ending with
/reviews/(empty reviews section) - URLs containing
/add-review/
Modified Regex
Here's the updated pattern that handles both exclusions:
listing/(.+?)/([^\/.]+)/(?!add-review/)(?:reviews/(.+?)/?)?/?$
Breakdown of Modifications
Negative Lookahead for
add-review/:
The(?!add-review/)part is a negative lookahead that checks immediately after the post name's trailing slash. If the next segment isadd-review/, the regex will reject the entire URL, directly excluding those unwanted paths.Enforce Non-Empty Reviews Section:
We adjusted the reviews segment fromreviews/?(.+?)?/?toreviews/(.+?)/?(wrapped in a non-capturing group(?:...)). This ensures that if areviews/segment exists, it must be followed by at least one character (no empty reviews paths allowed).
Test Cases
- Still Matches:
listing/united-states/postname1/listing/united-states/california/postname2/listing/united-states/california/chino/postname3/listing/united-states/california/chino/postname4/reviews/testreview/
- No Longer Matches:
listing/united-states/california/chino/postname1/reviews/listing/united-states/california/chino/postname2/add-review/
内容的提问来源于stack exchange,提问作者shamalli

