Finding patterns with re
A regular expression (*regex*) is a pattern that describes a set of texts: "three digits in a row", "a word that starts with A"……
Regular expressions are a language for describing text patterns. In this lesson you will learn to use the re module to search, validate, extract and replace text: character classes, quantifiers, anchors, groups and flags. You will practice with real cases such as validating emails, phone numbers and dates, or extracting numbers and words from a text.
A regular expression (*regex*) is a pattern that describes a set of texts: "three digits in a row", "a word that starts with A"……
A pattern is built by combining two kinds of pieces: which character to look for (classes) and how many times (quantifiers).
When you want all the matches, not just the first one, there are two functions: findall and finditer .
Regular expressions do not only search: they also transform texts.
Anchors do not consume characters: they indicate a position in the text.
Create a Python program that finds the first number that appears in a text using a regular expression.
Create a Python program that extracts all the numbers from a text and adds them up, using re.findall .
Create a Python program that hides all the digits of a text with re.sub .
Create a Python program that validates postal codes with re.fullmatch .
Create a Python program that validates mobile phone numbers with a pattern that includes an optional part.
Create a Python program that extracts the hashtags and the mentions from a message with re.findall .
Create a Python program that splits a text that uses different separators with re.split .
Create a Python program that checks the format of a date and extracts its parts using groups in a regular expression.
Create a Python program that changes the format of all the dates in a text using re.sub with groups.
Create a Python program that validates email addresses with a simple pattern.