Reputation: 157
I am trying to split a string looks like this:
a = 'sdfLKC[m2G]TO'
the output looks like this:
b = ['s', 'd', 'f', 'L', 'K', 'C', '[m2G]', 'T', 'O']
My knowledge of regex is basic, and my code is
b = re.split(r'(\[.+?\])', a)
but the output is ['sdfLKC', '[m2G]', 'TO']
, I also want split each character if they are not in the brackets, any help will be appreciated.
Upvotes: 0
Views: 73
Reputation: 107297
You can use re.findall
to find any single word character or a string between 2 square bracket.
>>> re.findall(r'\w|\[[^\]]+\]',a)
['s', 'd', 'f', 'L', 'K', 'C', '[m2G]', 'T', 'O']
Upvotes: 1
Reputation: 174706
What about re.findall
? ie, do matching instead of splitting.
>>> re.findall(r'\[[^\[\]]*\]|.', a)
['s', 'd', 'f', 'L', 'K', 'C', '[m2G]', 'T', 'O']
Upvotes: 1