← All lessons

Regular expressions

Sign in · Sign up

Lesson 11.12

A regex describes a pattern of text, and re looks for matches:

import re

text = "Write to mia@example.com or timur@school.ru"
print(re.findall(r"[\w.]+@[\w.]+", text))
  • \w is a letter, a digit or an underscore;
  • + means "one or more";
  • re.findall returns all the matches as a list;
  • re.search gives the first match, or None.

The pattern is written as a raw string r"...": that way \w is not confused with a special character.

The check sets the text text. Print all the emails in it with findall and the pattern r"[\w.]+@[\w.]+", and then how many there are — with len.

Hint

The pattern is a string, so don't forget r"..." and import re.

findall returns a list of all matches, len gives their number. In the pattern \w means letters and digits, [\w.]+ is the part before @ and after it.