Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member
So let's take a look at how we use regular expressions in Python. We'll start by making a working copy of regex.py and we'll call this regex-working.py. Regex is a common short name for regular expressions, because who wants to say all those syllables when you can just say regex? Here we have a very simple program that opens a file called raven.txt, which has the complete text of Edgar Allan Poe's poem, The Raven.
So we open that file and then we read the file line-by-line and we do a regex search for anything that matches this pattern here, and this pattern here basically matches the word Lenore or the word Nevermore, which occur with some regularity in this poem. And then it prints them out and you will notice we have end= the blank string, because we don't want to put a new line at the end of a line that already has a new line at the end of it. And so we'll go ahead and run this and there we have the lines that have Nevermore or Lenore in them.
So searching with regular expressions is done using the re.search method of the re module and here is our regular expression pattern. This is a very simple regular expression pattern. It's beyond the scope of this course to teach you regular expressions, but in a nutshell what this one does is it's an alternation and so it has the regular expression alternation operator which you can just call OR. So anything that has Len or Neverm immediately followed by the letters ore.
So this will match Lenore and it will also match Nevermore and we see in our results down here that we have lines that have Nevermore, quoth the raven, and we have lines that have Lenore. So that's how you do a search using regular expressions in Python. If you want to, you can just print out the part of this that was matched. If we take this line here and instead of putting it in the if, we take its result and call it match, then we get a match object which we can use and this is some of the beauty of how Python's "everything is an object" helps us out.
We can test match, if we have a match then what we can print here is match.group(), like that. So if I save this and run it, now we get all of the words that we actually matched. Now this can be really useful for simply looking for specific patterns in a set of text and it can also be used when we look later on for replacing patterns in text, when we talk about replacing later on in this chapter.
So those are some simple examples of how you use Python's regular expression engine.
Get unlimited access to all courses for just $25/month.Become a member