Lesson 6 of 6 · Modules and the Standard Library · 3 min read · Updated

Regular expressions

Finding and checking patterns in text — phone numbers, pin codes, emails.

String methods find fixed text. A regular expression describes a pattern — "six digits", "a word, an @, another word" — and the re module finds or checks it.

python
import re

text = "Call 98401 23456 or 044-2345 6789 before 5 pm"
print(re.findall(r"\d+", text))

match = re.search(r"(\w+)@(\w+)\.com", "Mail priya@example.com today")
if match:
    print(match.group())
    print(match.group(1), match.group(2))
Output
['98401', '23456', '044', '2345', '6789', '5']
priya@example.com
priya example

The pattern pieces you will use most

  • \d a digit, \w a letter, digit or underscore, \s a space.
  • . any character; \. a real full stop.
  • + one or more, * zero or more, ? optional, {6} exactly six.
  • [aeiou] any one of these; ( ) a group you can pull out afterwards.

Checking a whole value

python
import re

for pin in ["625001", "62500", "6250011", "62a001"]:
    print(pin, bool(re.fullmatch(r"\d{6}", pin)))
Output
625001 True
62500 False
6250011 False
62a001 False

fullmatch succeeds only if the whole string fits the pattern — right for validating input. search finds a match anywhere inside, and findall returns every match.

Replacing and splitting

python
import re

print(re.sub(r"\s+", " ", "too    many     spaces"))
print(re.split(r"[,;]\s*", "idli, dosa;vada,  pongal"))
Output
too many spaces
['idli', 'dosa', 'vada', 'pongal']

Note

Write patterns as raw strings — r"\d+" — so Python leaves the backslashes for re to read. And when a string method can do the job, prefer it: a regex is powerful but harder to read.

Which call checks that code is exactly four digits and nothing else?

Try this now

  1. Check whether a mobile number the user types is exactly 10 digits starting with 6, 7, 8 or 9.
  2. Pull every email address out of a paragraph of text with findall.

Create a free account to save your progress, or sign in.