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

Python Regex: Split on first occurrence of letter

I’m trying to split a string into an initial numeric component and the remaining components, using the first occurrence of a letter as the delimiter, so for example:

"123b" -> ["123", "b"]
"12b7.97ap" -> ["12", "b7.97ap"]

I’m new to regex and I’m having trouble achieving this… The best I could do is:

re.split(r"(\d+)", string)

But this returns:

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

["", "123", "b"]
["", "12", "b", "7", ".", "97", "ap"]

For the two examples above. I suppose I could then combine all the elements after index 1 into a single string, but I’m sure there’s a better way… Thanks in advance for any help!

>Solution :

One possibility, first matching digits and then matching the rest:

import re

for s in "123b", "12b7.97ap":
    print(re.findall('\d+|.+', s))

Output:

['123', 'b']
['12', 'b7.97ap']
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