正则提取URL片段时误排除单个字符而非指定单词的问题
Got it, let's sort out this regex problem for you. The core issue with your current pattern is that you're using a character class when you need to exclude an entire word, not individual characters.
What's Wrong with Your Current Regex?
Your regex: ^\/api\/(?:([^\/(add)]+?))\/.*?$
The [^\/(add)] part is a character set, which tells the regex to match any single character that is NOT a slash, (, a, d, or ). That's why it's incorrectly excluding any content with an "a" or "d"—it's treating those as individual forbidden characters, not the whole word "add".
The Corrected Regex
To exclude the entire "add" word (and only that word), we'll use a negative lookahead assertion to check that /api/ isn't followed by "add". Here's the working pattern:
^\/api\/(?!add\/?)([^\/]+)(?:\/.*)?$
Breakdown of the Pattern
Let's break down what each part does:
^\/api\/: Matches the start of the string followed by/api/(?!add\/?): Negative lookahead—this ensures that immediately after/api/, we don't have "add" (either followed by a slash or the end of the string)([^\/]+): Capture group that grabs all characters until the next slash (this is the value you want to extract)(?:\/.*)?: Optional non-capturing group that matches any trailing slash and content (covers URLs like/api/user1/profile/)/i: Case-insensitive flag (remove this if you need exact case matching)
Testing Against Your Cases
Let's verify this works with your test data:
/api/add→ No match (correct, since it starts with/api/add) ✅/api/add/view→ No match (correct, starts with/api/add) ✅/api/user1→ Matches, extracts "user1" ✅/api/user1/profile/→ Matches, extracts "user1" ✅/api/aaa/profile/→ Matches, extracts "aaa" ✅ (fixed your original issue, since "aaa" isn't the forbidden word "add")
This regex will only exclude URLs where /api/ is directly followed by "add" (with or without a trailing slash), while allowing all other valid segments to be captured.
内容的提问来源于stack exchange,提问作者Carlo

