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?
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".
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.
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'.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With