Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string after multiple delimiters and include it

Hello I'm trying to split a string without removing the delimiter and it can have multiple delimiters.

The delimiters can be 'D', 'M' or 'Y' For example:

>>>string = '1D5Y4D2M'
>>>re.split(someregex, string) #should ideally return
['1D', '5Y', '4D', '2M']

To keep the delimiter I use Python split() without removing the delimiter

>>> re.split('([^D]+D)', '1D5Y4D2M')
['', '1D', '', '5Y4D', '2M']

For multiple delimiters I use In Python, how do I split a string and keep the separators?

>>> re.split('(D|M|Y)', '1D5Y4D2M')
['1', 'D', '5', 'Y', '4', 'D', '2', 'M', '']

Combining both doesn't quite make it.

>>> re.split('([^D]+D|[^M]+M|[^Y]+Y)', string)
['', '1D', '', '5Y4D', '', '2M', '']

Any ideas?

like image 220
david serero Avatar asked Sep 02 '25 09:09

david serero


2 Answers

I'd use findall() in your case. How about:

re.findall(r'\d+[DYM]', string

Which will result in:

['1D', '5Y', '4D', '2M']
like image 179
JvdV Avatar answered Sep 04 '25 21:09

JvdV


(?<=(?:D|Y|M))

You need 0 width assertion split.Can be done using regex module python.

See demo.

https://regex101.com/r/aKV13g/1

like image 20
vks Avatar answered Sep 04 '25 23:09

vks