4.2 Grouping Frequently you need to obtain more information than just whether the RE matched or not. Regular expressions are often used to dissect strings by writing a RE divided into several subgroups which match different components of interest. For example, an RFC-822 header line is divided into a header name and a value, separated by a ':' , like this: This can be handled by writing a regular expression which matches an entire header line, and has one group which matches the header name, and another group which matches the header’s value. Groups are marked by the$_{'('}$ , ')' metacharacters. '(' and$_{')'}$ have much the same meaning as they do in mathematical expressions; they group together the expressions contained inside them, and you can repeat the contents of a group with a repeating qualifier, such as * , + , ? , or {m,n} . For example, (ab)* will match zero or more repetitions of ab . Groups indicated with$_{'('}$ ,$_{')'}$ also capture the starting and ending index of the text that they match; this can be retrieved by passing an argument to$_{group()}$ ,$_{start()}$ ,$_{end()}$ , and$_{span()}$ . Groups are numbered starting with 0. Group 0 is always present; it’s the whole RE, so match object methods all have group 0 as their default argument. Later we’ll see how to express groups that don’t capture the span of text that they match. Subgroups are numbered from left to right, from 1 upward. Groups can be nested; to determine the number, just count the opening parenthesis characters, going from left to right. group() can be passed multiple group numbers at a time, in which case it will return a tuple containing the corre- sponding values for those groups. The$_{groups()}$ method returns a tuple containing the strings for all the subgroups, from 1 up to however many there are. Backreferences in a pattern allow you to specify that the contents of an earlier capturing group must also be found at the current location in the string. For example,$_{\1}$will succeed if the exact contents of group 1 can be found at the >>> m.groups() ('abc', 'b') >>> m.group(2,1,2) ('b', 'abc', 'b') 11 >>> p =re.compile( '(a(b)c)d ') >>> m =p.match('abcd') >>> m.group(0) 'abcd' >>> m.group(1) 'abc' >>> m.group(2) 'b' >>> p =re.compile( '(a)b ') >>> m =p.match('ab') >>> m.group() 'ab' >>> m.group(0) 'ab' >>> p =re.compile( '(ab)* ') >>> print(p.match('ababababab').span()) (0, 10) From: author@example.com User-Agent: Thunderbird 1.5.0.9 (X11/20061227) MIME-Version: 1.0 To: editor@example.com