Python中的分割字符串和捕获组

问题描述 投票:0回答:1

我有以下字符串:

'Cc1cc([N+](=O)[O-])ccc1OCC(C)(O)CN1CCN(Cc2ccccc2)CC1'

并且想要捕获[N +]和[O-],即拆分并恢复它们。我似乎无法通过使用re.split恢复它们。

re.split(r'\[[^\]]*\]','Cc1cc([N+](=O)[O-])ccc1OCC(C)(O)CN1CCN(Cc2ccccc2)CC1')

output:
['Cc1cc(', '(=O)', ')ccc1OCC(C)(O)CN1CCN(Cc2ccccc2)CC1']

而且我正在寻找这样的东西:

['Cc1cc(', '[N+]','(=O)','[O-]', ')ccc1OCC(C)(O)CN1CCN(Cc2ccccc2)CC1']

我知道类似的修改:Splitting on regex without removing delimitersIn Python, how do I split a string and keep the separators?

python regex string split tokenize
1个回答
0
投票

这应该起作用:

s = 'Cc1cc([N+](=O)[O-])ccc1OCC(C)(O)CN1CCN(Cc2ccccc2)CC1'
re.split('(\[[^\]]*\])',s)
© www.soinside.com 2019 - 2024. All rights reserved.