求助:正则表达式拆分含括号的Create/Set/Delete分组语句
Got it, let's figure out why your current regex isn't working and fix it. The problem with your original pattern (Create|Set|Delete)\(.*\)\s*\| is that the .* is a greedy match—it grabs everything from the first opening parenthesis all the way to the last closing parenthesis in the entire string. That's why it can't split out each individual Create/Set/Delete block correctly, especially when you have nested parentheses like Banana(Tree).
The Solution: Match Balanced Parentheses
Since your input has nested parentheses, we need a regex that can recognize when a parenthesis is properly closed before moving on to the next operation. Here's how to do it depending on your programming language:
Option 1: Recursive Regex (Python, Perl, etc.)
If your regex engine supports recursion (like Python's regex library, not the standard re), use this pattern:
(Create|Set|Delete)\((?:[^()]|(?R))*\)
Let's break this down:
(Create|Set|Delete): Targets one of your three operation keywords\(: Matches the opening parenthesis right after the keyword(?:[^()]|(?R))*: A non-capturing group that either matches non-parenthesis characters, or recursively matches the entire regex pattern (to handle nested parentheses)\): Matches the closing parenthesis that pairs with the initial opening one
In Python, you'd use it like this:
import regex input_text = "Create(Apple | Banana(Tree) | Mango (Tree) ) | Delete(Guava)|Set(Orange(Tree))" pattern = r'(Create|Set|Delete)\((?:[^()]|(?R))*\)' result = [match.group() for match in regex.finditer(pattern, input_text)] print(result)
This will output exactly what you want:
['Create(Apple | Banana(Tree) | Mango (Tree) )', 'Delete(Guava)', 'Set(Orange(Tree))']
Option 2: Balanced Groups (C#, .NET)
If you're using a .NET-based language (like C#), you can use balanced group syntax to track opening and closing parentheses:
(Create|Set|Delete)\((?>[^()]|(?<open>\()|(?<-open>\)))*(?(open)(?!))\)
(?<open>\(): Creates a "stack" entry every time an opening parenthesis is found(?<-open>\)): Removes an entry from the stack when a closing parenthesis is found(?(open)(?!)): Ensures there are no unclosed parentheses left in the stack before matching the final closing parenthesis
Why This Works
Instead of greedily matching everything between the first and last parenthesis, this approach properly respects nested parentheses. It only stops matching when it reaches the closing parenthesis that pairs with the initial one after the operation keyword.
内容的提问来源于stack exchange,提问作者baskar_p

