[Python] How to get all overlapping matches in python regex that may start at the same...

Discussão em 'Python' iniciado por Stack, Janeiro 29, 2025.

  1. Stack

    Stack Membro Participativo

    How do I get all possible overlapping matches in a string in Python with multiple starting and ending points.

    I've tried using regex module, instead of default re module to introduce overlapped = True argument, but still it is missing some matches.

    Trying to describe my problem via a simpler illustration:

    Find all possible combinations in the string (axaybzb) starting with a and ending with b

    Tried following codes:

    import regex

    print(regex.findall(r'a\w+b','axaybzb', overlapped=False))

    ['axaybzb']

    print(regex.findall(r'a\w+?b','axaybzb', overlapped=False))

    ['axayb']

    print(regex.findall(r'a\w+b','axaybzb', overlapped=True))

    ['axaybzb', 'aybzb']

    print(regex.findall(r'a\w+?b','axaybzb', overlapped=True))

    ['axayb', 'ayb']


    Expected output to be

    ['axayb', 'axaybzb', 'ayb', 'aybzb']

    Continue reading...

Compartilhe esta Página