Skip to main content

Advanced Python

Regular Expressions

Complete lesson for Regular Expressions using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.

L1

Basics — Regular Expressions

Section: Advanced Python. Find, extract, and replace text patterns with Python’s re module — regex symbols, raw strings, groups, quantifiers, and safe compiling.

What is a regular expression?

  • A regex is a pattern language for describing sets of strings — emails, phone numbers, IDs, log lines.
  • Python’s standard engine lives in the re module (not a third-party package).
  • Real life: a “find in documents” search that understands shapes like “3 digits then a dash”, not only fixed text.
import re

text = "order A42 and order B99"
print(re.findall(r"order [A-Z]\d+", text))

Always prefer raw strings

  • Write patterns as r"..." so backslashes stay meaningful to regex, not Python string escapes.
  • In tutorial prose outside code, write \d so the published text shows a single backslash-d.
  • In String.raw code samples, both r"\d+" spellings resolve correctly; prefer r"\d+" for readability.
Prose / TS textPython patternMeaning
\dr"\d"One digit
\wr"\w"Word char [A-Za-z0-9_]
\sr"\s"Whitespace
\br"\b"Word boundary
\\r"\\"A literal backslash

Regex symbols (metacharacters)

  • These special symbols have meaning to the regex engine. To match them literally, escape with a backslash (e.g. \. for a real dot).
  • Inside [...], most metacharacters lose their special meaning (except ^ at the start, - between ends, and ] / \).
SymbolNameMeaningExampleMatches
.DotAny char except newline (unless re.DOTALL)a.cabc, a-c
^CaretStart of string (or line with re.M)^HiHi at start
$DollarEnd of string (or line with re.M)end$end at end
*Star0 or more of previousab*a, ab, abb
+Plus1 or more of previousab+ab, abb (not a)
?Question0 or 1 of previouscolou?rcolor, colour
{m}Exact countExactly m repeats\d{3}42 no; 123 yes
{m,n}Range countFrom m to n repeatsa{2,4}aa…aaaa
[]Character classOne char from the set[aeiou]one vowel
[^]Negated classOne char not in the set[^0-9]non-digit
|Alternation (OR)Either left or rightcat|dogcat or dog
()GroupCapture / group; also for | scope(ab)+ab, abab
\EscapeMake next char literal / start a shorthand\.a real .

Shorthand character classes

  • These are the most common \ shorthands. Prefer raw strings: r"\d+".
  • Uppercase usually means the opposite of the lowercase form (\D = not a digit).
SymbolMeaningSame as (approx.)ExampleMatches
\dDigit[0-9]\d\d42
\DNon-digit[^0-9]\D+Hi
\wWord char[A-Za-z0-9_]\w+Ada_1
\WNon-word[^A-Za-z0-9_]\W@, space
\sWhitespace[ \t\n\r\f\v]a\sba b
\SNon-whitespace[^ \t\n\r\f\v]\S+Hi
\bWord boundaryedge of a word\bcat\bcat not catch
\BNot a word boundaryinside a word\Bcatpart of bobcat
\AStart of stringlike ^ without re.M line mode\AHionly at absolute start
\ZEnd of stringlike $ at absolute endbye\Zonly at absolute end
import re

print(re.findall(r"\d+", "a12 b3"))
print(re.findall(r"\bcat\b", "cat catch cat"))
print(re.findall(r"\w+", "Hi_1!"))

Quantifiers (how many)

  • A quantifier applies to the thing immediately before it (a char, class, group, or shorthand).
  • Default is **greedy** (take as much as possible). Add ? for **non-greedy** / lazy: *?, +?, ??, {m,n}?.
SymbolMeaningGreedy exampleNon-greedyNotes
*0 or morea*a*?Can match empty
+1 or morea+a+?Must appear once
?0 or 1a?a??Optional
{n}Exactly na{3}—aaa only
{n,}n or morea{2,}a{2,}?No upper limit
{n,m}n to ma{2,4}a{2,4}?Inclusive range
import re

print(re.findall(r"[A-Z]{2}\d{3}", "AB123 XY9 CD456"))
print(re.findall(r"colou?r", "color colour"))
print(re.findall(r"a{2,4}", "a aa aaa aaaa aaaaa"))

Anchors and boundaries

  • Anchors do **not** consume characters — they assert a position.
  • With re.MULTILINE (re.M), ^ and $ also match at each line start/end.
SymbolAssertsExampleNotes
^Start of string / line^ErrorLine-aware with re.M
$End of string / linedone$Line-aware with re.M
\AAbsolute start of string\AOKIgnores re.M
\ZAbsolute end of stringOK\ZIgnores re.M
\bWord boundary\bpy\bBetween word / non-word
\BNot a word boundary\BpyInside a larger word

Groups and special constructs

  • Parentheses capture text for later use (m.group(1), findall tuples).
  • Use non-capturing and named groups to keep patterns clear.
SymbolMeaningExampleNotes
(…)Capturing group(ab)+Numbered 1, 2, …
(?:…)Non-capturing group(?:ab)+Groups without saving
(?P<name>…)Named capture(?P<id>\d+)m.group("id")
(?P=name)Backref by name(?P<w>\w)(?P=w)Same char twice
\1, \2Backref by number(a)\1aa
(?=…)Positive lookahead\d+(?=px)Digits before px
(?!…)Negative lookahead\d+(?!px)Digits not before px
(?<=…)Positive lookbehind(?<=\$)\d+Digits after $
(?<!…)Negative lookbehind(?<!\$)\d+Digits not after $

search vs match vs fullmatch

  • re.search finds the first match anywhere in the string.
  • re.match anchors at the start (like search with leading ^ for ordinary patterns).
  • re.fullmatch requires the entire string to match — best for validation.
import re

s = "id=42; ok"
print(bool(re.search(r"\d+", s)))
print(bool(re.match(r"\d+", s)))
print(bool(re.match(r"id=\d+", s)))
print(bool(re.fullmatch(r"id=\d+; ok", s)))

Character classes in practice

  • [abc], [a-z], [^0-9] build sets; combine with quantifiers from the tables above.
  • . matches any char except newline unless re.DOTALL.
  • Escape literal specials: \., \*, \+, \?, \(, \).
import re

print(re.findall(r"[A-Z]{2}\d{3}", "AB123 XY9 CD456"))
print(re.findall(r"colou?r", "color colour"))
print(re.findall(r"file\.\w+", "file.txt file_doc"))

Groups and findall

  • Parentheses capture groups. re.findall returns tuples of groups when groups exist.
  • Use (?:...) for a non-capturing group when you need structure without capture.
  • Named groups (?P<name>...) make groupdict() readable.
import re

text = "Ada Lovelace, Grace Hopper"
print(re.findall(r"(\w+) (\w+)", text))
m = re.search(r"(?P<first>\w+) (?P<last>\w+)", text)
print(m.groupdict())

sub and split

  • re.sub(pattern, repl, string) replaces matches; repl can be a function.
  • re.split splits on a pattern — stronger than str.split for mixed delimiters.
  • Count limits: sub(..., count=1), split(..., maxsplit=1).
import re

print(re.sub(r"\d+", "#", "a1b23c4"))
print(re.split(r"[,;]\s*", "a, b; c"))

compile for reuse

  • pattern = re.compile(r"...", flags) parses once — cleaner and slightly faster in loops.
  • Compiled objects expose .search, .findall, .sub with the same meanings.
  • Store module-level compiled patterns for validators you call often.
import re

email = re.compile(r"^[\w.+-]+@[\w-]+\.[\w.-]+$")
print(bool(email.fullmatch("user@example.com")))
print(bool(email.fullmatch("bad@")))
L2

Advanced — Regular Expressions

Greedy vs non-greedy

  • .* eats as much as possible; .*? eats as little as needed for a match.
  • HTML/XML-ish extraction with regex is fragile — prefer parsers — but non-greedy helps in demos.
  • Prefer explicit character classes over .* when you know the alphabet.
import re

text = "<a>1</a><a>2</a>"
print(re.findall(r"<a>.*</a>", text))
print(re.findall(r"<a>.*?</a>", text))

Lookahead and lookbehind

  • (?=...) / (?!...) are lookaheads; (?<=...) / (?<!...) lookbehinds — assertions that do not consume.
  • Variable-length lookbehind is limited in Python’s re; keep lookbehinds fixed width.
  • Great for “digit preceded by #” without capturing the #.
import re

text = "price $20 and code #42"
print(re.findall(r"(?<=\$)\d+", text))
print(re.findall(r"\d+(?= end)|#\d+", "12 end #99"))

Flags worth knowing

  • re.IGNORECASE (I), re.MULTILINE (M — ^/$ per line), re.DOTALL (S — . matches newline).
  • re.VERBOSE (X) lets you document complex patterns with whitespace and comments.
  • Combine flags with | : re.I | re.M.
import re

text = "Cat\ncar"
print(re.findall(r"^ca.", text, flags=re.I | re.M))

Substitution with functions

  • Pass a function to re.sub — it receives a match object and returns the replacement string.
  • Useful for case transforms, numbering, or dictionary-based expansions.
  • Keep the function pure and fast; it runs per match.
import re

def boom(m):
    return str(int(m.group()) * 10)

print(re.sub(r"\d+", boom, "a2 b3"))

Safety and performance

  • Catastrophic backtracking can freeze on crafted input — avoid nested ambiguous quantifiers on untrusted text.
  • Validate with fullmatch and bounded lengths for user input.
  • For ultra-hot paths, consider the third-party regex module — but interviews expect stdlib re.
TaskAPI
First hitsearch
Whole-string validatefullmatch
All strings / groupsfindall / finditer
Replacesub
Reuse in a loopcompile
L3

Tricky Interview Points

Q1) Why use raw strings for regex?

Answer So backslashes are passed to the regex engine instead of being interpreted as Python string escapes. Write r"\d+" in code; in prose documentation use \\d so readers see \d.

Q2) Name common regex metacharacters.

Answer . ^ $ * + ? { } [ ] \ | ( ) — each has special meaning; escape with \ to match literally (e.g. \. for a real dot).

Q3) What do \d, \w, \s, and \b mean?

Answer \d digit, \w word char [A-Za-z0-9_], \s whitespace, \b word boundary. Uppercase forms (\D, \W, \S, \B) are the opposites.

Q4) Difference between * + and ?

Answer * is 0 or more, + is 1 or more, ? is 0 or 1. All are greedy unless written *? +? ??

Q5) Difference between search, match, and fullmatch?

Answer search finds anywhere; match anchors at the start; fullmatch must consume the entire string.

Q6) What does findall return with groups?

Answer If the pattern has groups, findall returns a list of captured groups (tuples if more than one) instead of the full match text.

Q7) What is a named group?

Answer A group written (?P<name>...) so you can read m.group("name") or m.groupdict().

Q8) What does re.DOTALL do?

Answer Lets . match newline characters as well, useful for multi-line spans.

Q9) Greedy vs non-greedy quantifiers?

Answer Greedy (*, +, {}) take as much as possible; non-greedy (*?, +?, {}?) take as little as needed for an overall match.

Q10) How do you replace with a function?

Answer Pass a callable to re.sub; it receives each Match and returns the replacement string.

Q11) What is re.compile for?

Answer It builds a reusable Pattern object, clarifying intent and avoiding reparsing the same pattern in tight loops.

Q12) How do you match a literal dot?

Answer Escape it: r"\." — a bare . means any character (except newline without DOTALL).

Q13) What is a non-capturing group?

Answer (?:...) groups for structure/quantifiers without creating a capture that findall/group would return.

Q14) Can regex parse HTML reliably?

Answer No for general HTML. Use an HTML parser. Regex is fine for simple, controlled tokens.

Q15) What flag makes ^ and $ work per line?

Answer re.MULTILINE. With it, ^ matches after each newline and $ before each newline.

L4

Simple Programs

Extract emails

import re

text = "mail me at ada@lab.org or bob.smith@uni.edu thanks"
print(re.findall(r"[\w.+-]+@[\w.-]+\.\w+", text))

Validate an Indian mobile number

import re

mobile = re.compile(r"^[6-9]\d{9}$")
for sample in ("9876543210", "12345", "5876543210"):
    print(sample, bool(mobile.fullmatch(sample)))

Parse log level lines

import re

line_re = re.compile(
    r"^(?P<level>INFO|WARN|ERROR)\s+(?P<msg>.+)$",
    re.MULTILINE,
)
log = "INFO boot\nERROR disk full\nWARN heat"
for m in line_re.finditer(log):
    print(m.group("level"), "->", m.group("msg"))

Mask credit-card-like digits

import re

def mask(m):
    digits = m.group()
    return "*" * (len(digits) - 4) + digits[-4:]

text = "card 1234567812345678 ok"
print(re.sub(r"\d{13,16}", mask, text))

Split camelCase

import re

name = "HTTPResponseCode"
parts = re.findall(r"[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+", name)
print(parts)
L5

Problem Solving Tricks

  • Prose needs \d in TypeScript strings so the site shows \d; code samples use r"\d" inside String.raw blocks.
  • Validate with fullmatch, search with search — do not confuse them in interviews.
  • Prefer finditer when you need match positions (m.start(), m.end()).
  • Escape user text with re.escape before embedding it in a larger pattern.
  • Use verbose mode for patterns longer than a tweet.
  • Non-capturing groups keep findall returning full strings when you only needed grouping.
  • Anchor validations: ^...$ or fullmatch.
  • Test patterns in the REPL with a small table of yes/no examples.
  • Beware greedy .* across delimiters — switch to .*? or a negated class [^<]*.
  • Compile once at import time for hot validators.
L6

Practice Programs List

  1. From the symbols table, write demos for ., ^, $, *, +, ?, and |.
  2. Match Indian mobile numbers with \d{10} and word boundaries \b.
  3. Write a fullmatch pattern for HH:MM 24-hour times.
  4. Extract all hashtags from a tweet-like string (#word).
  5. Replace multiple spaces with a single space using re.sub.
  6. Parse key=value pairs with named groups.
  7. Build a password checker: length 8+, one digit, one letter (use lookaheads).
  8. Use re.split to tokenise on commas or semicolons with optional spaces.
  9. Demonstrate greedy vs non-greedy on a nested quote string.
  10. Compile a pattern with re.I | re.M and match headers in a multi-line document.