Why won't re.groups() give me anything for my one correctly-matched group?

dtc picture dtc · Sep 5, 2011 · Viewed 60.8k times · Source

When I run this code:

print re.search(r'1', '1').groups() 

I get a result of (). However, .group(0) gives me the match.

Shouldn't groups() give me something containing the match?

Update: Thanks for the answers. So that means if I do re.search() with no subgroups, I have to use groups(0) to get a match?

Answer

Hod - Monica's Army picture Hod - Monica's Army · Sep 5, 2011

To the best of my knowledge, .groups() returns a tuple of remembered groups. I.e. those groups in the regular expression that are enclosed in parentheses. So if you were to write:

print re.search(r'(1)', '1').groups()

you would get

('1',)

as your response. In general, .groups() will return a tuple of all the groups of objects in the regular expression that are enclosed within parentheses.