Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex split string but not at the beginning

I need to split strings like this:
'-89p-98u+2s-26y+97q+67r+71w-52t-3735+80z-7x+17v'
but exclude the first ‘-‘

[-|+]

captures all the ‘-‘ and ‘+’ but sadly gets the first one too:

s = '-89p-98u+2s-26y+97q+67r+71w-52t-3735+80z-7x+17v'
re.split(r'[-|+]', s)
['', '89p', '98u', '2s', '26y', '97q', '67r', '71w', '52t', '3735', '80z', '7x', '17v']

How do i exclude the first ‘-‘?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could use a negative lookbehind to prevent splitting just after the start of the line:

>>> s = '-89p-98u+2s-26y+97q+67r+71w-52t-3735+80z-7x+17v'
>>> re.split(r'(?<!^)[-|+]', s)
['-89p', '98u', '2s', '26y', '97q', '67r', '71w', '52t', '3735', '80z', '7x', '17v']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading