Python 使用正则表达式排除括号内的术语

Python 使用正则表达式排除括号内的术语,python,regex,Python,Regex,我只想捕获不在括号中的大写单词: Reggie (Reginald) Potter -> Reggie Potter (?<!\()\b([A-Z][a-z]+)\b(?!\)) 我正在使用这个正则表达式: test = re.findall('([A-Z][a-z]+(?:\s\(.*?\))?(?=\s[A-Z])(?:\s[A-Z][a-z]+)+)', 'Reggie (Reginald) Potter') 我把这个拿回来: Reggie (Reginald) Pott

我只想捕获不在括号中的大写单词:

Reggie (Reginald) Potter -> Reggie Potter
(?<!\()\b([A-Z][a-z]+)\b(?!\))
我正在使用这个正则表达式:

test = re.findall('([A-Z][a-z]+(?:\s\(.*?\))?(?=\s[A-Z])(?:\s[A-Z][a-z]+)+)', 'Reggie (Reginald) Potter')
我把这个拿回来:

Reggie (Reginald) Potter
我想既然这是非捕获:

(?:\s\(.*?\))

我不会在括号内找到任何内容

如果要避免的单词与括号直接相邻,则可以使用来匹配不在括号内的单词:

Reggie (Reginald) Potter -> Reggie Potter
(?<!\()\b([A-Z][a-z]+)\b(?!\))

(?我将使用更简单的正则表达式加上列表理解:

all_words = re.findall(r'(\(?\b[A-Z][a-z]+\b\)?)', 'Reggie (Reginald) Potter')
good_matches = [word for word in all_words if len(word) > 0 and not (word[0] == '(' and word[-1] == ')')]

现在,正如预期的那样,好的匹配是
['Reggie','Potter']

关于
Foo(barbaz)Qaz(Qaz)Paz)Raz(Qaz(Maz)Paz)
?我假设在第一个单词后面只有一组paren(像昵称)将匹配
fooBar
@Qtax-Ah中的
Bar
——我忘记了常用的单词边界字符。已修复。