Regular Expressions (REs, regexes, or regex patterns) are sequences of characters used to identify patterns in data. Although regex can be difficult to learn, it is an invaluable tool for processing strings and other data.
.*. Learn to read patterns fluently and to write the simple ones yourself; leave the hard ones to tools, but check what they give you.Regexes are not specific to Python: most languages and tools, from grep to JavaScript, support them, with small differences in syntax. The examples below write each pattern on its own, like \d+; in Python code it goes inside a raw string, r"\d+", which Writing Your First Regex explains.
Regex uses character classes to illustrate patterns within programs. Developers often opt to use the special sequences explained below. Classes are enclosed within square brackets [] and specify the sequences you want to match. Here are some examples of regex classes:
[xyz]: Matches x, y, or z. This would match the y in Python.[a-d]: Equivalent to [abcd]. This would match the b in box.[^a-c]: Equivalent to [d-z]. Caret (^) matches anything not in the square brackets. This would first match the o in bacon.^ can denote the start of input outside a character class. The next section will discuss this.[A-Za-z0-9]: This matches any alphanumeric character.Classes are often used when you need a specific pattern that the special sequences would not match.
The special sequences are a list of provided classes that make writing regex faster.
The . serves as a wildcard: it matches any single character except a newline (\n). Passing the re.DOTALL flag makes it match newlines too. For example, the regex .y would match my or py, but not yes since there's no character before y.
. loses its meaning and matches a literal dot.The \d special sequence is used to match numbers. It is equivalent to [0-9]. For example, \d matches 2 in "I have 2 cats".
The \D special sequence is used to match anything but numbers. It is equivalent to [^0-9]. For example, \D matches I in "I have 2 cats".
\w matches any word character: letters, digits, and underscores. For ASCII text this is equivalent to [A-Za-z0-9_]. For example, \w will match a in apple, 5 in $5.28, and 3 in 3D. Python's \w also matches accented and non-Latin letters, so it matches É in Émanuel; pass the re.ASCII flag to restrict it to [A-Za-z0-9_].
\W matches everything not in \w. For example, \W matches % in 50%.
\s matches a single white space character, including space, tab, form feed, line feed, and other Unicode spaces. For example, \s\w* matches bar (space intended) in foo bar. More on the asterisk in the Quantifiers section.
\S matches a single character other than white space. For example, \S\w* matches foo in foo bar.
\0 matches a NULL byte. Don't follow it with another digit, or Python reads the digits as an octal escape.
Matching escape sequences is the same as we would use them in normal strings:
\t: Matches a horizontal tab.\r: Matches a carriage return.\n: Matches a line feed (new line).\v: Matches a vertical tab.To match a character that has a special meaning in regex, such as ., *, ?, ( or [, put a backslash in front of it: \. matches a literal dot.
Boundary-type assertions allow for regex to only match characters if they're at certain places within the string.
^ matches the beginning of the input. With the re.MULTILINE flag, it also matches the start of every line. Therefore, ^A will not match the A in an A but will match the first A in An A.
$ matches the end of the input, or the end of every line with re.MULTILINE. Therefore, t$ does not match the t in eater but does match the t in eat.
\b is a word boundary. This is a position where a word character is not followed or preceded by another word character, such as between a letter and a space. This is a confusing assertion to use, so here are some examples of how it works:
\bm matches the m in moon.oo\b will not match the oo in moon because oo is followed by an n (which is a word character).oon\b does match the oon in moon.\w\b\w will never match anything because a word character can never be followed by both a non-word and a word character.Quantifiers indicate the number of characters or expressions to match.
x* matches the preceding item x 0 or more times. For example, bo* matches boooo in "A ghost booooed" and b in "A bird warbled", but nothing in "A goat grunted".
x+ matches the preceding item x 1 or more times. For example, a+ matches the a in "candy" and all the a's in "caaaaaaandy".
x? matches the preceding item x 0 or 1 time. For example, e?le? matches the el in angel and the le in angle.
x{n} matches exactly n occurrences of the preceding item x, where n is a non-negative integer. x{n,m} matches between n and m occurrences, and x{n,} matches n or more. For example, a{2} doesn't match the a in candy, but it matches all of the a's in caandy, and the first two a's in caaandy.
*, +, ? and {n,m} match as much as they can. Against <b>bold</b>, the pattern <.*> matches the whole string, not just <b>. Add a ? after the quantifier to make it match as little as possible: <.*?> matches <b>.Regex is supported through Python's re module. We can use import re to import this module.
We will use findall to find all matches of the regex pattern inside a string. Patterns are written as raw strings, r"", which keep backslashes as they are. Without the r, Python would turn "\b" into a backspace character before the regex engine ever saw it. Let's find all the a's in a string:
1import re
2
3txt = "The cat ate all the candy"
4re.findall(r"a", txt) # Return: ['a', 'a', 'a', 'a']This returns all the instances of the match. Let's show a more helpful example:
re.findall(r"\bS\w+", "The rain in Spain is NASTY") # Return: ['Spain']Let's discuss the other major functions that the re module provides.
re.split()This function will return a list where the input string has been split by each match. Let's split the string on spaces (the equivalent of txt.split(" ")):
1import re
2
3txt = "The cat ate all the candy"
4re.split(r"\s", txt) # Return: ['The', 'cat', 'ate', 'all', 'the', 'candy']We can also control the number of splits using the maxsplit parameter:
re.split(r"\s", txt, maxsplit=2) # Return: ['The', 'cat', 'ate all the candy']re.sub()This function will replace all found occurrences with a provided value. For example, let's replace all the spaces of a string with underscores.
1import re
2
3txt = "The cat ate all the candy"
4re.sub(r"\s", "_", txt) # Return: 'The_cat_ate_all_the_candy'We can also restrict the number of replacements it makes with the count parameter:
re.sub(r"\s", "_", txt, count=2) # Return: 'The_cat_ate all the candy're.search()The search() function will search the string for a match and return an re.Match object if there is a match. Note that re.search() only returns the first match. If no value is found, the function returns None.
Here, we find the first instance of whitespace in the string:
1import re
2
3txt = "The cat ate all the candy"
4re.search(r"\s", txt) # Return: <re.Match object; span=(3, 4), match=' '>The re.Match object has properties that provide information about the search string and the result:
.span() returns a tuple containing the start and end positions of the match..string returns the string passed into the function..group() returns the part of the string where there was a match.In our case:
1find = re.search(r"\s", txt)
2find.span() # Return: (3, 4)
3find.string # Return: 'The cat ate all the candy'
re.match() and re.fullmatch()re.search() looks for a match anywhere in the string. Two variants anchor it: re.match() only matches at the start of the string, and re.fullmatch() only matches if the pattern covers the entire string. fullmatch is the right tool for validating input, where a match on part of the string isn't good enough:
1re.search(r"\d+", "port 8080") # Return: <re.Match object; span=(5, 9), match='8080'>
2re.match(r"\d+", "port 8080") # Return: None, the string doesn't start with a digitre.search(r"^[a-z]+", name) accepts "admin; rm -rf /", because the pattern only has to match the start. Input validation needs both anchors, ^...$, or re.fullmatch(). A missing anchor is one of the most common ways a regex filter gets bypassed. Watch for $ too: it also matches just before a trailing newline, so ^[a-z]+$ accepts "admin\n", while fullmatch doesn't.Finding where a pattern matches is only half the job. Usually you want to pull specific pieces out of the match, and that's what capture groups do. Parentheses in a pattern group part of it and remember what that part matched. On the Match object, .group(1) returns the first group, .group(2) the second, and .groups() returns all of them as a tuple; .group(0) is still the whole match:
1m = re.search(r"(\d+)\.(\d+)\.(\d+)\.(\d+)", "host 10.0.0.5 is up")
2m.group(0) # Return: '10.0.0.5'
3m.groupGroups always capture strings, so convert them yourself: [int(g) for g in m.groups()].
When a pattern has several groups, numbers get hard to follow. A named group, written (?P<name>...), can be read back by name, and .groupdict() returns every named group as a dictionary:
1m = re.search(r"(?P<user>\w+)@(?P<host>[\w.]+)", "contact: echo@ironforge.local")
2m.group("user") # Return: 'echo'
3m.Parentheses also group for quantifiers and alternation: (ab)+ matches ababab, and (cat|dog)s matches cats or dogs. When you need the grouping but don't want to capture, use a non-capturing group, (?:...).
When a pattern has groups, re.findall() returns the groups instead of the whole match: a list of strings for one group, or a list of tuples for several. This is the fastest way to pull every structured piece out of a block of text:
1log = "GET /index.html 200\nPOST /login 403\nGET /admin 401"
2
3re.findall(r"(GET|POST) (\S+) (\d+)", log)
4# Return: [('GET', '/index.html', '200'), ('POST', '/login', '403'), ('GET', '/admin', '401')]
To get Match objects for every match, with positions and named groups, use re.finditer(), which yields them one at a time.
In the replacement string of re.sub(), \1, \2 and so on insert what each group matched, which lets you rearrange text:
re.sub(r"(\w+)@(\w+)", r"\2:\1", "echo@ironforge") # Return: 'ironforge:echo're.compile() turns a pattern into a reusable pattern object with the same methods as the module: .search(), .findall(), .sub() and the rest. Python caches recently used patterns anyway, so compiling is mostly about readability: it gives a pattern a name and keeps it in one place. Flags are passed when compiling:
1IPV4 = re.compile(r"\b(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\b")
2
3IPV4.findall("from 10.0.0.5 to 192.168.1.20")
4# Return: [('10', '0', '0', '5'), ('192', '168', '1', '20')]The flags you'll use most are re.IGNORECASE (re.I) to ignore case, re.MULTILINE (re.M) to make ^ and $ match at every line, and re.DOTALL (re.S) to let . match newlines. Combine them with |: re.compile(pattern, re.I | re.M).
Putting it all together, here's input in the shape of a common puzzle: a picture of crate stacks, a blank line, and then a list of moves. The moves have a regular structure that's awkward to take apart with split() but easy with a regex:
1 [D]
2[N] [C]
3[Z] [M] [P]
4 1 2 3
5
6move 1 from 2 to 1
7move 3 from 1 to 3The pattern captures the three numbers in each move line, and findall collects all of them at once, which skips the crate picture entirely since no line there matches:
1import re
2
3with open("input.txt") as f:
4 text = f.read()When every line has the same shape, there's an even shorter trick: re.findall(r"-?\d+", line) pulls out every integer, including negatives, and ignores everything else. It turns "Sensor at x=2, y=-18" into ['2', '-18'], and it's often the fastest way to parse puzzle input when only the numbers matter.