如何修改正则表达式匹配不在任意括号内的管道符(|)
I get it, dealing with nested brackets in regex can be tricky—your original pattern works for single-level brackets but falls apart when you have nested {...{...}...} structures. Let's fix that.
The Problem with Your Original Regex
The pattern /\|(?![^{]*})/g only checks if there's no } immediately after non-{ characters. But when there's a nested { after the pipe, this check passes incorrectly, leading to matches inside nested brackets (like the | between Jason, Maria, Santa in your test case).
Solution 1: Recursive Groups (Modern Environments)
If you're working with modern JavaScript (ES2018+, e.g., Node.js 10+, modern browsers), you can use recursive capture groups to handle unlimited nested brackets cleanly:
const nestedPipeRegex = /\|(?!(?:[^{}]|{(?<nest>(?:[^{}]|{(?&nest)})*)}))/g;
Solution 2: Expanded Pattern (Legacy Compatibility)
For environments that don't support recursive groups, use this expanded pattern that explicitly handles nested brackets (this example supports up to 3 levels, but you can extend it by adding more nested (?:[^}{]|{...})* blocks if needed):
const nestedPipeRegex = /\|(?!(?:[^}{]|{(?:[^}{]|{(?:[^}{]|{[^}{]*})*})*})*})/g;
How It Works
Let's break down the logic:
\|: Matches the pipe character we want to target.(?!...): A negative lookahead that ensures the pipe isn't inside any brackets (including nested ones):(?:[^}{]|{(?:[^}{]|{(?:[^}{]|{[^}{]*})*})*})*: Matches any combination of non-bracket characters or nested{...}structures.}: Ensures we're not looking at a pipe that's inside an unclosed bracket (if there's a}after the nested content, the pipe is inside a bracket pair and should be excluded).
Test Case Example
Take this test string:
Jason|{Maria|{Santa|Claus}}|Bob
The regex will match exactly two pipes:
- The
|betweenJasonand{Maria|{Santa|Claus}} - The
|between{Maria|{Santa|Claus}}andBob
The pipes inside the nested brackets (Maria|{Santa...} and Santa|Claus) are correctly excluded—no more false matches!
内容的提问来源于stack exchange,提问作者Nadir Novruzov

