#100DaysOfCode in Python Transcripts
Chapter: Days 28-30: Regular Expressions
Lecture: String capturing parenthesis
Login or
purchase this course
to watch this video and the rest of the course contents.
0:00
A common task is to capture strings using a regex. Here we have two strings, 100 and 200. What if we want to extract number days of code
0:14
out of these strings. Here's how you would do it. First, I do a research. And I use the capturing parentheses.
0:29
What this will do, any regex inside these parentheses that matches the string will be stored in a match object, which we can access with groups.
0:40
Hashtag, one or more digits, days of code. As it is searched, re is happy to just match the substrings.
0:51
So I don't need make sure that the whole string matches. If this would be match. Let's do it actually.
1:00
I would have to account for anything that comes before, and anything that comes after. Of course I need to give it a string.
1:10
And let's see what happens. So first of all we have a match object, and to get the actual matching string I can do groups.
1:20
And it gives me a tuple of the matches. So to get the actual string, I can just use indexing. And I got 100 days of code.
1:32
Now this will work the same for 200. Let me show search, that was my initial intent. Search, then I don't have to account for end time,
1:44
so I those wild cards out. I'm going to use 200 to show the match object first. And again, 200 days of code.
2:02
So you see the power of regular expressions, this is still very simple. I can just say one or more digits, followed by a string,
2:09
and it will match both 100 and 200 days of code. So that's how you capture strings with the re module.