Python 使用正则表达式解析字符串

Python 使用正则表达式解析字符串,python,regex,Python,Regex,我有一根绳子 txt = 'text1 & ("text2" | "text3" | "text4") & "text5" ! (text6 | text7 | text8)' 假设我想对它进行解析,这样我就得到了括号之间的元素。我的图案看起来像 pattern = '\(([^\)(]+)\)' 使用python,我最终得到了两个组 >>> print re.findall(pattren, text) ['"text2" | "text3" | "tex

我有一根绳子

txt = 'text1 & ("text2" | "text3" | "text4") & "text5" ! (text6 | text7 | text8)'
假设我想对它进行解析,这样我就得到了括号之间的元素。我的图案看起来像

pattern = '\(([^\)(]+)\)'
使用python,我最终得到了两个组

>>> print re.findall(pattren, text)
['"text2" | "text3" | "text4"', 'text6 | text7 | text8']
假设我们想找到像这样的东西

>>> print re.findall(magic_pattren, text )
['& ("text2" | "text3" | "text4")', '! (text6 | text7 | text8)']
猜猜那将是什么
magic\u pattren
。我可以使用字符串操作来获得所需的输出

 >>> print [txt[str.find(txt, a)-3: 1+len(a)+str.find(txt, a)] for a in re.findall(pattren, txt)]
 ['& ("text2" | "text3" | "text4")', '! (text6 | text7 | text8)']
但是,如果括号组在开始时,这感觉有点笨拙,并且失败了。我可以加一张支票,但就像我说的,感觉有点笨重。任何接受者?

您可以在模式开头使用
(?:\B\W\s*)?
可选组:

import re
p = re.compile(r'(?:\B\W\s*)?\([^()]+\)')
test_str = "(text9 & text10) & text1 & (\"text2\" | \"text3\" | \"text4\") & \"text5\" ! (text6 | text7 | text8)"
print(p.findall(test_str))
结果:
['(text9和text10)',&(“text2”|“text3”|“text4”),!(text6 | text7 | text8)]

(?:\B\W\s*)?
是一个非捕获组(因此值不会在结果中输出),可以重复一次或零次(由于最后一个
),并且它仅在前面有非字字符或字符串开头(
\B
)时匹配非字字符(
\W
)然后是0+空格


请检查
r'\B\W\s*\([^()]+\)”
regex。谢谢您的帮助,但是如果组处于启动状态,这将丢失。所以,让那个部分成为可选的,明白了吗。。这就是黄金。。。