如何编写正则表达式匹配指定函数后的括号内参数
Let's break down how to fix this regex issue. Your initial pattern r'((.*?))' is way too broad—it grabs the first opening bracket it sees and stops at the first closing one, which is why it incorrectly matches (name(foo) in your example instead of just foo.
The Correct Regex Patterns
First, we need to anchor our match to the specific prefixes (name, number, listget) so we only target the parentheses immediately following those keywords.
Case 1: No Nested Parentheses Inside Target Brackets
If the content inside the parentheses never has its own nested brackets (like your examples abc1, param9, foo, bar, baz), use this pattern:
import re pattern = r'(?:name|number|listget)\(([^)]+)\)' text = "(name(foo) & number(bar)) - listget(baz)" matches = re.findall(pattern, text) print(matches) # Output: ['foo', 'bar', 'baz']
(?:name|number|listget): Non-capturing group to match one of our target prefixes (we don't need to capture the prefix itself)\(: Matches the opening bracket immediately after the prefix([^)]+): Capturing group that matches any character except a closing bracket—this ensures we only grab the content inside the prefix's parentheses, not any outer brackets\): Matches the closing bracket for our target parentheses
Case 2: Handling Nested Parentheses (If Needed)
If you might have nested brackets inside the target (e.g., name(foo(bar)) where you want to extract foo(bar)), use this recursive regex (supported in Python's re module):
pattern = r'(?:name|number|listget)\(([^()]*(?:\((?1)\)[^()]*)*)\)' text = "name(foo(bar)) & number(param(123))" matches = re.findall(pattern, text) print(matches) # Output: ['foo(bar)', 'param(123)']
- The
(?1)refers back to the first capturing group, allowing the regex to recursively match nested pairs of parentheses inside our target bracket.
Why Your Initial Pattern Failed
r'((.*?))' uses non-greedy matching (.*?) but doesn't anchor to the prefixes. So it starts matching from the first ( in the entire string (the outer one in (name(foo)...), stops at the first ) it finds (the one closing foo), resulting in the incorrect match (name(foo). By anchoring to our specific prefixes, we ensure we only target the parentheses we care about.
内容的提问来源于stack exchange,提问作者zubug55

