Path: blob/master/12-Advanced Python Modules/05-Overview-of-Regular-Expressions.ipynb
666 views
Overview of Regular Expressions
Regular Expressions (sometimes called regex for short) allows a user to search for strings using almost any sort of rule they can come up. For example, finding all capital letters in a string, or finding a phone number in a document.
Regular expressions are notorious for their seemingly strange syntax. This strange syntax is a byproduct of their flexibility. Regular expressions have to be able to filter out any string pattern you can imagine, which is why they have a complex string pattern format.
Let's begin by explaining how to search for basic patterns in a string!
Searching for Basic Patterns
Let's imagine that we have the following string:
We'll start off by trying to find out if the string "phone" is inside the text string. Now we could quickly do this with:
But let's show the format for regular expressions, because later on we will be searching for patterns that won't have such a simple solution.
Now we've seen that re.search() will take the pattern, scan the text, and then returns a Match object. If no pattern is found, a None is returned (in Jupyter Notebook this just means that nothing is output below the cell).
Let's take a closer look at this Match object.
Notice the span, there is also a start and end index information.
But what if the pattern occurs more than once?
Notice it only matches the first instance. If we wanted a list of all matches, we can use .findall() method:
To get actual match objects, use the iterator:
If you wanted the actual text that matched, you can use the .group() method.
Patterns
So far we've learned how to search for a basic string. What about more complex examples? Such as trying to find a telephone number in a large string of text? Or an email address?
We could just use search method if we know the exact phone or email, but what if we don't know it? We may know the general format, and we can use that along with regular expressions to search the document for strings that match a particular pattern.
This is where the syntax may appear strange at first, but take your time with this, often its just a matter of looking up the pattern code.
Let' begin!
Identifiers for Characters in Patterns
Characters such as a digit or a single string have different codes that represent them. You can use these to build up a pattern string. Notice how these make heavy use of the backwards slash \ . Because of this when defining a pattern string for regular expression we use the format:
placing the r in front of the string allows python to understand that the \ in the pattern string are not meant to be escape slashes.
Below you can find a table of all the possible identifiers:
Character | Description | Example Pattern Code | Exammple Match |
---|
For example:
Notice the repetition of \d. That is a bit of an annoyance, especially if we are looking for very long strings of numbers. Let's explore the possible quantifiers.
Quantifiers
Now that we know the special character designations, we can use them along with quantifiers to define how many we expect.
Character | Description | Example Pattern Code | Exammple Match |
---|
Let's rewrite our pattern using these quantifiers:
Groups
What if we wanted to do two tasks, find phone numbers, but also be able to quickly extract their area code (the first three digits). We can use groups for any general task that involves grouping together regular expressions (so that we can later break them down).
Using the phone number example, we can separate groups of regular expressions using parenthesis:
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-32-866de7a94a57> in <module>()
1 # We only had three groups of parenthesis
----> 2 results.group(4)
IndexError: no such group
Additional Regex Syntax
Or operator |
Use the pipe operator to have an or statment. For example
The Wildcard Character
Use a "wildcard" as a placement that will match any character placed there. You can use a simple period . for this. For example:
Notice how we only matched the first 3 letters, that is because we need a . for each wildcard letter. Or use the quantifiers described above to set its own rules.
However this still leads the problem to grabbing more beforehand. Really we only want words that end with "at".
Starts with and Ends With
We can use the ^ to signal starts with, and the $ to signal ends with:
Note that this is for the entire string, not individual words!
Exclusion
To exclude characters, we can use the ^ symbol in conjunction with a set of brackets []. Anything inside the brackets is excluded. For example:
To get the words back together, use a + sign
We can use this to remove punctuation from a sentence.
Brackets for Grouping
As we showed above we can use brackets to group together options, for example if we wanted to find hyphenated words:
Parenthesis for Multiple Options
If we have multiple options for matching, we can use parenthesis to list out these options. For Example:
Conclusion
Excellent work! For full information on all possible patterns, check out: https://docs.python.org/3/howto/regex.html