Yuebo Guo
Yuebo Guo

Reputation: 5

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()

Upvotes: 0

Views: 279

Answers (2)

The fourth bird
The fourth bird

Reputation: 163362

You are repeating a capture group, which gives you the value of the last iteration which is ('c', '3')

You can repeat the pattern to check if the whole string if of that format, and then split on a space and wrap it in a tuple.

import re

m = re.match(r"(?: [a-z]+ [0-9]+)*$", " a 1 b 2 c 3")
if m:
    print(tuple(m.group().split()))

Output

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

Upvotes: 0

Nick
Nick

Reputation: 147166

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.

Upvotes: 2

Related Questions