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

4

34

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?

Pumpkin answered 5/9, 2011 at 19:24 Comment(0)
A
23

groups is empty since you do not have any capturing groups - http://docs.python.org/library/re.html#re.MatchObject.groups. group(0) will always returns the whole text that was matched regardless of if it was captured in a group or not

Edited.

Akin answered 5/9, 2011 at 19:28 Comment(1)
That's the groups field, not the methodProcrastinate
M
26

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.

Metabolic answered 5/9, 2011 at 19:39 Comment(0)
A
23

groups is empty since you do not have any capturing groups - http://docs.python.org/library/re.html#re.MatchObject.groups. group(0) will always returns the whole text that was matched regardless of if it was captured in a group or not

Edited.

Akin answered 5/9, 2011 at 19:28 Comment(1)
That's the groups field, not the methodProcrastinate
S
5

The reason for this is that you have no capturing groups (since you don't use () in the pattern). http://docs.python.org/library/re.html#re.MatchObject.groups

And group(0) returns the entire search result (even if it has no capturing groups at all): http://docs.python.org/library/re.html#re.MatchObject.group

Spires answered 5/9, 2011 at 19:36 Comment(0)
M
5

You have no groups in your regex, therefore you get an empty list (()) as result.

Try

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

With the brackets you are creating a capturing group, the result that matches this part of the pattern, is stored in a group.

Then you get

('1',)

as result.

Manifesto answered 5/9, 2011 at 19:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.