re split to break a string into components but keeping separators

Viewed 48

I want to break a string into components

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

which gives me

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

But I want to achieve

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

Please help!

1 Answers

Use

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

See Python proof.

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

Explanation

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