Python Tutorial / Search and Extract Text with Regular Expressions
Regular expressions locate patterns or test a string’s overall shape. A matching format does not prove that a date or amount is meaningful, so separate matching, parsing and application validation.
Choose search, fullmatch or repeated matches
| Function | Purpose |
|---|---|
| re.search | Find a matching part anywhere |
| re.fullmatch | Require the entire string to match |
| re.finditer | Read successive matches and positions |
Raw strings such as r"..." reduce confusion between Python string escapes and regular-expression escapes. They still obey Python string syntax, including restrictions around a final backslash.
For the relevant APIs and platform requirements, see Python: re.
Semantic date validation and HTML extraction build on the rules demonstrated in Work with Dates, Times and Time Zones.
Extract named fields and parse a date
Save the complete code below as regex_demo.py in a separate practice folder, using UTF-8. Run python regex_demo.py in a terminal with your project virtual environment selected. Outside a virtual environment on macOS or Ubuntu, use python3 when that is your interpreter command.
import re
from datetime import date
text = "A001:3500 B002:8000"
pattern = re.compile(r"(?P<id>[A-Z][0-9]{3}):(?P<amount>[0-9]+)")
for match in pattern.finditer(text):
print(match["id"], int(match["amount"]))
value = "2026-10-17"
if re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}", value):
print(date.fromisoformat(value))
Expected output:
A001 3500 B002 8000 2026-10-17
Handle absent matches and semantic validation
Groups divide a match into fields; named groups communicate what those fields mean. A search can return None, so check it before accessing groups. A search pattern can also match only part of an invalid whole value; consider fullmatch for validation.
The date pattern accepts the shape 2026-99-99. date.fromisoformat performs the calendar check afterwards. Use a format-specific parser for HTML or complex CSV rather than trying to capture the whole grammar in one expression.
re.search returns None when nothing matches. After match = re.search(r"[0-9]+", "no digits"), guard group access with if match is not None:. A matching date format still does not make 2026-02-30 a valid date, and parsing complete HTML is a different task from matching a text pattern.
Constrain patterns and inputs
Untrusted patterns or complex nested repetitions over unlimited input can take excessive processing time. Keep accepted patterns controlled and impose appropriate input-length limits.
- Change A001 to a001 to inspect the uppercase rule.
- Change an amount to -1 and check the current pattern’s accepted range.
- Try 2026-02-30: its format matches, but date parsing rejects it.
Restore the sample after each experiment. For a form accepting a single identifier–amount pair, matching the entire input would be a different contract from extracting several pairs from free text.




