Python: string search for variable repeated characters

I am trying to write a function that will look for a string (all numeric, 0-9) for a variable sequence of 4 or more repeating characters.

Here are some examples of inputs:

"14888838": the function will return True because it detected "8888".

"1111": the function will return True because it detected "1111".

"1359": the function will return False because 4 duplicate characters were not found in it.

My first inclination is to use re, so I thought that the pattern: "[0-9] {4}" would work, but returns true if it finds four digits in a string, whether they are a match or not.

In any case, in advance for your help.

Dave

+4
source share
1 answer

You can rely on capture and feedbacks :

if re.search(r'(\d)\1{3}', s):
    print(s)

Here it (\d)fixes a digit in group 1, and \1{3}corresponds to 3 occurrences in the received value, which is located to the right of this digit.

Watch the regex demo and Python demo

import re
values = ["14888838", "1111", "1359"]
for s in values:
    if re.search(r'(\d)\1{3}', s):
        print(s)

Conclusion:

14888838
1111
+4
source

Source: https://habr.com/ru/post/1655126/


All Articles