Python Regular Expression Match All 5 Digit Numbers but None Larger

>>> import re
>>> s="four digits 1234 five digits 56789 six digits 012345"
>>> re.findall(r"\D(\d{5})\D", s)
['56789']

if they can occur at the very beginning or the very end, it’s easier to pad the string than mess with special cases

>>> re.findall(r"\D(\d{5})\D", " "+s+" ")

Leave a Comment