Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 748
dtc Avatar asked Sep 05 '11 19:09

dtc


People also ask

How do I match a group in regex?

Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression (dog) creates a single group containing the letters "d", "o", and "g".

What does Groups () do in Python?

groups() method. This method returns a tuple containing all the subgroups of the match, from 1 up to however many groups are in the pattern. The default argument is used for groups that did not participate in the match; it defaults to None.

How do you're group in Python?

What is Group in Regex? A group is a part of a regex pattern enclosed in parentheses () metacharacter. We create a group by placing the regex pattern inside the set of parentheses ( and ) . For example, the regular expression (cat) creates a single group containing the letters 'c', 'a', and 't'.

What is first capturing group in regex?

First group matches abc. Escaped parentheses group the regex between them. They capture the text matched by the regex inside them into a numbered group that can be reused with a numbered backreference. They allow you to apply regex operators to the entire grouped regex.


2 Answers

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.

like image 190
Hod - Monica's Army Avatar answered Sep 29 '22 09:09

Hod - Monica's Army


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.

like image 40
arunkumar Avatar answered Sep 29 '22 09:09

arunkumar