Lesson · Regular Expressions
Python re API
58 min readPython re API
The `re` API separates pattern construction from search operations. Compiled patterns, named groups, iterators, and substitution functions make complex text processing easier to organize.
Learning goals
- Use
search,match, andfullmatchcorrectly, and explain the anchoring rule that separates them. - Walk a
finditerloop and readMatchobjects withgroup,groupdict, andspan. - Predict the shape
findallreturns from the number of groups in the pattern. - Replace matches with
sub, using both a replacement template and a callable. - Compile a pattern once for reuse and say what the module's internal cache does and does not handle.
Mental model
The three readers share one matching engine and differ only in the span they accept, so choosing among them is a question about your input, not about the pattern. All of them return a Match object on success and None on failure: never a boolean, never an exception.
Mental model
read it top to bottom
reader where the match must begin how far it must extend match position 0 anywhere up to the pattern's end search anywhere anywhere up to the pattern's end fullmatch position 0 the entire string
Core idea
The module functions and the compiled-pattern methods are the same engine: re.search(pattern, text) and pattern.search(text) do the same work. The design questions are which reader fits the task (search, match, fullmatch, findall, finditer), what result shape you want back (Match objects versus plain strings or tuples), and how sub rebuilds the text from what the pattern captures.
search
re.search(pattern, text) scans for the leftmost match anywhere in text and returns a Match object, or None when no position works. A compiled pattern exposes the same operation as pattern.search(text).
match
re.match(pattern, text) attempts the match only at position 0, so a prefix the pattern does not cover makes it return None even when the pattern occurs later in the text. On success it returns a Match object, and text after the matched span is allowed to remain.
fullmatch
re.fullmatch(pattern, text) succeeds only when the pattern consumes the entire string, returning a Match object or None. It is the natural reader for validation, because unlike match it leaves no room for unconsumed text at either end.
findall
re.findall(pattern, text) returns every non-overlapping match in one list: plain strings when the pattern has no groups, that group's strings when it has exactly one group, and tuples when it has several. It is the compact reader when you only need the captured text, not positions.
finditer
re.finditer(pattern, text) yields a Match object for each non-overlapping match, in order of position, as a lazy iterator. Prefer it over findall when you need spans, named groups, or group access without flattening the result.
sub
re.sub(pattern, replacement, text) returns a new string with matches replaced, using either a template such as r"\g<id>" or a callable that receives the Match and returns the replacement text. By default every match is replaced; pass count=1 to change only the first.
Compiled patterns
Compile a regular expression when you will reuse it or when a named pattern object improves organization. Python also caches some recent patterns, so compilation is primarily about clarity and explicit reuse.
Named groups
Regex groups control precedence and can capture submatches. Named groups make extraction code more maintainable than relying on positional group numbers.
Walkthrough
re.compilebuilds onePatternfor the whole loop;(?P<id>[A-Z]-\d+)captures an uppercase order code while(?P<price>\d+\.\d+)captures a decimal price.- The lazy
.*?between the groups is what keeps theidcapture from swallowing the rest of the line: it expands only as far as the price group needs, so each match spans one order plus the nearest price. pattern.finditer(text)yieldsMatchobjects in order, andgroup("id")andgroup("price")read the named captures by name instead of by position number.- Predict before running: how many
Matchobjects the iterator yields, which text theidgroup holds in the second match, and whatmatch.group(0)would contain for the first one.
Experiments to try
- Add
print(match.groupdict())inside the loop and confirm the dict keys areidandprice; then printmatch.span()for each match and read the two positions it returns. - Make the middle quantifier greedy (
.*instead of.*?) and explain which price each match captures now and why the earlier price disappears. - Replace
finditerwithfindalland print the result twice: once with both groups in the pattern and once after removing the group parentheses. Explain the two return shapes. - Use
pattern.subwith a callable that rewrites each order as"id=price"and print the new string; verify the unmatched filler text is preserved.
Common mistakes
- Expecting
matchto find a match anywhere: it tests position 0 only, so the worked example'sre.match(r"A-100", text)returnsNonewhilere.searchfinds the code. - Reading
findallas always returning strings: one group gives that group's strings, two or more groups give tuples, and only a group-free pattern gives full-match strings. - Calling
.group()on a failed search:searchand friends returnNoneon failure, so the call raisesAttributeError(not a regex error) unless you guard the result first. - Forgetting that
subreplaces every occurrence by default: when only the first match should change, passcount=1, or the later matches silently transform too.
Practice: Easy
- Run the worked example, then test the three anchoring readers against the full text with the pattern
r"[A-Z]-\d+"and record which ofsearch,match,fullmatchreturnNoneand why. - Collect every decimal price from the text with
finditerandgroup(0), then reproduce the same list withfindall; compare the two lines of code. - Replace the two named groups with unnamed ones and update the prints to
group(1)andgroup(2); confirm the output is identical.
Practice: Medium
- Parse the worked text into a list of
(id, price)pairs withfinditer, convert each price withfloat, and print the total cost of both orders. - Use
subwith the templater"\g<id>: \g<price>"to rewrite each order as"A-100: 42.50"; then repeat with a callable and say when the callable is required. - Run
findallandfinditeron the same pattern: print both results, explain when the iterator and itsMatchobjects are worth the extra code, and give one question the flattened list cannot answer.
Practice: Hard
- Write
parse_orders(text)returning a list of dicts with keysid,price(float), andspanfrommatch.span(); return an empty list when nothing matches and test the default text plus a no-match input. - Failure lab: reproduce the
AttributeErrorfromre.search(r"Z-9", text).group()and the silent shape change when a group is added to afindallpattern; explain the mechanism behind each result. - Time a loop of
re.search(r"[A-Z]-\d+", text)(string pattern, cache lookup each pass) againstpattern.search(text)over many iterations and state what the module's internal pattern cache saves and what it does not.
Lesson checklist
- I can pick
search,match, orfullmatchfrom their anchoring rules and predict which inputs succeed. - I can read a
Matchobject withgroup,groupdict, andspaninside afinditerloop. - I can predict whether
findallreturns strings or tuples from the pattern's group count. - I can use
subwith a template and with a callable, and say when onlycount=1is correct.
Remember
The `re` module exposes one engine through several readers: `match` pins the attempt to position 0, `search` scans the whole text, and `fullmatch` demands the entire string, with each returning a `Match` or `None`. `finditer` hands those objects over one at a time, `findall` flattens them into strings or tuples depending on the pattern's groups, and `sub` rebuilds the text from what the pattern captures. Compile the patterns you reuse, and guard every result before reading a group from it.
Interview angles
What is the main purpose of **search**?+
re.search scans the text and returns the leftmost Match object anywhere in it, or None when nothing matches. Use it when the pattern may start at any position.
What should you pay attention to when using **match**?+
match tests only at position 0, so a prefix the pattern does not cover makes it return None even when the pattern occurs later. Reach for search when the match may start anywhere.
How does **fullmatch** fit into this lesson?+
fullmatch succeeds only when the pattern consumes the entire string, returning a Match or None. That strictness makes it the reader for validation, since match would allow unconsumed text after the matched span.
Why does `re.search(r"Z-9", text).group()` raise an error when the pattern does not occur in `text`?+
search signals failure with None, and None has no group attribute, so the call raises AttributeError rather than a regex error. Guard the result with if match: before reading any group.