Ningxi
Ningxi

Reputation: 157

python regex split string to each char but keep anything in brackets

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

Answers (2)

Kasravnd
Kasravnd

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

Avinash Raj
Avinash Raj

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

Related Questions