re.split() function throwing error for Python 3.6 version

Viewed 31

I am trying to find strings of pattern (letters)(digits) and make them as (letters)-(digits). For e.g.: If test001 is found, replace that with test-001. So, I need to split the string at first digit following the letters. I am using regular expressions 'match' and 'split' functions for the same.

if re.match(r'^\D+\d*$', str):
     parts = re.split(r'(?=\d)', str, 1)
     updated_str = parts[0] + "-" + parts[1]

It is working for other python versions, but failing for python 3.6 version, throwing error: ValueError: split() requires a non-empty pattern match. Can someone help me with achieving the same, which can work with all the versions of python.

1 Answers

Before Python 3.7, re.split did not allow to split on "a pattern that could match an empty string".

You can insert the hyphen with a single re.sub call:

import re

s = "test001"
print(re.sub(r'^(\D+)(\d+)$', r'\1-\2', s))

See the Python demo.

Note that ^(\D+)(\d*)$ also matches strings like a:b, without digits at the end, so you could end up with a a:b- string, that is why I used + after \d.

Note also that \D matches any non-digit char. If you really want to match just letters, you should use either [a-zA-Z] (if you only need to support ASCII letters), or [^\W\d_] to support any Unicode letters.

Related