Expresiones regulares
Suenan a magia negra. Son, en el fondo, una forma de describir un patrón de texto.
Regular expressions
They sound like black magic. Underneath, they are just a way to describe a text pattern.
Imagina que quieres revisar si un texto parece un correo electrónico. Con lo que sabes hasta ahora, tendrías que revisar letra por letra si hay una arroba, si hay un punto después, etc. Una expresión regular (o "regex") describe ese patrón de una sola vez.
Imagine you want to check whether a text looks like an email address. With what you know so far, you would have to check letter by letter for an @, a dot afterwards, and so on. A regular expression (or "regex") describes that pattern in one go.
No hace falta memorizarlos todos el primer día. Con este puñado ya resuelves la mayoría de los casos reales:
\d— un dígito (0-9)\w— una letra, número o guion bajo\s— un espacio en blanco+— una o más veces lo anterior*— cero o más veces lo anterior?— cero o una vez lo anterior (opcional)
No need to memorise them all on day one. With this handful you already solve most real cases:
\d— a digit (0-9)\w— a letter, digit or underscore\s— a whitespace character+— one or more of the previous thing*— zero or more of the previous thing?— zero or one of the previous thing (optional)
re.search() encuentra la primera coincidencia. re.findall() te
las devuelve todas, en una lista.
re.search() finds the first match. re.findall() returns
all of them, in a list.
re.sub() reemplaza todo lo que calce con el patrón, por el texto que le
indiques. Es como un "buscar y reemplazar" mucho más potente que .replace().
re.sub() replaces everything matching the pattern with the text you give it.
It is like a "find and replace" much more powerful than .replace().
Describir un patrón de texto con símbolos como \d, \w y
+, buscar la primera coincidencia o todas, y reemplazar texto que cumpla un
patrón.
Para cerrar el curso, dos ideas que suenan avanzadas pero que vas a reconocer en cuanto las veas en acción: generadores y decoradores.
Describing a text pattern with symbols like \d, \w and
+, finding the first match or all of them, and replacing text that fits a
pattern.
To close the course, two ideas that sound advanced but that you will recognise the moment you see them in action: generators and decorators.