The built-in re
does not support possessive quantifiers/atomic groups and does not support recursion, nor balanced groups, all those features that could help you build this pattern.
Thus, the easiest solution is to install the PyPi regex library with pip install regex
and then use the How can we match a^n b^n? solution.
Otherwise, throw in some Python code and a simple (a+)(b+)
regex:
import re
texts = [ "ab", "aaabbb", "aaaaabbbbb", "aab", "aaabbbb" ]
for text in texts:
match = re.fullmatch(r'(a+)(b+)', text)
if len(match.group(1)) == len(match.group(2)):
print( text, '- MATCH' )
else:
print( text, '- NO MATCH' )
See this demo yielding
ab - MATCH
aaabbb - MATCH
aaaaabbbbb - MATCH
aab - NO MATCH
aaabbbb - NO MATCH
NOTE:
re.fullmatch(r'(a+)(b+)', text)
matches an entire string that only contains one or more a
s and then one or more b
s
if len(match.group(1)) == len(match.group(2)):
is checking the lengh of a
s and b
s, and only passes the strings where their counts are equal.