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 Search and Extract Text with Regular Expressions documentation.
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.
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.




