[Python] Regex Group referencing doesn't work for re.findall() python [duplicate]

Discussão em 'Python' iniciado por Stack, Setembro 12, 2025.

  1. Stack

    Stack Membro Participativo

    I am new to regular expression. I ran into an issue trying group referencing with re.findall() function of python.

    Here in pattern i try to group ha --> 1 and haa --> 2 and try to reference it into the itself to avoid repetition.

    import re
    s = "ha-haa-ha-haa"
    re.findall(r"(ha)-(haa)-\1-\2", s)


    [('ha', 'haa')] # Actual Output
    ['ha-haa-ha-haa'] # Expected output


    I tried some different approaches:

    Approach 1

    import re
    s = "ha-haa-ha-haa"
    p = re.compile(r"(ha)-(haa)-\1-\2")
    re.findall(p, s)


    Still get this output:


    [('ha', 'haa')] # Output


    Approach 2

    I tried this then:

    import re
    s = "ha-haa-ha-haa"
    p = re.compile(r"(ha)-(haa)-\1-\2")
    re.search(p, s)


    This gave expected output

    <re.Match object; span=(0, 13), match='ha-haa-ha-haa'>


    Can somebody explain why group reference is not working for re.findall() while working for re.search()?

    I am using python 3.12.11

    Continue reading...

Compartilhe esta Página