The re module handles regular expressions in Python

A regular expression can be used to find all matches in a string or simply test if a match exists.

Regular expressions help you to quickly collect some items from large piles of data just by defining some grammar rules.

Related course: Python Crash Course: Master Python Programming!

Example

Create a string to run the regular expression. As example phrase we’ll use the famous American tongue twister “wouldchuck”.

Find all matches for a string using a regular expression. Call the method findall() with as parameters the regular expression and the search space.

Try the program below:

import re

string = "How much wood would a woodchuck chuck if a woodchuck could chuck wood?"

matches = re.findall(r'woo\w*', string)
print(matches)

It returns the matches for the regular expression.
We define starting letters “woo”, followed by a word character \w that matches zero or more times * .

regular expression

To test if the data a matching regular expression, use the search method. This returns true or false, that can be matched with an if statement:

if re.search(r'woo\w*', string):
print('woo\w* foud!')
else:
print('not found')

Checkout this cheat sheet if you want to write your own regular expressions.

Exercise

  1. Find out if regular expressions are case sensitive
  2. Create a regular expression for phone numbers