Search code examples
pythonregexregex-group

Is there a method to get all groups in regular expression with wildcard in python


Just like the follow code, there is not all groups. Is there a method to get all groups? Thanks~

import re

res = re.match(r'(?: ([a-z]+) ([0-9]+))*', ' a 1 b 2 c 3')

# echo ('c', '3'), but I want ('a', '1', 'b', '2', 'c', '3')
res.groups()

Solution

  • You could use re.finditer to iterate the matches, appending each result to an empty tuple:

    import re
    
    res = tuple()
    matches = re.finditer(r' ([a-z]+) ([0-9]+)', ' a 1 b 2 c 3')
    for m in matches:
        res = res + m.groups()
    

    Output:

    ('a', '1', 'b', '2', 'c', '3')
    

    Note that in the regex the outer group is removed as it is not required with finditer.