…
…
Python Programming Fundamentals · Lesson 38 / 40 · Regular expressions
PreviewIn this lesson you will
re.fullmatchre.search and re.findall, using groups when neededYou can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
Product codes typed by hand at the register must look like LAT-425-S, but sometimes there are wrong entries like lat-425-s, LAT-42-S, or XLAT-425-SX. In online orders, customers write free text and phone numbers in the note field, for example "2 latte, 1 brownie and 3 tea". Ada wants wrong codes to be caught before they enter the system, and the quantities and phone numbers in the notes to be pulled out automatically.
At the end of the lesson, the program you write will validate four codes and pull the phone numbers out of a customer note:
OutputLAT-425-M True
lat-425-m False
LAT-42-M False
XLAT-425-MX False
['555 123 4567', '555 987 6543']Let's start with the tools you already know. In lessons 20 and 21 you learned to slice strings and to use string methods like isupper and isdigit. You can ask one by one: are the first three characters of a product code uppercase letters, is the fourth character a dash, are the next three digits?
Example 1 (case): Trying with string methods
code = "LAT-425-S" print(code[:3].isupper(), code[3] == "-", code[4:7].isdigit()) code = "LATT-425-S" print(code[:3].isupper(), code[3] == "-", code[4:7].isdigit())
OutputTrue True True
True False FalseIt works, but the price is heavy. We wrote a separate comparison for every rule and we are still missing some: the second dash, the size letter being S, M, or L, and the total length of the code are not checked. For a longer format like a phone number, these lines grow into dozens of comparisons. The problem is this: string methods find a fixed text ("latte" in note), but they cannot find a format like "three uppercase letters, a dash, three digits".
A regular expression (regex for short) is a small language that describes a text format. In Python you use it with the re
We validate the codes entered during the day one by one and report them.
import re codes = ["LAT-425-S", "tea-125-M", "BRW-375-L", "LIM-65-M"] pattern = r"[A-Z]{3}-\d{3}-[SML]" for code in codes: if re.fullmatch(pattern, code): print(f"{code}: valid") else: print(f"{code}: invalid")
OutputLAT-425-S: valid
tea-125-M: invalid
BRW-375-L: valid
LIM-65-M: invalidThe serial number format: two digits, a space, one to three uppercase letters, a space, two to four digits.
import re def serial_valid(serial): return re.fullmatch(r"\d{2} [A-Z]{1,3} \d{2,4}", serial) is not None for serial in ["24 ABC 123", "07 A 1234", "24ABC123", "240 AB 12"]: print(serial, serial_valid(serial))
24 ABC 123 True 07 A 1234 True 24ABC123 False 240 AB 12 False
Using `search` for validation. It feels very natural to write the code validator with search, because we think "is the pattern in this code?":
import re def code_valid(code): return re.search(r"[A-Z]{3}-\d{3}-[SML]", code) is not None print(code_valid("XLAT-425-SX"))
OutputTrueNo error message appears and the program runs, but the wrong code counts as valid: search finds the LAT-425-S piece in the middle of the text and is satisfied. The right way: when validating the format of an input, use re.fullmatch, which looks at the whole text. search is for finding a piece inside a text or checking whether a format appears in it.
\d a digit, \w a letter or digit, \s whitespace, [...] one character from the list; + * ? {n} {n,m} say only how many times the element right before them comes. Patterns are written as r"...", and [A-Z] does not cover accented letters.re.fullmatch asks about the whole text, re.search asks about anywhere in it; both return None when they find nothing, so check before calling .group(). Validation is always done with fullmatch.re.findall gives all matches as a list of strings; if the pattern has groups in parentheses, it returns the groups (tuples when there are several). If you need numbers, convert them with int.Next lesson: Unit 7 is finished: you can write programs that read files, survive errors, and use the standard library. In the unit task (G7) you will complete a command-driven program that stores its data in a file; then, in the Capstone, we will turn a request into a program on your own.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
In this lesson you will:
re.fullmatch.re.search and re.findall, and with groups when needed.This lesson is marked "Advanced"; it does not lock your progress. Still, you will meet it in many places, from form validation to data cleaning.
A pattern is made of two kinds of characters. Ordinary characters match themselves: the pattern latte finds the word "latte" in the text, and the pattern - finds a dash. Special elements describe not one character but a group of characters. To say "a digit" you do not list the ten digits one by one, you write \d.
| Element | Meaning | Example pattern | Matches |
|---|---|---|---|
\d | A digit | \d\d | 85 |
\w | A letter, a digit, or an underscore | \w+ | latte |
\s | A whitespace character | \d\s\w+ | 2 latte |
[SML] | One of the characters in the list | [SML] | M |
[A-Z] | One of the characters in the range | [A-Z] | L |
. | Any character except a line break | L.T | LAT |
Quantifiers say how many times an element comes. A quantifier always applies to the single element right before it, not to the whole pattern. In the pattern -?\d+, the ? makes only the dash optional, and the + repeats only \d.
| Quantifier | Meaning | Example | Matches |
|---|---|---|---|
+ | One or more | \d+ | 7, 1042 |
* | Zero or more | \d* | empty, 85 |
? | Zero or one | -?\d | 5, -5 |
{n} | Exactly n times | \d{3} | 085 |
{n,m} | Between n and m times | \d{2,3} | 85, 085 |
Do not try to memorize the tables; get to know them by matching first.
Match each pattern element with its meaning.
For each row, pick its match from the list, then check.
\d\w[SML].+?{3}Let's see the difference between quantifiers on the same text. In the code below, re.findall(pattern, text) returns all the pieces of the text that fit the pattern, as a list. We will meet this function in detail in section 3; for now we use it as a tool to try patterns.
Example 2 (case): Four patterns, the same note
import re text = "Table 7: -5, 085 and 1042" print(re.findall(r"\d+", text)) print(re.findall(r"\d{3}", text)) print(re.findall(r"\d{2,3}", text)) print(re.findall(r"-?\d+", text))
Output['7', '5', '085', '1042']
['085', '104']
['085', '104']
['7', '-5', '085', '1042']Read the lines one by one. \d+ says "one or more digits" and takes digits standing side by side as one piece. \d{3} wants exactly three digits: 7 and 5 drop out because they are one digit, and from inside 1042 the first three digits (104) are cut. The pattern does not know that the number ended; it only sees three digits. \d{2,3} tries three first, and settles for two if three do not work. -?\d+ takes an optional dash in front, so -5 comes with its minus sign. Now change the patterns yourself and compare the results.
Put different patterns in the pattern box. Which numbers come out, and which ones are cut?
Pick a value; predict the output first, then look.
1import re2pattern = r"\d+"3print(re.findall(pattern, "Table 7: -5, 085 and 1042"))
['7', '5', '085', '1042']
Faded lines didn't run with this value. {3} does not know where a number ends: it also cuts the first three digits out of the long number (104). The ? applies only to the dash before it; -5 comes with its minus sign, and 7 matches without a dash too.
Now we can write the pattern of the product code: [A-Z]{3}-\d{3}-[SML]. When you write or read a pattern, the best method is to split it into parts and say them aloud: "three uppercase letters ([A-Z]{3}), a dash, three digits (\d{3}), a dash, S or M or L ([SML])." The dash is an ordinary character, so it was written as it is.
But what if you want to search for the character itself that has a special meaning, like a period, a plus, or a bracket? You put a backslash in front of it: \. is a real period, \+ is a real plus, and \$ is a real dollar sign. The pattern L.T means "L, any character, T" and finds all three of LAT, L-T, and L.T; L\.T finds only L.T.
You may have noticed that all the patterns were written with an r before the quote: r"\d+". This is called a raw string. In a normal string the backslash is special for Python too: "\n" is the newline character, and "\b" is the backspace character. When you write r, Python does not touch the backslash and passes it to the re module as it is. In some sequences the difference is not visible; in others the pattern is silently broken:
Example 3: Why a raw string is needed
import re print("\n" == r"\n", len("\n"), len(r"\n")) print(re.findall("\btea\b", "one tea and two teapots")) print(re.findall(r"\btea\b", "one tea and two teapots")) print(re.findall(r"L.T", "LAT L-T L.T"), re.findall(r"L\.T", "LAT L-T L.T"))
OutputFalse 1 2
[]
['tea']
['LAT', 'L-T', 'L.T'] ['L.T']"\n" is a newline of one character, but r"\n" is two characters: a backslash and an n. The pattern in the second line was written without r, so Python turned \b into the backspace character; the pattern looked for a character that is not in the text and returned an empty list without an error. (\b means "word boundary" in the pattern language; we will not use it in this lesson, here it only shows the importance of r.) For some sequences like "\d", when you do not write r, Python also shows a warning. The rule is simple: always write patterns as r"...".
One last detail: \w also covers letters with accents; the result of re.findall(r"\w+", "2 tea, 1 café latte") is ['2', 'tea', '1', 'café', 'latte']. But [A-Z] is a range, and it covers the 26 uppercase letters of the English alphabet. Predict: what happens if a code is typed at the register with an accented letter?
What does this code print?
import re print(re.fullmatch(r"[A-Z]{3}-\d{3}-[SML]", "TÉA-425-M"))
search and fullmatchWe wrote the pattern; now we need to ask it a question. There are two basic questions in the re module. re.search(pattern, text) asks "is there a piece anywhere in the text that fits the pattern?" and returns the first one it finds. re.fullmatch(pattern, text) asks "does the whole text fit the pattern?"
Both answer in the same way. If they find nothing, None, which you know from lesson 8, is returned. If they find something, a match object is returned; the .group() method of this object gives the matched text. If you print the match object, Python shows where and what matched:
Example 4 (case): Searching in a customer note
import re note = "Table 12 for 2 latte, urgent" match = re.search(r"\d+", note) print(match) print(match.group()) print(re.search(r"urgent", note) is not None) print(re.search(r"mocha", note))
Output<re.Match object; span=(6, 8), match='12'>
12
True
Nonespan=(6, 8) says the match starts at index 6 and ends before index 8; like the slice in lesson 20: note[6:8] is also "12". search found the first number (12) and stopped; it did not look at the next 2. To ask whether the word "urgent" is in the note, we checked that the result is not None. Because None counts as false in a condition, you can also write if re.search(...):.
Here is a very common mistake: calling .group() when there is no match. The result is not an empty string but None, and None has no method called group:
table = re.search(r"Table (\d+)", "takeaway").group(1)
Error:
OutputAttributeError: 'NoneType' object has no attribute 'group'Read the message: "the object of type NoneType has no attribute named group." In other words, search found nothing and you acted as if it had found something. The fix is always the same: first put the result in a variable, check whether it is None, then call .group().
Now predict the difference between the two functions. The pattern is "exactly three digits", the text is five digits:
What does this code print?
import re print(re.fullmatch(r"\d{3}", "12345") is not None)
This difference is decisive in validation. Let's try the codes at the register with both functions:
Example 5 (case): The same codes, two functions
import re pattern = r"[A-Z]{3}-\d{3}-[SML]" for code in ["LAT-425-M", "lat-425-m", "XLAT-425-SX"]: full = re.fullmatch(pattern, code) is not None part = re.search(pattern, code) is not None print(code, full, part)
OutputLAT-425-M True True
lat-425-m False False
XLAT-425-SX False TrueIn the first two codes, both functions gave the same answer. In the third, they differed: in the middle of XLAT-425-SX there is a piece LAT-425-S that fits the pattern; search found it and counted the wrong code as valid. No error message appeared either. The answer to "is this input fully in the right format?" is always fullmatch. search is for "does this format appear inside the text, and if it does, what is it?"
Your turn. The validator is ready in the cell below. Try the three tasks in the comments in order, and run each time.
Try it now· not graded; doesn't affect progress
There is more than one way for the second task; you can try a part like X?[SML] or [SML]L? instead of [SML]. Look at which one also accepts sizes you do not want, like XS or LL: writing a pattern means leaving out what you do not want.
findall and groupsValidation is solved; now let's pull data out of the notes. search gives only the first match. For all matches, use re.findall(pattern, text); the result is a list, and if there is no match, an empty list is returned. Every element of the list is a string. If you want to calculate with the numbers, you need to convert them with int, as in lesson 4:
Example 6 (case): All the quantities in the note
import re note = "2 latte, 1 brownie and 3 tea" quantities = re.findall(r"\d+", note) print(quantities) total = 0 for quantity in quantities: total = total + int(quantity) print(total)
Output['2', '1', '3']
6Without int, the line total + quantity would raise a TypeError, because a string cannot be added to a number. We found the quantities, but we lost which quantity belongs to which product. This is where groups come in. If you put a part of the pattern in parentheses, that part is captured separately.
In the result of search, you reach the groups by number: group(0) or group() is the whole match, group(1) is the first parenthesis, group(2) is the second. groups() gives all the groups as a tuple, and, as in lesson 29, it can be unpacked directly into variables. Let's see with a receipt line:
Example 7 (case): Fields from a receipt line
import re record = "Order #1042 - Table 7 - $13" m = re.search(r"#(\d+) - Table (\d+) - \$(\d+)", record) print(m.group(), "|", m.group(1), m.group(2), m.group(3)) order_no, table, amount = m.groups() print(int(amount) + 1)
Output#1042 - Table 7 - $13 | 1042 7 13
14The pattern describes the whole line: a hash, a number, " - Table ", a number, " - ", a dollar sign, a number. The parentheses mark only the three numbers. This way the word "Table" works in the pattern like a signpost: it shows where the number is, but it does not enter the result. (The dollar sign is special in patterns, so we wrote it as \$.)
When groups are used with findall, the behavior changes: if the pattern has a group, findall returns not the whole match but the groups. With one group, a list of the group strings comes back: the result of re.findall(r"Table (\d+)", "Table 4 and Table 12") is ['4', '12']. With more than one group, each match becomes a tuple. Predict first:
What does this code print?
import re print(re.findall(r"(\d+) (\w+)", "2 latte, 1 brownie"))
A list of tuples is very suitable for unpacking in a loop. Follow the code below step by step. In each round, look at the quantity and product boxes, then at the value in the dictionary: quantity is a string with quotes, but the value that goes into the dictionary is a number without quotes.
Run the code line by line: see which line runs next, the variable boxes and the output.
import re note = "2 latte, 1 brownie and 3 tea" order = {} for quantity, product in re.findall(r"(\d+) (\w+)", note): order[product] = int(quantity) print(order)
Let's collect the same work in one example:
Example 8 (case): Turning a note into an order
import re note = "2 latte, 1 brownie and 3 tea" pairs = re.findall(r"(\d+) (\w+)", note) print(pairs) order = {} for quantity, product in pairs: order[product] = int(quantity) print(order)
Output[('2', 'latte'), ('1', 'brownie'), ('3', 'tea')]
{'latte': 2, 'brownie': 1, 'tea': 3}Why was and not taken as a product? Because the pattern says "digits, space, word"; there is no number before and. If the same product appears twice in the note, this code overwrites the first quantity; adding them up with the get(..., 0) + ... pattern from lesson 27 is your job in the exercises.
Let's combine the three ideas. Putting the patterns at the top of the file under uppercase names makes the program readable: someone who sees the names CODE and PHONE understands at once what the pattern is for. The phone format is "three digits, space, three digits, space, four digits"; turned into a pattern, it is \d{3} \d{3} \d{4}.
Example 9 (case): The lesson's target program
import re # 1. Patterns CODE = r"[A-Z]{3}-\d{3}-[SML]" PHONE = r"\d{3} \d{3} \d{4}" # 2. Validate def code_valid(code): return re.fullmatch(CODE, code) is not None # 3. Extract def phones(note): return re.findall(PHONE, note) # 4. Try for code in ["LAT-425-M", "lat-425-m", "LAT-42-M", "XLAT-425-MX"]: print(code, code_valid(code)) print(phones("Ada 555 123 4567, backup 555 987 6543; table 12"))
OutputLAT-425-M True
lat-425-m False
LAT-42-M False
XLAT-425-MX False
['555 123 4567', '555 987 6543']To see the value of the pattern, what would happen if we searched the same note with only \d+? The result of re.findall(r"\d+", ...) would be ['555', '123', '4567', '555', '987', '6543', '12']: the numbers fall apart into pieces, and the table number mixes in. Because the pattern describes the format, we found the phone as a whole and left the table number out. Now put the phone part of the program in the right order.
Put the lines of the program that finds the phones in a note in order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
In real data, other tools are useful too; if you see them in someone else's code, it is enough to recognize them. re.sub(pattern, new, text) replaces every piece that fits the pattern with new and returns a new string. Uppercase classes are the opposite of the lowercase ones: \D is a character that is not a digit, \W is a character that is not a letter or digit, \S is a character that is not whitespace. * and + are greedy, which means they take as long a piece as possible; if you add ? after them, they take the shortest piece. To ignore the difference between uppercase and lowercase, you can make the text lowercase with lower() or give re.IGNORECASE to the function.
Example 10: Four tools together
import re print(re.sub(r"\D", "", "555-123 45.67")) print(re.sub(r"\s+", " ", "latte and tea")) note = "latte (large) and tea (small)" print(re.search(r"\((.*)\)", note).group(1)) print(re.search(r"\((.*?)\)", note).group(1)) print(re.findall(r"latte", "Latte, LATTE and latte", re.IGNORECASE))
Output5551234567
latte and tea
large) and tea (small
large
['Latte', 'LATTE', 'latte']The first line reduces the phone to digits; after cleaning, checking with fullmatch that it is "10 digits" is a frequently used pair. In the third line, .* took everything from the first opening parenthesis to the last closing one; .*? stopped at the first closing parenthesis.
We take all the dates in an announcement, then the day, month, and year separately. Look at the backslash before the period: \. is a real period.
import re text = "Exams on 12.01.2026 and 03.02.2026; homework 5.3.2026" print(re.findall(r"\d{2}\.\d{2}\.\d{4}", text)) print(re.findall(r"(\d{2})\.(\d{2})\.(\d{4})", text))
Output['12.01.2026', '03.02.2026']
[('12', '01', '2026'), ('03', '02', '2026')]The homework date 5.3.2026 did not come, because the pattern wants exactly two digits for the day and the month. Is this a deliberate decision, or a gap that needs fixing? If single-digit dates should be accepted too, write \d{1,2}. You always choose the pattern according to how the data is really entered.