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.
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
remodule (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
\dso 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 text | Python pattern | Meaning |
|---|---|---|
\d | r"\d" | One digit |
\w | r"\w" | Word char [A-Za-z0-9_] |
\s | r"\s" | Whitespace |
\b | r"\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]/\).
| Symbol | Name | Meaning | Example | Matches |
|---|---|---|---|---|
. | Dot | Any char except newline (unless re.DOTALL) | a.c | abc, a-c |
^ | Caret | Start of string (or line with re.M) | ^Hi | Hi at start |
$ | Dollar | End of string (or line with re.M) | end$ | end at end |
* | Star | 0 or more of previous | ab* | a, ab, abb |
+ | Plus | 1 or more of previous | ab+ | ab, abb (not a) |
? | Question | 0 or 1 of previous | colou?r | color, colour |
{m} | Exact count | Exactly m repeats | \d{3} | 42 no; 123 yes |
{m,n} | Range count | From m to n repeats | a{2,4} | aa…aaaa |
[] | Character class | One char from the set | [aeiou] | one vowel |
[^] | Negated class | One char not in the set | [^0-9] | non-digit |
| | Alternation (OR) | Either left or right | cat|dog | cat or dog |
() | Group | Capture / group; also for | scope | (ab)+ | ab, abab |
\ | Escape | Make 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).
| Symbol | Meaning | Same as (approx.) | Example | Matches |
|---|---|---|---|---|
\d | Digit | [0-9] | \d\d | 42 |
\D | Non-digit | [^0-9] | \D+ | Hi |
\w | Word char | [A-Za-z0-9_] | \w+ | Ada_1 |
\W | Non-word | [^A-Za-z0-9_] | \W | @, space |
\s | Whitespace | [ \t\n\r\f\v] | a\sb | a b |
\S | Non-whitespace | [^ \t\n\r\f\v] | \S+ | Hi |
\b | Word boundary | edge of a word | \bcat\b | cat not catch |
\B | Not a word boundary | inside a word | \Bcat | part of bobcat |
\A | Start of string | like ^ without re.M line mode | \AHi | only at absolute start |
\Z | End of string | like $ at absolute end | bye\Z | only 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}?.
| Symbol | Meaning | Greedy example | Non-greedy | Notes |
|---|---|---|---|---|
* | 0 or more | a* | a*? | Can match empty |
+ | 1 or more | a+ | a+? | Must appear once |
? | 0 or 1 | a? | a?? | Optional |
{n} | Exactly n | a{3} | — | aaa only |
{n,} | n or more | a{2,} | a{2,}? | No upper limit |
{n,m} | n to m | a{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.
| Symbol | Asserts | Example | Notes |
|---|---|---|---|
^ | Start of string / line | ^Error | Line-aware with re.M |
$ | End of string / line | done$ | Line-aware with re.M |
\A | Absolute start of string | \AOK | Ignores re.M |
\Z | Absolute end of string | OK\Z | Ignores re.M |
\b | Word boundary | \bpy\b | Between word / non-word |
\B | Not a word boundary | \Bpy | Inside a larger word |
Groups and special constructs
- Parentheses capture text for later use (
m.group(1),findalltuples). - Use non-capturing and named groups to keep patterns clear.
| Symbol | Meaning | Example | Notes |
|---|---|---|---|
(…) | 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, \2 | Backref by number | (a)\1 | aa |
(?=…) | 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.searchfinds the first match anywhere in the string.re.matchanchors at the start (likesearchwith leading^for ordinary patterns).re.fullmatchrequires 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 unlessre.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.findallreturns tuples of groups when groups exist. - Use
(?:...)for a non-capturing group when you need structure without capture. - Named groups
(?P<name>...)makegroupdict()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;replcan be a function.re.splitsplits on a pattern — stronger thanstr.splitfor 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,.subwith 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@"))) 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
fullmatchand bounded lengths for user input. - For ultra-hot paths, consider the third-party
regexmodule — but interviews expect stdlibre.
| Task | API |
|---|---|
| First hit | search |
| Whole-string validate | fullmatch |
| All strings / groups | findall / finditer |
| Replace | sub |
| Reuse in a loop | compile |
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.
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) Problem Solving Tricks
- Prose needs
\din TypeScript strings so the site shows\d; code samples use r"\d" inside String.raw blocks. - Validate with
fullmatch, search withsearch— do not confuse them in interviews. - Prefer
finditerwhen you need match positions (m.start(),m.end()). - Escape user text with
re.escapebefore embedding it in a larger pattern. - Use verbose mode for patterns longer than a tweet.
- Non-capturing groups keep
findallreturning full strings when you only needed grouping. - Anchor validations:
^...$orfullmatch. - 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.
Practice Programs List
- From the symbols table, write demos for
.,^,$,*,+,?, and|. - Match Indian mobile numbers with
\d{10}and word boundaries\b. - Write a
fullmatchpattern forHH:MM24-hour times. - Extract all hashtags from a tweet-like string (
#word). - Replace multiple spaces with a single space using
re.sub. - Parse
key=valuepairs with named groups. - Build a password checker: length 8+, one digit, one letter (use lookaheads).
- Use
re.splitto tokenise on commas or semicolons with optional spaces. - Demonstrate greedy vs non-greedy on a nested quote string.
- Compile a pattern with
re.I | re.Mand match headers in a multi-line document.