How to describe string with only repeated characters groups in regular expression in Python
<p>i.e. <code>'aaeegggwwqqqqq', 'ttteeyyjjj'</code></p>

<p>I tried <code>r'(([a-z])\1*)+$'</code>, but get error said: cannot refer to open group.</p>

<p>Anyone can help me figure it out? Thanks!</p>

<p>You should use a non-capturing outer group:</p>

<pre><code>re.match(r'(?:([a-z])\1+)+$', s)
</code></pre>

<p>See the <a href="https://regex101.com/r/f186ye/1" rel="nofollow">regex demo</a></p>

<p>This way, you do not have to re-adjust the backreferences inside the pattern.</p>

<p>An alternative is to use a named capture group and a named backreference:</p>

<pre><code>re.match(r'((?P&lt;l&gt;[a-z])(?P=l)+)+$', s)
</code></pre>

<p>See <a href="https://regex101.com/r/f186ye/2" rel="nofollow">this regex demo</a></p>

<p>Here, <code>(?P&lt;l&gt;[a-z])</code> captures an ASCII lowercase letter into Group "l" and <code>(?P=l)+</code> matches 1 or more (<code>+</code> matches one or more occurrences of the quantified subpattern as many times as possible) ocurrences of the captured letter.</p>

<p><a href="http://ideone.com/ipIFkx" rel="nofollow">Python demo</a>:</p>

<pre><code>import re
s = ["aaeegggwwqqqqq", "ttteeyyjjj", "sdfghj"]
for x in s:
    if re.match(r'(?:([a-z])\1+)+$', x):
        print("{0} matches the pattern".format(x))
</code></pre>

<p>Output:</p>

<pre><code>aaeegggwwqqqqq matches the pattern
ttteeyyjjj matches the pattern
</code></pre>

python regex