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.
To use any of the regular expressions you’ll need to add this library:
Create the regex object using the
This creates or defines the regex object which we can then use against a string.
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:
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:
re.IGNORECASE option to ignore capitalization. Example:
This produces the following results:
Pro Tip: You can use the shortcut
re.I instead of
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:
My number is XXX-XXX-XXXX..