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!
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!
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