Explore a Match Object
In the previous lesson, you identified a substring using
re.search(), and what you got from running the function was a
Match object. In this lesson, you’ll see how you can get information about the substring from that
Match object. You could assign that to a variable.
And in this case, this right away gives you the word that got matched, and then you can say
m.span(), and that would give you the beginning and the end of the substring that got matched in here. So if you use the
re module and, for example,
.search(), you can find a substring according to somewhat more elaborate conditions than you did when, for example, you used
.index() to get just the index.
01:12 Then you got the beginning index. In this case, you get both the beginning and the end index, and you also get the actual string that got matched. So this gives you more to work with if you really need to do something with the substring that you’re searching. And you can also match other things.
So by opening and closing a square bracket here, I can define some characters where just one of them needs to match. So I’m going to say a dot, and I’m escaping this with the backslash (
\) character because the dot has special meanings in regex, and then also a comma.
And the reason is that
"secret." appears first in the text and search is just going to return you the first match that it finds scanning the string that you’re searching in from the beginning. So in that case, after it finds
"secret.", it basically stops and just returns you that match.
And that’s not dependent on the order of the characters here in the square brackets. If you wrote the comma first, and then the dot, Python would still match the substring
"secret." just because it appears first in the text that you’re searching in. All right, so this seems useful, but at the same time, what if you do want to have both of those results back?
Become a Member to join the conversation.