Regular Expressions in Python
Regular expressions (regex) are powerful patterns for matching and manipulating text. They're used for validation (emails, phone numbers), searching, extracting data, and cleaning text.
Python's re module provides full regex support. Patterns can look complex at first, but they're built from simple building blocks.
We'll start with basics and build up with lots of examples.
Importing re and Basic Patterns
Import re and use raw strings (r"") for patterns to avoid escape issues.
Common characters:
- . – any character (except newline)
- ^ – start of string
- $ – end of string
- * – 0 or more
- + – 1 or more
- ? – 0 or 1
- \d – digit
- \w – word character
- \s – whitespace
Main re Methods
search() – first match anywhere match() – match at start findall() – all matches as list sub() – replace matches
Groups and Capturing
Use () to capture parts of the match.
Flags for Advanced Matching
re.IGNORECASE, re.MULTILINE, re.DOTALL etc.
Practical Examples
Validate simple email:
Extract phone numbers:
Quick Quiz
Hemos revisado y comprobado los materiales, pero aún pueden existir errores. El contenido se ofrece únicamente con fines educativos, así que úsalo bajo tu propia responsabilidad y verifica con otras fuentes si es necesario.
✨ Pregunta a Lara — tu compañera de estudio con IA
Desbloquea soporte de aprendizaje personalizado. Lara puede explicar lecciones, resumir temas y responder tus preguntas — disponible desde el plan Go y superiores.
Lara te ayuda a aprender más rápido — exclusivo para los miembros ReadyTools Go, Plus y Max.

