[Python] Capture one character sequence in several groups

Discussão em 'Python' iniciado por Stack, Outubro 7, 2024.

  1. Stack

    Stack Membro Participativo

    I need to find in a string all character sequences corresponding to sets of characters.

    By instance:

    re.findall(r"([a-z]+)|([A-Z]+)","aa BB cc DD")

    return: [('aa', ''), ('', 'BB'), ('cc', ''), ('', 'DD')]


    So it seems I can use the position in the tuple to determine which group the string is in.

    But it doesn't work when a sequence is in several groups:

    re.findall(r"([a-z]+)|([a-zA-Z]+)","aa bB cc DD")

    return: [('aa', ''), ('b', ''), ('', 'B'), ('cc', ''), ('', 'DD')]


    I would like something like:

    [('aa', ''), ('b', ''), ('', 'bB'), ('cc', ''), ('', 'DD')]


    I think it doesn't work because character 'b' is consumed by "([a-z]+)".nkss

    How can I do it?

    Thanks

    Continue reading...

Compartilhe esta Página