Python Master Course V2 — 079. Regular Expressions
SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · LESSON 079 OF 200 · MODULE 08 — FILES AND STRUCTURED DATA
Regular Expressions
Study time: 70–100 minutes. Prerequisites: functions, exceptions, structured data and Lesson 78.
Video
Video not yet available. This section is reserved for a verified lesson video URL or embedded player.
Learning outcomes
Extract structured tokens using re. Explain the concept, trace a sample program, test a boundary condition and implement a small real-world solution.
Detailed explanation
Regular expressions match patterns rather than meanings. Use raw strings for regex and fullmatch for complete-field validation, and avoid catastrophic backtracking on untrusted text.
Engineering workflow: define the input and expected output, choose a representation, enforce constraints, implement the smallest useful operation, test success and failure paths, and document the result. Separate data acquisition from transformation and presentation. Avoid hidden global state and irreversible changes during practice.
Production considerations: validate external inputs, preserve recoverable source data, use explicit types, log failures without exposing secrets, and plan for malformed or missing records. As programs grow, modularize code into functions with clear contracts and add automated regression tests.
Understand and apply: Regular Expressions
Describe the token before choosing a pattern
A regular expression describes a set of matching strings. It is useful for locating order IDs, checking a narrow identifier format or extracting groups from predictable logs. It does not understand business meaning: a correctly shaped order ID may not exist in your database. Start with a concrete contract. Here an order ID contains two uppercase ASCII letters, a hyphen and four ASCII digits.
Character classes describe one position: [A-Z] permits an uppercase letter and [0-9] permits an ASCII digit. A quantifier such as {4} repeats the preceding item exactly four times. Parentheses capture a part for later use; named groups make that part easier to identify. Raw Python strings prevent Python from interpreting backslashes intended for the regex engine. The regex engine still interprets its own escapes.
Python example
import re
pattern = re.compile(r"\b(?P<prefix>[A-Z]{2})-(?P<number>[0-9]{4})\b")
match = pattern.search("Order AB-1234 shipped")
if match is not None:
print(match.group(0))
print(match.group("prefix"), match.group("number"))
Expected output
AB-1234
AB 1234
The word boundaries stop this search from matching inside a longer word-like identifier. They do not require the entire input to be an ID. Word boundaries use the engine’s notion of word characters, which is broader than ASCII by default. If a log format defines different separators, match those separators explicitly rather than assuming a word boundary is the exact business rule.
Search for a token; fullmatch for a complete field
Python example
import re
identifier = re.compile(r"[A-Z]{2}-[0-9]{4}")
for text in ("AB-1234", "Order AB-1234", "AB-1234\n"):
print(bool(identifier.fullmatch(text)))
print([m.group() for m in identifier.finditer("AB-1234 CD-0007")])
Expected output
True
False
False
['AB-1234', 'CD-0007']
search scans for the first match anywhere. fullmatch requires the whole string to match. finditer yields Match objects for all non-overlapping matches. A trailing newline fails this fullmatch contract; remove it only if the surrounding file format says it is a record separator. Calling strip indiscriminately can turn an invalid identifier into a different accepted input. The $ anchor has special handling for a final newline, so fullmatch is clearer for complete-field validation.
For the project, read a log line, extract exactly one candidate token, validate it with the identifier pattern, and emit either a structured result or a rejection containing the line number. Decide what to do when a line contains zero or multiple IDs. Do not use group on None, and keep the identifier as text so leading zeros survive. Convert the number group only when arithmetic is actually required.
Favor short, bounded patterns and limit input size when processing untrusted text. Some regex constructions can take disproportionate time because of backtracking; a raw string does not fix that. Do not use regex as a substitute for a JSON, XML or CSV parser. Tests should cover valid minimum digits, lowercase letters, too many digits, embedded IDs, missing matches and the final-newline case.
Runnable Python example
Requires Python 3.10+. Save as lesson79.py, run with python lesson79.py or python3 lesson79.py. Examples use only the standard library.
import re
text='Order AB-1234 shipped'
m=re.search(r'\b[A-Z]{2}-\d{4}\b',text)
print(m.group() if m else 'not found')
Expected output:
AB-1234
Walkthrough
Read the imports first, then identify the input and the operation that produces the result. Verify the expected output, change one input, predict the new result and rerun. Explain what should happen if the input is empty, invalid or unavailable.
Guided practical project
Scenario: Extract valid order IDs from logs and report lines that fail validation.
- Specify the data schema and constraints in a small requirements table.
- Create a sample dataset with typical, boundary and invalid records.
- Implement separate functions for validation, transformation and reporting.
- Handle expected errors with informative messages.
- Write three automated tests and compare actual with expected results.
- Document execution, assumptions and limitations.
Acceptance criteria: reproducible output, safe handling of invalid data, no silent data loss, and clearly documented assumptions. The project is a guided assignment, not a claim that it has been executed here.
Common mistakes and debugging
- Using the wrong data type or assuming input is always valid.
- Failing to validate keys, fields, constraints or encodings.
- Hiding exceptions with a broad catch rather than identifying the cause.
- Changing important records without backups or transaction planning.
- Testing only normal inputs rather than empty and boundary cases.
When debugging, reproduce with a minimal example, inspect the traceback, compare values to the documented contract and add a regression test.
Practice with explained answers
Make a prediction before opening each answer. Then trace the example and explain the result in your own words.
What does {4} apply to in [0-9]{4}?
It repeats the immediately preceding digit class exactly four times. It does not repeat the whole order ID. Thus 0007 is valid and 007 is too short.
Which operation validates an entire ID field?
fullmatch, because it requires the whole input to satisfy the pattern. search would accept an ID embedded inside unrelated text.
Why preserve 0007 as a string?
Leading zeros are part of this identifier’s representation. int("0007") becomes 7 and loses them. Identifiers usually need comparison and lookup, not arithmetic.
What is wrong with calling re.search(…).group() immediately?
search may return None. Check the result first so a nonmatching record becomes a documented rejection instead of an unexpected AttributeError.
Does a raw string make a regex safe from slow matching?
No. Raw strings affect Python string parsing. Performance depends on the regex structure and input; use a narrow pattern, bounded input and representative tests.
Mastery checkpoint
Reproduce the sample, explain each operation, complete the guided project and demonstrate at least three test cases. Learner progress is not account-synchronized by this page.
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.