Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 08 / Topic 10 of 10

Regular expressions (regex)

A regex is a pattern to find text, like "a 6-digit number" or "an email". It is like a smart search box that understands "any digit" or "one or more letters". Use the re module. Always write patterns as raw strings r"..." (strings where \ is kept as it is), so \d is not treated as a Python escape.

A match object (m below) holds what was found; a group is a part of the pattern in ( ) that you want to pull out.

Real-world example: pull data out of server logs and messages.

import re

line = "2025-03-10 09:17:33 ERROR [payment] Payment failed for order #4521"

m = re.search(r"order #(\d+)", line)          # search: first match or None
print(m.group(0))                             # order #4521   (whole match)
print(m.group(1))                             # 4521          (group 1)

m = re.search(r"(?P<date>\d{4}-\d{2}-\d{2}) \S+ (?P<level>[A-Z]+)", line)
print(m["date"], m["level"])                  # 2025-03-10 ERROR
print(m.groupdict())                          # {'date': '2025-03-10', 'level': 'ERROR'}

sms = "Call 98765 43210 or 91234 56789"
print(re.findall(r"\d{5} \d{5}", sms))        # ['98765 43210', '91234 56789']
print(re.sub(r"\d{5} (\d{5})", r"XXXXX \1", sms))   # Call XXXXX 43210 or XXXXX 56789

re.sub with a function. Instead of a fixed replacement text, you can give re.sub a function. Python calls it once for every match, passes the match object, and puts the text it returns in place of the match.

import re

def short_name(m):
    return f"{m['first'][0]}. {m['last']}"    # "Asha Verma" -> "A. Verma"

text = "Asha Verma and Ravi Kumar paid."
print(re.sub(r"(?P<first>[A-Z][a-z]+) (?P<last>[A-Z][a-z]+)", short_name, text))
# A. Verma and R. Kumar paid.
print(re.sub(r"[0-9]+", lambda m: str(int(m.group(0)) * 2), "2 tea, 3 samosa"))
# 4 tea, 6 samosa

Validating a whole string: use re.fullmatch and [0-9]. To check that a PIN code is exactly 6 digits, the pattern must cover the whole text. Two traps:

  • $ also matches just before a final "\n", so re.search(r"^\d{6}$", "560001\n") still finds a match. re.fullmatch has no such gap.
  • \d matches a digit in any script, for example Devanagari ५६०००१. For PIN codes and phone numbers write [0-9] (or pass the flag re.ASCII).
import re

print(bool(re.search(r"^\d{6}$", "560001\n")))     # True   (the "\n" slipped through)
print(bool(re.fullmatch(r"[0-9]{6}", "560001\n")))  # False
print(bool(re.fullmatch(r"[0-9]{6}", "560001")))    # True
print(bool(re.fullmatch(r"\d{6}", "५६०००१")))       # True   (Devanagari digits)
print(bool(re.fullmatch(r"[0-9]{6}", "५६०००१")))    # False
Pattern Matches Example
\d a digit (any script; use [0-9] for 0–9 only) \d{6} → 482913
\w letter, digit or _ \w+ → asha_21
\s / \S space / not a space
. any character (except newline)
+ / * / ? 1+ / 0+ / 0 or 1 times
{n} / {m,n} exactly n / m to n times \d{4} → 2025
[A-Z] one char from a set [A-Z]+ → ERROR
^ / $ start / end of text ($ also matches before a final \n)
( ) a group (captures) #(\d+)
(?P<name> ) a named group (?P<year>\d{4})
(?: ) a group that does not capture (?:\d{1,3}\.){3}
\b a word boundary (edge of a word) \b\d{4}\b
\[ \. a real [ or .
Function Returns
re.search(p, text) First match object, or None
re.fullmatch(p, text) Match object only if the whole text fits, else None (use it for validation)
re.findall(p, text) List of all matches (or of the group, if there is one; tuples if there are several)
re.finditer(p, text) One match object per match, to loop over: [m.group(0) for m in re.finditer(p, text)]
re.sub(p, new, text) New text with matches replaced (new can be a text or a function)
re.compile(p) A reusable pattern object with the same methods (.search, .findall, .sub)

See examples/05_log_parser.py, a full server log parser.

🔍 Going deeper: + and * are greedy: they grab as much as they can. Add ? (.+?) to take as little as possible. re caches recently used patterns, so compile is mainly for readability. For HTML or JSON use a real parser, not regex.

Read more: the official re documentation.

Done here? The practice set for Part 8 — 8 exercises with solutions — is on the part page.

Search the guide