If you need to do pattern matching on a string within Python, using a regular expression will be the best way to do it. Here are some basic examples to help you with this.
Import Library
To use any of the regular expressions you’ll need to add this library:
|
Regex Compiler
Create the regex object using the compile()
method.
|
This creates or defines the regex object which we can then use against a string.
The r
here indicates a raw string.
I recommend building and testing your regex with a tool like http://regexpal.com.
Matching Regex Objects
Once the regex object is defined you can use the search()
method like this:
|
The results of this are:
|
The search()
method will return the first match it finds in the string.
The results are stored in the group()
method of your variable.
Using Parenthesis to Form Groups
If you need to match on a larger string but want to only extract a portion of the string, you can use parenthesis to make more groups.
|
This has created 4 groups shown here:
|
Without Regex Compile
An alternative way to do this is to skip the regex compile()
method and use this syntax instead:
|
Results:
|
Ignore Case
Use the re.IGNORECASE
option to ignore capitalization. Example:
|
This produces the following results:
|
Pro Tip: You can use the shortcut re.I
instead of re.IGNORECASE
.
Using findall()
While the search()
method finds the first occurrence, the findall()
method returns every occurrence.
|
This turns the search_results
variable into a list and has the following results:
|
Substituting Using a Regex
You can use the sub()
method to substitute a string matching a regex. Example:
|
This prints My number is XXX-XXX-XXXX.
.
Comments