重新拆分以将字符串分解为组件但保留分隔符

re split to break a string into components but keeping separators

我想将一个字符串分解成组件

s = 'Hello [foo] world!'
re.split(r'\[(.*?)\]', s)

这给了我

['Hello ', 'foo', ' world!']

但是我想实现

['Hello ', '[foo]', ' world!']

请帮忙!

使用

import re
s = 'Hello [foo] world!'
print(re.split(r'(\[[^][]*])', s))

Python proof

结果['Hello ', '[foo]', ' world!']

说明

--------------------------------------------------------------------------------
  (                        group and capture to :
--------------------------------------------------------------------------------
    \[                       '['
--------------------------------------------------------------------------------
    [^][]*                   any character except: ']', '[' (0 or
                             more times (matching the most amount
                             possible))
--------------------------------------------------------------------------------
    ]                        ']'
--------------------------------------------------------------------------------
  )                        end of