I'd like to have a regex pattern that splits the string based on the numbers present in them
50cushions => [50,cushions]
30peoplerescued20children => [30,peoplerescued,20,children]
moon25flightin2days => [moon,25,flightin,2,days]
Is it possible to do this a regex, or else what is the best way to do it?
>>> re.findall(r'\d+|\D+', '50cushions')
['50', 'cushions']
>>> re.findall(r'\d+|\D+', '30peoplerescued20children')
['30', 'peoplerescued', '20', 'children']
>>> re.findall(r'\d+|\D+', 'moon25flightin2days')
['moon', '25', 'flightin', '2', 'days']
where \\d+
matches one or more digits and \\D+
matches one or more non digits. \\d+|\\D+
will find either ( |
) a group of digits or non digits, and append the result to the list of matches.
Or with itertools
>>> from itertools import groupby
>>> [''.join(g) for k, g in groupby('moon25flightin2days', key=str.isdigit)]
['moon', '25', 'flightin', '2', 'days']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.