Module 15 · Python Standard Libraries — topic 13 of 13
re
Regular expressions with re: search, match, fullmatch, findall and finditer, substitution with sub, splitting, groups and named groups, character classes and quantifiers, flags and compiled patterns.
Learning objectives
- Write basic patterns with classes and quantifiers
- Search, extract and replace text
- Use groups, named groups, flags and compiled patterns
Definition
The re module provides regular expressions: patterns that describe sets of strings. They are used to search text, validate formats, extract parts and replace text.
Introduction
Find every order number in a log, check that a vehicle registration looks valid, reformat dates — regular expressions do these in a line or two.
Why it matters
Text processing is everywhere, and regular expressions are the standard tool across languages, editors and command-line utilities.
Detailed explanation
Write patterns as raw strings (r"\d+") so backslashes reach the regex engine unchanged.
Building blocks: \d digit, \w word character, \s whitespace, . any character, [abc] a set, [^abc] not in set, ^ start, $ end.
Quantifiers: * zero or more, + one or more, ? optional, {n} exactly n, {m,n} between m and n. Add ? (*?, +?) for non-greedy matching.
re.search finds the first match anywhere; re.match only at the start; re.fullmatch requires the whole string to match.
re.findall returns all matches (or group contents); re.finditer yields match objects; re.sub replaces matches (\1 refers to groups); re.split splits on a pattern.
Parentheses create groups, read with m.group(1) or m.groups(); (?P<name>...) creates named groups read with m["name"].
Flags change behaviour: re.IGNORECASE, re.MULTILINE, re.VERBOSE. re.compile(pattern) prepares a pattern for repeated use.
Syntax
- Use raw strings.
- search, findall, sub, split.
- Groups extract parts.
Code examples
Finding and extracting
['1042', '1043']
2026-11-27 ('2026', '11', '27')Replacing, splitting and validating
too many spaces ['a', 'b', 'c ', 'd'] True
More examples
Parsing logs and validating emails
INFO @ 09:00 - server started WARN @ 09:05 - slow query unparsed: garbage line ERROR @ 09:10 - disk full ['asha@example.com', 'ravi.k+news@mail.co.in'] due 01/12/2026
Step-by-step explanation
- Named groups make the log fields self-describing: m["level"] instead of m.group(2).
- The email pattern is a practical check, not a complete validator of every legal address.
- In the replacement, \3/\2/\1 reorders the captured year, month and day.
Expected output
Running “Parsing logs and validating emails” prints exactly:
Practical applications
- Extracting IDs, dates and amounts from logs and documents.
- Form validation for phone numbers and postcodes.
Best practices
- Use raw strings and compile patterns you reuse.
- Prefer named groups for readability.
- Use string methods when a regex isn't needed.
Common mistakes
Forgetting raw strings
Avoid
Prefer
Without r, Python interprets escape sequences before re sees them.
match instead of search
Avoid
Prefer
match only checks the beginning of the string.
Important notes
- This completes the standard library module; next come external libraries and web APIs.
Key takeaways
- Patterns combine classes, quantifiers and anchors.
- search/findall/sub/split cover most tasks.
- Groups extract parts; flags and compile refine use.
Try it yourself
- 1Extract all Indian mobile numbers (10 digits starting with 6–9) from a paragraph.
- 2Convert dates from DD/MM/YYYY to YYYY-MM-DD in a text using re.sub.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
2 questions test this exact topic. Answers and explanations are revealed after you submit.
- ModerateWhat is printed?
- ModerateWhat is printed?