带有附加条件的正则表达式拆分字符串

Regexp split string with additional conditions

我有这样的字符串

a = 'text1, text2 (subtext1, subtext2), text3'

需要通过逗号符号拆分该字符串的各个部分,但仅限那些不在框架括号中的部分:

splited = ['text1', 'text2 (subtext1, subtext2)', 'text3']

如何用正则表达式来实现?

使用基于正则表达式的否定前瞻断言。

>>> a = 'text1, text2 (subtext1, subtext2), text3'
>>> re.split(r',(?![^()]*\))', a)
['text1', ' text2 (subtext1, subtext2)', ' text3']
>>> re.split(r',\s*(?![^()]*\))', a)
['text1', 'text2 (subtext1, subtext2)', 'text3']

DEMO

基于正前瞻的正则表达式。

>>> re.split(r',\s*(?=[^()]*(?:\(|$))', a)
['text1', 'text2 (subtext1, subtext2)', 'text3']