Python正则表达式:按"and"拆分字符串但不拆分大括号内的内容
Alright, let's fix this regex issue for you! The core problem with your original pattern is that it only checks for balanced brackets from the current position to the end, but doesn't account for the bracket depth leading up to the "and" we want to split on. We need to ensure we're only splitting on top-level "and" separators—those that aren't inside any nested curly braces, even if the brackets ahead are balanced.
The key insight is to use a recursive regex (supported in Python's re module) to validate that the content after the "and" forms a fully balanced set of curly braces. This ensures our target "and" is at the top level, not nested inside any unclosed braces.
Here's the working solution:
import re # Your test string test_str = "{{Institution Name 1} and {Institution name 2}} and {Institution name 3} and {Institution and institution name 4}" # Regex to match only top-level "and" separators split_pattern = r'\band\b(?=(?:[^{}]|{(?R)})*$)' # Split the string split_results = re.split(split_pattern, test_str) # Optional: Clean up results to remove outer braces if desired cleaned_results = [ item.strip().strip('{}') if item.strip().startswith('{') and item.strip().endswith('}') else item.strip() for item in split_results ] print("Original split results (keeping outer braces):") print(split_results) print("\nCleaned results (outer braces removed):") print(cleaned_results)
Let's break down the regex \band\b(?=(?:[^{}]|{(?R)})*$):
\band\b: Matches the word "and" as a whole word (avoids partial matches like "and" inside longer words like "institution").(?=...): Positive lookahead to validate what follows the "and":(?:[^{}]|{(?R)})*: A non-capturing group that matches either:[^{}]: Any character that's not a curly brace, OR{(?R)}: A pair of curly braces containing content that matches the entire regex (this handles nested brackets recursively).
$: Ensures we match all the way to the end of the string, confirming the content after "and" has perfectly balanced braces.
When you run this code, you'll get exactly the results you want:
- Original split results (keeping outer braces):
['{{Institution Name 1} and {Institution name 2}}', '{Institution name 3}', '{Institution and institution name 4}'] - Cleaned results (removing outer braces):
['{Institution Name 1} and {Institution name 2}', 'Institution name 3', 'Institution and institution name 4']
内容的提问来源于stack exchange,提问作者sdaau

