Find a course

Module 3: Regex in CodeLesson 8 of 1215 min

Regex in Python and Other Tools

Use Python's re module with raw strings, choose between search, match, fullmatch, findall and sub, and apply regex in grep and code editors.

Step 1 of 14Learn

Python's re module

In Python, regular expressions live in the standard library module re. The functions you'll use most:

FunctionWhat it does
re.search(p, s)finds the first match anywhere; returns a match object or None
re.match(p, s)matches only at the start of the string
re.fullmatch(p, s)the entire string must match
re.findall(p, s)list of all matches (strings, or tuples of groups)
re.finditer(p, s)iterator of match objects
re.sub(p, repl, s)replace all matches (all by default, unlike JavaScript)
re.split(p, s)split at matches

Patterns are written as raw strings, prefixed with r: r"\d{4}". In a raw string, backslashes are kept literally, so you avoid the double escaping that plagues JavaScript's RegExp constructor. Without the r, some escapes still happen to work while others, like "\b" (a backspace character in normal strings), silently break your pattern.

re.match is a frequent source of confusion: despite its name, it only checks the start of the string, so re.match(r"\d+", "abc123") returns None. For validation, prefer re.fullmatch, which needs no anchors and doesn't have the trailing-newline quirk of $.

Step 2 of 14Compare

search, match and fullmatch on "abc123"

Aspectre.search(r"\d+", s)re.match(r"\d+", s)re.fullmatch(r"\d+", s)
LooksAnywhereOnly at the startWhole string
Result on "abc123"Match: 123NoneNone
Result on "123"Match: 123Match: 123Match: 123
Use forFindingPrefix checksValidation

Step 3 of 14Practice · Match the pairs

Match each Python call to its result.

Tap an answer, then tap the place where it belongs (or drag it there).

  1. re.search(r"\d+", "abc123")
  2. re.match(r"\d+", "abc123")
  3. re.fullmatch(r"\d+", "123")
  4. re.findall(r"\d", "a1b2")

Step 4 of 14Learn

findall, groups and compiled patterns

re.findall changes its output depending on the groups in the pattern, which surprises many people:

  • No groups: a list of whole matches. re.findall(r"\d+", "7 cats, 12 dogs") gives ["7", "12"].
  • One group: a list of that group's text. re.findall(r"(\d+) cats", "7 cats, 12 dogs") gives ["7"].
  • Several groups: a list of tuples. re.findall(r"(\d+) (\w+)", "7 cats, 12 dogs") gives [("7", "cats"), ("12", "dogs")].

If you want whole matches while still grouping for structure, use non-capturing groups, or use re.finditer and call m.group(0).

For patterns used many times, compile them once:

DATE = re.compile(r"(?P<y>\d{4})-(?P<m>\d{2})-(?P<d>\d{2})")
for line in lines:
    m = DATE.search(line)
    if m:
        print(m.group("y"))

Python caches recently used patterns, so compiling is mostly about readability: a well-named constant documents what the pattern means. Flags are passed as arguments, re.compile(p, re.IGNORECASE | re.MULTILINE), and the re.VERBOSE flag lets you spread a pattern over several lines with comments, which you'll use in the last module.

Step 5 of 14Practice · Diagram

What re.findall returns

What does r"(\w+)@(\w+)\.com" give you?

Tap the shape that answers the question, then press Check.

What re.findall returnsHierarchy diagram: How many groups?, None: whole matches, One: that group's text, Two or more: tuples.How many groups?None: whole matchesOne: that group'stextTwo or more: tuples
How many groups?
None: whole matches

r"\d+" gives ["7", "12"]

One: that group's text

r"(\d+) cats" gives ["7"]

Two or more: tuples

r"(\d+) (\w+)" gives [("7", "cats"), ("12", "dogs")]

Step 6 of 14Practice · Work it out

How many items are in the list returned by re.findall(r"(\w+)@(\w+)\.com", "ana@mail.com, ben@corp.com, bad@site.org")?

Step 7 of 14Practice · Code challenge · Python

Write extract_prices(text) that returns a list of all prices written as a dollar sign followed by digits, optionally with a decimal point and exactly two more digits (like $5, $19.99). Return them as floats without the dollar sign, in order.

Real Python, running in a sandbox in your browser.
  • extract_prices("Tea $3.50, cake $4, combo $7.25")
  • extract_prices("Free today!")
  • extract_prices("Was $120.00 now $99.99")

Step 8 of 14Learn

grep, sed and editors

Regex is just as useful outside programming languages.

grep searches files line by line. grep -E "ERROR|FATAL" app.log prints matching lines; -E selects extended syntax, where +, ?, | and () work as you'd expect. Without -E, basic grep syntax requires backslashes for some of them, such as \+ and \|. Useful options: -i ignores case, -v inverts the match, -o prints only the matched part, and -c counts matching lines. Many systems also offer grep -P for Perl-compatible syntax, or the faster tool ripgrep (rg), which uses a modern syntax similar to Python and JavaScript.

sed edits streams: sed -E "s/([0-9]{4})-([0-9]{2})-([0-9]{2})/\2\/\3\/\1/g" dates.txt rewrites dates. Note [0-9] instead of \d, because \d isn't supported in POSIX regex.

Editors such as VS Code, Sublime Text and JetBrains IDEs have a regex toggle in find-and-replace (often a .* button). VS Code uses JavaScript syntax and $1 in replacements. This is where regex saves the most time day to day: renaming a function across a project, reformatting a list into code, or cleaning pasted data.

Spreadsheets and databases often include regex functions too, such as REGEXMATCH in Google Sheets or REGEXP_LIKE in several SQL dialects.

Step 9 of 14Compare

Common regex flavors

AspectPOSIX (grep, sed)PCRE (PHP, grep -P)JavaScriptPython re
Digit shorthand \dNot in basic POSIX; use [0-9]YesYesYes (Unicode digits by default)
Lazy quantifiers *?NoYesYesYes
LookbehindNoYes, fixed lengthYes, variable lengthYes, fixed length
Named group syntaxNone(?<name>...) or (?P<name>...)(?<name>...)(?P<name>...)
Replacement reference\1 in sedDepends on host language$1 and $<name>\1 and \g<name>

Step 10 of 14Note

Step 11 of 14Practice · What would you do?

What would you do?

A data analyst writes re.match(r"[A-Z]{2}\d{6}", code) to validate that a whole product code is two letters and six digits. It accepts "AB123456XYZ". What should the analyst change?

Step 12 of 14Note

Step 13 of 14Note

Step 14 of 14Practice · Choose one

Why are Python regex patterns usually written as raw strings, like r"\bword\b"?