[Python] Angle brackets cause re.split() result to become empty string

Discussão em 'Python' iniciado por Stack, Julho 10, 2025.

  1. Stack

    Stack Membro Participativo

    This example:

    import re

    regex = r"\[.*?]"
    parsed = "start[param1]sep[param2]sep[param3]end"
    print(re.split(regex, parsed))
    print(re.findall(regex, parsed))


    prints the expected result:

    ['start', 'sep', 'sep', 'end']
    ['[param1]', '[param2]', '[param3]']


    However, as soon as the input string has angle brackets like this:

    parsed = "<start>[param1]<sep>[param2]<sep>[param3]<end>"


    the output of re.split() becomes empty strings (the re.findall() result obviously remains the same):

    ['', '', '', '']


    I verified that it's because of the angle brackets:

    parsed = "start[param1]<sep>[param2]sep[param3]end"


    yields

    ['start', '', 'sep', 'end']


    Does anyone know why that happens and if I can suppress this behavior somehow?

    In case it's relevant, I'm using Python 3. Not sure if it's specific to Python 3 though. I couldn't find anything about such a behavior anywhere.

    Continue reading...

Compartilhe esta Página