我想匹配最后一个被包含在
[]
中的组,但它本身可能包含一个或多个嵌套的[]
。我使用Python
的regex
解决了嵌套的[]
匹配问题,虽然不够优雅。这个解决方案对于某些情况(如s1
)有效,但是当有多个这样的匹配时,对于s2
或s3
无效。我的解决方案只会匹配第一个。有什么建议吗?是否需要更好的正则表达式?或者说正则表达式不是解决这个问题的方法?非常感谢!In [116]:
s1 = 'AAA [BBB [CCC]]'
s2 = 'AAA [DDD] [EEE]'
s3 = 'AAA [BBB [CCC]] [EEE]'
for s in [s1, s2, s3]:
result = regex.search(r'(?<rec>\[(?:[^\[\]]++|(?&rec))*\])',s,flags=regex.VERBOSE)
print(result.captures('rec'))
['[CCC]', '[BBB [CCC]]'] #I know it is perfect, but I can take the last one in the list
['[DDD]'] #This is the first one, I want the last one, which is [EEE]
['[CCC]', '[BBB [CCC]]'] #same problem as above
编辑:
非常感谢帮助,如果我有15个声望值,我会给你们所有人点赞。但是,很抱歉没有包括预期的结果,应该是:
'AAA [BBB [CCC]]' -> '[BBB [CCC]]'
'AAA [DDD] [EEE]' -> '[EEE]'
'AAA [BBB [CCC]] [EEE]' -> '[EEE]'
'000 [[aaa] xxx [yyy [zzz ]]' -> '[[aaa] xxx [yyy [zzz ]]'
000 [[aaa] xxx [yyy [zzz ]]
应该产生[[aaa] xxx [yyy [zzz ]]
,请参见编辑: - user3732025