Re
Re en Python (expreciones regulares)
Section titled “Re en Python (expreciones regulares)”¿Qué es re?
Section titled “¿Qué es re?”El módulo re (de regular expressions, expresiones regulares) permite buscar, reemplazar y analizar texto mediante patrones.
Se importa con:
import reFUNCIONES PRINCIPALES
Section titled “FUNCIONES PRINCIPALES”1. re.match(patrón, texto)
Section titled “1. re.match(patrón, texto)”Busca solo al inicio del texto.
import rem = re.match(r"Hola", "Hola mundo")print(m.group()) # Hola2. re.search(patrón, texto)
Section titled “2. re.search(patrón, texto)”Busca en cualquier parte del texto (la primera coincidencia).
re.search(r"mundo", "Hola mundo").group() # mundo3. re.findall(patrón, texto)
Section titled “3. re.findall(patrón, texto)”Devuelve todas las coincidencias en una lista.
re.findall(r"\d+", "Edad 17 años, código 2025") # ['17', '2025']4. re.finditer(patrón, texto)
Section titled “4. re.finditer(patrón, texto)”Devuelve un iterador con objetos Match (útil para posiciones).
for m in re.finditer(r"\d+", "x=5 y=10 z=20"):print(m.group(), m.start(), m.end())5. re.sub(patrón, reemplazo, texto, count=0)
Section titled “5. re.sub(patrón, reemplazo, texto, count=0)”Reemplaza coincidencias por otro texto.
re.sub(r"\d+", "X", "Tengo 2 perros y 3 gatos") # 'Tengo X perros y X gatos'6. re.split(patrón, texto, maxsplit=0)
Section titled “6. re.split(patrón, texto, maxsplit=0)”Divide el texto usando el patrón como separador.
re.split(r"\s+", "uno dos tres") # ['uno', 'dos', 'tres']7. re.compile(patrón, flags=0)
Section titled “7. re.compile(patrón, flags=0)”Compila el patrón para reutilizarlo muchas veces (más eficiente).
patron = re.compile(r"\d+")print(patron.findall("a1b22c333")) # ['1', '22', '333']OBJETOS Match
Section titled “OBJETOS Match”Cuando haces match() o search(), obtienes un objeto con información útil:
m = re.search(r"(\d+)", "Edad: 25 años")print(m.group()) # '25'print(m.start()) # 6print(m.end()) # 8print(m.span()) # (6, 8)Sí hay grupos (entre paréntesis):
m = re.search(r"(\d+)\s*(años)", "Edad: 25 años")print(m.groups()) # ('25', 'años')print(m.group(1)) # '25'print(m.group(2)) # 'años'METACARACTERES MÁS IMPORTANTES
Section titled “METACARACTERES MÁS IMPORTANTES”SECUENCIAS ESPECIALES
Section titled “SECUENCIAS ESPECIALES”FLAGS COMUNES
Section titled “FLAGS COMUNES”Ejemplo:
patron = re.compile(r"""^\d{4} # 4 dígitos al inicio-\d{2} # guion y 2 dígitos-\d{2}$ # guion y 2 dígitos al final""", re.VERBOSE)print(bool(patron.match("2025-10-27"))) # TrueEJEMPLOS PRÁCTICOS
Section titled “EJEMPLOS PRÁCTICOS”1. Validar un correo electrónico
Section titled “1. Validar un correo electrónico”import repatron = r"^[\w\.-]+@[\w\.-]+\.\w+$"print(bool(re.match(patron, "usuario@mail.com"))) # True2. Extraer números de un texto
Section titled “2. Extraer números de un texto”re.findall(r"\d+", "ID123, edad 45, año 2025") # ['123', '45', '2025']3. Reemplazar palabras
Section titled “3. Reemplazar palabras”texto = "Hola mundo cruel"nuevo = re.sub(r"cruel", "hermoso", texto)print(nuevo) # Hola mundo hermoso4. Separar texto por comas o espacios
Section titled “4. Separar texto por comas o espacios”re.split(r"[, ]+", "rojo, verde azul,amarillo") # ['rojo', 'verde', 'azul', 'amarillo']Buenas prácticas
Section titled “Buenas prácticas”✅ Usa r”./…” (raw strings) para no tener que escapar . ✅ Compila patrones que usarás muchas veces con re.compile(). ✅ Usa re.fullmatch() sí necesitas que toda la cadena coincida. ✅ Usa ? después de * o + para modo no codicioso (lazy).
re.findall(r"", "") # ['', '']Ejercicio rápido
Section titled “Ejercicio rápido”Extrae todos los nombres de usuario de correos:
import retexto = "Correos: ana@mail.com, juan123@dominio.org"print(re.findall(r"(\w+)@", texto)) # ['ana', 'juan123']