Regex matching 5-digit substrings not enclosed with digits

Your current regex (((\D|^)*)\d\d\d\d\d((\D|$)*)) used with re.findall won’t return the digit chunks because they are not captured. More, the (\D|^)* and
(\D|$)* parts are optional and that means they do not do what they are supposed to do, the regex will find 5 digit chunks inside longer digits chunks.

If you must find 5 digit chunk not enclosed with other digits, use

re.findall(r"(?<!\d)\d{5}(?!\d)", s)

See the regex demo

Details:

  • (?<!\d) – no digit is allowed before the current location
  • \d{5} – 5 digits
  • (?!\d) – no digit allowed after the current location.

Leave a Comment