15
Lesson 40 of 44

Regular expressions

Regular expressions are a language for describing text patterns. In this lesson you will learn to use the re module to search, validate, extract and replace text: character classes, quantifiers, anchors, groups and flags. You will practice with real cases such as validating emails, phone numbers and dates, or extracting numbers and words from a text.

  • 5 theory articles
  • 10 practice exercises
Start lesson

Fundamentals concepts 5

Finding patterns with re

A regular expression (*regex*) is a pattern that describes a set of texts: "three digits in a row", "a word that starts with A"……

Theory
Read more

Character classes and quantifiers

A pattern is built by combining two kinds of pieces: which character to look for (classes) and how many times (quantifiers).

Theory
Read more

findall, finditer and groups

When you want all the matches, not just the first one, there are two functions: findall and finditer .

Theory
Read more

Replacing and splitting with re.sub and re.split

Regular expressions do not only search: they also transform texts.

Theory
Read more

Anchors, flags and good practices

Anchors do not consume characters: they indicate a position in the text.

Theory
Read more

Practice exercises 10

First number

Create a Python program that finds the first number that appears in a text using a regular expression.

Exercise Easy
Solve it

All the numbers

Create a Python program that extracts all the numbers from a text and adds them up, using re.findall .

Exercise Easy
Solve it

Hide digits

Create a Python program that hides all the digits of a text with re.sub .

Exercise Easy
Solve it

Postal code

Create a Python program that validates postal codes with re.fullmatch .

Exercise Easy
Solve it

Phone numbers

Create a Python program that validates mobile phone numbers with a pattern that includes an optional part.

Exercise Medium
Solve it

Hashtags and mentions

Create a Python program that extracts the hashtags and the mentions from a message with re.findall .

Exercise Medium
Solve it

Split by several separators

Create a Python program that splits a text that uses different separators with re.split .

Exercise Medium
Solve it

Date with groups

Create a Python program that checks the format of a date and extracts its parts using groups in a regular expression.

Exercise Medium
Solve it

Change the date format

Create a Python program that changes the format of all the dates in a text using re.sub with groups.

Exercise Medium
Solve it

Validate emails

Create a Python program that validates email addresses with a simple pattern.

Exercise Medium
Solve it