In this lesson, I’ll show you how to get at those groups defined in your regex. You’ve already seen some of the attributes and methods on the
re.Match object. There are other ones, though, around grouping. The
.group() function takes a list of arguments.
It returns a tuple of matched groups for each of the numbers you give it. So if you call
.group(1, 3), it’ll return the first and third match in a tuple.
.groups() plural returns all of the matched groups.
You’ve seen the
.end() methods showing the beginning and end of matches in the string. The
.expand() method takes a string template and substitutes any backreferences inside of the template with their actual results.
This is kind of like the idea of an f-string, but with the backreferences from your regex. Finally, there’s also the
.span() method, which you’ve seen before as well, which contains the start and end values in a tuple.
01:58 If you pass in more than one, you get back a tuple in the order that you put it in. You may notice that these are all one-referenced. This is to be consistent with the concept of a backreference.
.group(0) is the entire match. Because this regular expression is looking for some number of meta-characters, a comma, and then some number of meta-characters, the
'one' and the
'two' match, but the
'three' does not because there’s only one instance.
.expand() gives you a template to be able to expand the backreferences. This takes the results of the match and then inserts the backreferences that you reference inside of the template into the string.
There’s a plain text
.search(). There’s the
Match. Starting value of
4, ending value of
7, and the
7. Just as a reminder, these are zero-indexed, the same as a slice in a list or a string.
Become a Member to join the conversation.