regex expression to check if same number of repetions in python

I have two complex (and maybe repeating) groups (ab) and (cd)

abcd is valid abababcdcdcd is valid

but: ababcd is invalid abcdcd is invalid

my idea is to repeat with |: ((ab){1}(cd){1})|((ab){2}(cd){2})|((ab){3}(cd){3})|((ab){4}(cd){4}) and so on

I want to know if exists an effective way to write this expression.


You could use a recursive expression, for instance,

import regex

# example:
example_string = "ababababcdcdcdcd"

# regular expression that consumes the whole string
regex.match(r"^(ab(?1)cd|abcd)$", example_string)

If you want to match the expression as substring (not consuming the whole string), you can go without ^ and $, i.e. "(ab(?R)cd|abcd).