Python: Search a string for a variable repeating characters
<p>I'm trying to write a function that will search a string (all numeric, 0-9) for a variable sequence of 4 or more repeating characters. </p>

<p>Here are some example inputs:</p>

<p>"14888838": the function would return True because it found "8888". </p>

<p>"1111":     the function would return True because it found "1111". </p>

<p>"1359":     the function would return False because it didn't find 4 repeating characters in a row. </p>

<p>My first inclination is to use re, so I thought the pattern :"[0-9]{4}" would work but that returns true as long as it finds any four numerics in a row, regardless of whether they are matching or not. </p>

<p>Anyway, thanks in advance for your help.</p>

<p>Dave</p>

<p>You may rely on <a href="http://www.regular-expressions.info/brackets.html" rel="nofollow"><strong>capturing</strong></a> and <a href="http://www.regular-expressions.info/backref.html" rel="nofollow"><strong>backreferences</strong></a>:</p>

<pre><code>if re.search(r'(\d)\1{3}', s):
    print(s)
</code></pre>

<p>Here, <code>(\d)</code> captures a digit into Group 1 and <code>\1{3}</code> matches 3 occurrences of the value captured that are immediately to the right of that digit.</p>

<p>See the <a href="https://regex101.com/r/aP1gJ2/1" rel="nofollow">regex demo</a> and a <a href="http://ideone.com/Px7fvH" rel="nofollow">Python demo</a></p>

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

<p>Output:</p>

<pre><code>14888838
1111
</code></pre>

python regex