[Python] Regex: Match strings where each character appears the same number of times

Discussão em 'Python' iniciado por Stack, Junho 7, 2025.

  1. Stack

    Stack Membro Participativo

    I'm working on a regex challenge using the third-party regex module in Python (not the standard re module). The regex is being validated with the following code:


    import regex

    def check_regex(pattern, matches, nonmatches):
    try:
    re = regex.compile(pattern, flags=regex.V1)
    except:
    print("nope")
    return False

    for text in matches:
    if not re.search(text):
    print(f"whoops, didn't match on {text}")
    return False

    for text in nonmatches:
    if re.search(text):
    print(f"whoops, matched on {text}")
    return False

    return True​

    I'm trying to write a single regex expression that matches strings in which every character appears the same number of times. For example:

    matches = ["aabb", "abab", "baba", "aabbcc", "abcabc"] nonmatches = ["aab", "aabbc", "abc", "aabbb"]

    I know that the regex module (unlike re) supports features like subroutines, recursion, and balancing groups via regex.V1, but I’m unsure if it’s even theoretically possible to enforce equal character counts in a single regex expression without programmatic counting.

    Is there a clever way (perhaps with recursive patterns or balancing groups) to do this with just regex? Or is this a task that's fundamentally beyond regular expressions, even with the extended features of regex.V1?

    Would appreciate any insight or partial ideas—happy to accept clever hacks too.

    Continue reading...

Compartilhe esta Página