Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a string with repeated characters into a list

Tags:

I am not well experienced with Regex but I have been reading a lot about it. Assume there's a string s = '111234' I want a list with the string split into L = ['111', '2', '3', '4']. My approach was to make a group checking if it's a digit or not and then check for a repetition of the group. Something like this

L = re.findall('\d[\1+]', s)

I think that \d[\1+] will basically check for either "digit" or "digit +" the same repetitions. I think this might do what I want.

like image 454
Mathews_M_J Avatar asked Apr 05 '14 15:04

Mathews_M_J


1 Answers

Use re.finditer():

>>> s='111234'
>>> [m.group(0) for m in re.finditer(r"(\d)\1*", s)]
['111', '2', '3', '4']
like image 139
devnull Avatar answered Oct 06 '22 23:10

devnull