I have a string with repeated parts:
s = '[1][2][5] and [3][8]'
And I want to group the numbers into two lists using re.match
. The expected result is:
{'x': ['1', '2', '5'], 'y': ['3', '8']}
I tried this expression that gives a wrong result:
re.match(r'^(?:\[(?P<x>\d+)\])+ and (?:\[(?P<y>\d+)\])+$', s).groupdict()
# {'x': '5', 'y': '8'}
It looks like re.match
keeps the last match only. How do I collect all the parts into a list instead of the last one only?
Of course, I know that I could split the line on ' and '
separator and use re.findall
for the parts instead, but this approach is not general enough because it gives some issues for more complex strings so I would always need to think about correct splitting separately all the time.