如何使用POSIX扩展正则表达式匹配方括号外的‘organization’单词
Got it, let's work through adapting your regex to POSIX Extended Regular Expressions (ERE)!
First, let's break down why your original regex (?:^|\s)(organization)(?!]) won't work here: POSIX ERE doesn't support non-capturing groups ((?:...)—all parentheses in ERE create capturing groups) or negative lookahead assertions ((?!])). So we need to rethink the approach to fit POSIX ERE's capabilities.
Solution 1: Accurate match for non-nested brackets (uses capture groups)
If your application supports extracting capture group results, this is the most reliable method—especially if you might have organization inside brackets with surrounding text (like [abc organization def]). The trick is to first match and skip all bracket-enclosed content, then capture the valid organization words outside brackets:
\[.*\]|([[:<:]]organization[[:>:]])
Here's what each part does:
\[.*\]: Matches any pair of brackets and all content inside them (the greedy.*ensures it grabs up to the closing], which works for non-nested brackets)|: Acts as a logical OR—either match the bracket content, or match the capture group([[:<:]]organization[[:>:]]): Captures standaloneorganizationwords outside brackets.[[:<:]]and[[:>:]]are POSIX-standard word boundaries, so we don't accidentally match parts of longer words (likeorganizationxyz).
When you run this regex, only the valid organization instances will show up in capture group 1—bracket-enclosed content gets matched but not captured.
Solution 2: Simplified match for specific bracket formats (no capture groups needed)
If your use case only has brackets wrapping organization directly or with adjacent text (like [organization] or [organization name], no spaces around organization inside brackets), you can use this simpler pattern that matches valid instances directly:
(^|\s)organization([^\]]|$)
(^|\s): Ensures we're matching the start of the string or a space beforeorganization, so we only target standalone wordsorganization: The word we want to match([^\]]|$): Matches any character that isn't a closing bracket, or the end of the string—this excludes anyorganizationthat's inside brackets (since those would be followed by either]or text leading to]).
Testing this on your example string:
The organization “[organization name]” must contain at least one user per organization . The ID [id] for [organization] must contain digits only
It will correctly match the first organization (after "The ") and the third organization (after "per "), while ignoring the ones inside brackets.
内容的提问来源于stack exchange,提问作者user1298431

