Regular Expressions
We often want to search for text whose format we know but whose exact wording we don’t. We’ll start with globs for finding files by name, then use regular expressions to find, check, and replace text inside those files.
Globs
When several filenames have a common pattern, we can use a glob to select them together. Write the characters they share and use wildcards for the parts that can vary.
When we use a glob in a command, the shell fills in the matching filenames for us. The command then works with those files just as if we had typed their names individually. This substitution is called expansion.
| Glob syntax | Meaning |
|---|---|
* |
Any run of characters, including none |
? |
Exactly one character |
[ab] |
One character from the set |
[a-z] |
One character in the range |
[!ab] |
One character outside the set |
We have already looked for patterns via the command line. For example, in ls *.log, the * matched any run of characters in a filename. The pattern access-2026-10-1?.log matched one character in the final position of the date.
Suppose we keep birthday reminders in several text files. First, we need to find the reminder files among our other notes. In a new practice folder, create three empty sample files:
touch birthdays-a.txt birthdays-b.txt notes.txt
ls birthdays-?.txt # birthdays-a.txt birthdays-b.txt
ls birthdays-[ab].txt # birthdays-a.txt birthdays-b.txt
ls birthdays-[!b].txt # birthdays-a.txtIn ls *.txt, the pattern selects text files in the current folder. If we had a folder called archive, ls archive/*.txt would list the text files inside it. The pattern */*.txt allows any folder name before the slash, so it finds text files one folder down.
We can also use globs when a Python program needs to choose which files to process. Python’s standard-library glob module looks for files using the same wildcard notation. glob.glob(pattern) returns the matching paths in a list, so the program can loop over them.
Create select_birthdays.py in the same folder:
import glob
print(sorted(glob.glob('birthdays-*.txt'))) # ['birthdays-a.txt', 'birthdays-b.txt']Run python3 select_birthdays.py. sorted puts the filenames in order.
Regular Expressions
A regular expression, often shortened to regex, describes a pattern in text. It can specify which characters may appear, in what order, and how often. A piece of text that fits the pattern is a match.
Globs and regexes both describe patterns, but their symbols do not always mean the same thing. To translate a glob into a regex:
- Replace
?with.to match any one character, except a newline. - Replace
*with.*: the dot matches a character, and the star allows it to repeat zero or more times. - Replace a dot in the filename with
\.. The backslash makes the regex require an actual dot instead of accepting any character.
To match a whole filename ending in .txt, the glob is *.txt and the regex is .*\.txt. Both match birthdays-a.txt.
Our birthday notes use Sam Altman, Elon Musk, Dario Amodei, Sundar Pichai, Satya Nadella, and Tim Cook. We’ll use their first names in the short Python examples. We want to collect the dates, check how newly entered dates are written, and put them in a consistent format.
A regex is written as text, but some of its characters give instructions about what to match. Most characters stand for themselves: a pattern containing a letter requires that letter in the text. These are literal characters. Other characters, called metacharacters, have special jobs, such as allowing a choice or repeating part of a pattern.
A character class specifies the allowed choices for one character. A quantifier controls how many times the preceding character or group can appear. An anchor restricts where a match can occur, such as the beginning or end of the text. It does not stand for another character that the text must contain.
The table below shows common regex syntax and its meaning in Python. (All the cheatsheets from this reading are available as a PDF here.)
| Syntax | Meaning | Example |
|---|---|---|
| Ordinary text | Match those characters in order | cat matches cat inside scatter |
. |
Any one character except a newline | c.t matches cat or cut |
\. |
A literal dot | a\.b matches a.b |
\d |
One digit | \d matches 4 |
\w |
One word character: a letter, digit, or underscore | \w matches a, 4, or _ |
\s |
One whitespace character | \s matches a space, tab, or newline |
\S |
One character that is not whitespace | \S matches a or !, but not a space |
[abc] |
One of the listed characters | [aeiou] matches a lowercase vowel |
[a-z], [A-Z], [0-9] |
One character from a range | [A-Z][0-9] matches B7 |
[^abc] |
One character outside the set | [^0-9] matches a character other than an ASCII digit |
* |
Zero or more of the preceding character or group | ab* matches a, ab, or abbb |
+ |
One or more | \d+ matches a run of digits |
? |
Zero or one | colou?r matches color or colour |
{n} |
Exactly n repetitions |
\d{3} matches three digits |
{m,n} |
Between m and n repetitions |
\d{3,5} matches three to five digits |
.* |
Zero or more characters, except newlines | a.*b matches ab or a long b |
^ |
Start of the string | ^cat matches cat nap but not the cat |
$ |
End of the string, or just before a final newline | cat$ matches the cat but not cat nap |
(...) |
Group a pattern and capture its matched text | (ab)+ repeats the pair ab |
| |
Match either alternative | cat|dog matches either word |
\g<1> in a replacement |
Insert the text captured by group 1 | r'birthday: (\d+)' with replacement r'day \g<1>' turns birthday: 14 into day 14 |
The syntax is documented in Python’s regex reference.
The pattern describes what text we are looking for. We also need to decide what to do when we find it: check whether it is present, collect the matches, or change the text. The same pattern can be used for any of these tasks. The table below shows the functions in Python’s built-in re module.
| Function | Arguments | Result |
|---|---|---|
re.search |
pattern, text |
First match anywhere in the text: a match object, or None if there is no match. |
re.findall |
pattern, text |
List of non-overlapping matches, in order. Capturing groups determine which parts it returns. No matches gives []. |
re.fullmatch |
pattern, text |
A match object if the entire string matches; otherwise None. |
re.sub |
pattern, replacement, text |
New string with every non-overlapping match replaced. The original string is unchanged. |
A match object records what matched and where it appeared in the original string. The search examples below show how to use one.
Both Python strings and regex patterns use backslashes to give characters special meanings. We want Python to pass the backslashes to re so it can interpret the pattern. A raw string, with an r before the opening quote, keeps Python from interpreting sequences such as \n first. Use raw strings for regex patterns.
In r'\d+', Python passes the characters \, d, and + to re, which interprets them as “one or more digits.”
Copy any Python block below into birthdays.py and run python3 birthdays.py. Each block includes its imports and sample text. The completed script runs all the Python regex examples together.
Searching
Searching answers whether the text contains anything that fits our pattern and, if so, where it first appears. The match may be a small part of a much longer string. Characters before or after it do not prevent the search from succeeding.
The result lets a program decide what to do next based on whether a match was found. A match object is truthy and None is falsy, so a search result can be used directly in an if.
Try two separate searches in the same sentence, one for a word that is present and one for a word that is absent:
import re
print(re.search(r'birthday', 'Sam has a birthday today')) # <re.Match object; span=(10, 18), match='birthday'>
print(re.search(r'anniversary', 'Sam has a birthday today')) # NoneUse the result in a condition:
import re
if re.search(r'birthday', 'Sam has a birthday today'):
print('Send a card') # Send a card
Often we care about the kind of character in a position without requiring one particular character. A character class defines the choices we will accept there. It matches one character from that set each time it is used.
A quantifier tells us how many times a character or group may repeat. Combining a class with a quantifier lets us specify both the allowed characters and how many we expect. The quantifier applies only to the character or group immediately before it.
In ab+, only the b repeats: it can match ab or abbb. Parentheses let us repeat several characters together, so (ab)+ can match ab or abab.
Search for a digit in Sam Altman’s birth year:
import re
print(re.search(r'\d', 'Sam was born in 1985')) # <re.Match object; span=(16, 17), match='1'>Add + to match a run of digits:
import re
print(re.search(r'\d+', 'Sam was born in 1985')) # <re.Match object; span=(16, 20), match='1985'>The pattern [ST][ai]m matches Sam or Tim: the first class allows S or T, and the second allows a or i. In birthdays?, the ? makes the final s optional:
import re
print(bool(re.search(r'[ST][ai]m', 'Tim: 11/01'))) # True
print(bool(re.search(r'birthdays?', 'one birthday this week'))) # True
We may want to accept several different forms of text in the same search. Alternation joins patterns with | to say that any one of them is an acceptable match. Each alternative can describe a complete pattern of its own.
Alternation works in Python’s re functions and in the shell command grep -E. The -E option selects extended regular expressions, where | is the alternation operator. grep prints each matching line once, even if several parts of the line match.
Save these lines as birthday-notes.txt:
Sam Altman: April 22
Elon Musk: June 28
Dario Amodei: January 13
Sundar Pichai: June 10
Satya Nadella: August 19
Tim Cook: November 01
Search for birthdays in either June or August:
grep -E 'June|August' birthday-notes.txt # Elon Musk: June 28
# Sundar Pichai: June 10
# Satya Nadella: August 19Extraction and Groups
A document may contain many pieces of information that our program needs to work with individually. Extraction collects the matching pieces as values the program can use, leaving the original text unchanged. A regex tells the program how to recognize each piece without knowing its contents in advance.
Without capturing groups, findall returns the complete matches as a list of strings. It preserves their order and any duplicates. Matched digits are still strings. Use int to convert them when you need to do arithmetic.
Extract the dates from birthday notes written in month/day order:
import re
text = 'Sam: 04/22; Elon: 06/28'
print(re.findall(r'\d{2}/\d{2}', text)) # ['04/22', '06/28']The pattern requires two digits, a slash, and two more digits.
Sometimes we need surrounding text to recognize the information we want, but only want to keep part of what matched. A capturing group marks that part with parentheses so we can retrieve it separately. The rest of the pattern still has to match, even though we do not include it in the extracted value.
With one capturing group, findall returns that group’s text for each match. With multiple groups, it returns tuples of the captured strings.
Put parentheses around the month:
import re
text = 'Sam: 04/22; Elon: 06/28'
print(re.findall(r'(\d{2})/\d{2}', text)) # ['04', '06']Capture the month and day separately:
import re
text = 'Sam: 04/22; Elon: 06/28'
print(re.findall(r'(\d{2})/(\d{2})', text)) # [('04', '22'), ('06', '28')]For a search result, .group(0) gives the whole match and .group(1) gives the first capture. Use it after checking that a match was found:
import re
match = re.search(r'birthday: (\d{2}/\d{2})', 'Sam birthday: 04/22')
if match:
print(match.group(0)) # birthday: 04/22
print(match.group(1)) # 04/22A message might mention files containing birthday lists. We want to collect the .csv filenames from that message:
import re
print(re.findall(r'\w+\.csv', 'files: birthdays.csv, friends.csv')) # ['birthdays.csv', 'friends.csv']Read \w+\.csv in three pieces: \w+ matches one or more letters, digits, or underscores, \. requires a dot, and csv matches those three letters. Without the backslash, the dot would accept any character, including the X in birthdaysXcsv. Here we are searching the text of a message. Unlike the glob examples, this does not look for files on our computer.
Validation and Substitution
Programs often expect input to follow a particular format. Validation checks whether a supplied value meets that requirement before the program uses it. To check the format of an entire input, we need the pattern to match from its first character to its last. Extra text before or after a match should cause the check to fail.
re.fullmatch applies the pattern to the entire string. This checks the input’s format, but cannot tell us whether the information itself is accurate.
Compare searching for a word with matching the whole string:
import re
print(bool(re.search(r'birthday', 'Sam has a birthday today'))) # True
print(bool(re.fullmatch(r'birthday', 'Sam has a birthday today'))) # False
print(bool(re.fullmatch(r'birthday', 'birthday'))) # TrueNow check a birthday date with and without an extra digit:
import re
date_pattern = r'\d{2}/\d{2}'
print(bool(re.fullmatch(date_pattern, '04/22'))) # True
print(bool(re.search(date_pattern, '04/220'))) # True
print(bool(re.fullmatch(date_pattern, '04/220'))) # FalseThis pattern also accepts 99/99: it checks how the date is written, not whether that date exists.
Sometimes we want to make the same kind of change wherever a pattern occurs in a document. Substitution finds each match and puts replacement text in its place. We can describe what needs changing even when the individual matches contain different text. The result is a new string, with text outside the matches copied unchanged.
A replacement can be fixed text, or it can reuse parts of each match. Parentheses in the pattern capture those parts, numbered from left to right. In the replacement, \g<1> inserts the first group’s text, \g<2> inserts the second group’s text, and so on.
Replace each run of spaces or tabs in a birthday reminder with one space. The pattern \s+ matches one or more whitespace characters:
import re
print(re.sub(r'\s+', ' ', 'Sam birthday:\t04/22')) # Sam birthday: 04/22To rewrite month/day dates in day-month order, capture both parts and swap their positions in the replacement:
import re
text = 'Sam: 04/22; Elon: 06/28'
print(re.sub(r'(\d{2})/(\d{2})', r'\g<2>-\g<1>', text)) # Sam: 22-04; Elon: 28-06Testing and Complexity
A regex can be valid syntax and still describe the wrong set of strings. To check that it expresses what we intend, test it on strings that should match and strings that should not. Both matter: a missed match leaves wanted text out of an extraction, while an overly broad pattern includes unwanted text. For substitution, check the full result so you catch changes to text that should have been preserved.
These assertions check that a date has exactly two digits on each side of the slash:
import re
pattern = r'\d{2}/\d{2}'
assert re.fullmatch(pattern, '04/22') is not None
assert re.fullmatch(pattern, '4/22') is None
assert re.fullmatch(pattern, '0422') is None
assert re.fullmatch(pattern, '') is None
assert re.fullmatch(pattern, 'Sam: 04/22') is None
assert re.fullmatch(pattern, '04/220') is NoneFor substitution, compare the entire result, including the names and punctuation:
import re
text = 'Sam: 04/22; Elon: 06/28'
result = re.sub(r'(\d{2})/(\d{2})', r'\g<2>-\g<1>', text)
assert result == 'Sam: 22-04; Elon: 28-06'A tester such as regex101.com highlights matches and explains each part of a pattern. Select Python under Flavor. Enter the pattern in Regular Expression and paste the sample text into the text area below it. Enter just the pattern, without Python’s r prefix or surrounding quotes.
Try these experiments in regex101:
- How many digits? Paste
Sam: 04/22; Elon: 6/28; Dario: 1/13as the text and\d{2}/\d{2}as the pattern. Which dates match? Change both{2}quantifiers to{1,2}and compare the matches. - Which dot? Use the text
birthdays.csv friendsXcsvand the pattern\w+.csv. Why does the second name match? Change the pattern to\w+\.csvand check again. - What did we capture? Use the text
Sam: 04/22; Elon: 06/28and the pattern(\d{2})/(\d{2}). Inspect the groups for each match. Which group holds the month? Move the parentheses to capture the entire date as one group.
Then copy one of your patterns into a Python example above and compare the result.
For more examples, see the Automate the Boring Stuff regex chapter.
Regex raises two questions that computer scientists study far beyond text processing: what can we describe, and how much work does it take to check? A formal language is a set of strings. A regex describes one of these sets by giving rules for which strings belong. The set can be infinite even though the pattern is only a few characters long.
The pattern ab* describes a, ab, abb, abbb, and so on. We cannot list every member, but we can decide whether a particular string belongs: it must start with one a and contain only bs afterward.
A foundational result connects regular expressions to finite-state machines. These machines read one character at a time and keep track of which of a fixed set of states they are in. For the basic regex operations, a pattern and a machine can describe exactly the same language. That gives us a way to turn a description of what we want into a program that recognizes it.
Complexity studies how the work of solving a problem grows as the input gets larger. Some regex matchers try one possibility, back up when it fails, and try another. With enough overlapping choices, the number of attempts can grow exponentially. A different algorithm can track the possible states together and avoid repeating that work. The speed difference can be enormous: over a minute versus about 20 microseconds to check the same pattern on the same input. A microsecond is one millionth of a second.
For other problems, researchers do not know whether such shortcuts exist. One example is 3-SAT, which asks whether a collection of logical requirements can all be satisfied by choosing true or false for each variable. Trying every combination gets expensive quickly: each additional variable doubles the number of combinations to check. The Exponential Time Hypothesis proposed that this exponential growth is unavoidable on the hardest inputs, even with a better algorithm. Researchers have used that assumption to argue that many other problems cannot be solved much faster either.
In October 2026, OpenAI announced an AI-generated disproof of the hypothesis. The company released a proof checked by Lean, a program for verifying mathematical proofs, and outside researchers are examining the result. If confirmed, it would reopen the search for faster algorithms across problems that researchers had treated as computationally difficult.