Regex in Python
Use re.search, match and fullmatch correctly, write raw-string patterns, compile and reuse them, and read match objects. Run on Python 3.9.
Capturing groups and numberingNamed capture groupsFlags: ignore case, global and multilineReplacing with regex
Regex in Python
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- search looks anywhere, match must begin at the start, and fullmatch must cover the whole string. match does not anchor the end, and $ before a trailing newline is a trap that fullmatch avoids.
- Write patterns as raw strings, r'\bcat\b'. In a normal string '\b' is a single backspace character and the pattern silently fails, and '\d' is an invalid escape that Python 3.9 warns about.
- re.compile returns a pattern object whose methods (search, match, finditer, sub) take the same arguments plus optional pos and endpos. Compile once when you reuse a pattern or want to name it.
- A match object has group(), groups(), groupdict(), start(), end(), span(), lastgroup and expand(). Failed searches return None, so check before calling .group().
- I ran Python 3.9, which has no atomic groups (?>...) and no possessive quantifiers a++. Python 3.11 added both, and the lookbehind rule still needs a fixed width in 3.9.
Python has the same engine, with different entry points
Everything about patterns carries over: classes, quantifiers, groups, lookaround. What changes is the API around them. The re module has no regex literals and no g flag, so the choice between the functions does the work that flags do elsewhere. All examples here ran on Python 3.9.6.
search, match and fullmatch
Three functions answer three different questions about abc123def:
re.search(r'\d+', t) -> <re.Match object; span=(3, 6), match='123'>
re.match(r'\d+', t) -> None
re.match(r'[a-z]+', t) -> <re.Match object; span=(0, 3), match='abc'>
re.fullmatch(r'\d+', t) -> None
re.fullmatch(r'[a-z]+\d+[a-z]+', t) -> <re.Match ... span=(0, 9) ...>
search scans for the pattern anywhere. match requires it to start at the beginning but says nothing about the end, so re.match(r'[a-z]+', t) succeeded after only three characters. fullmatch requires the pattern to account for the whole string. For validation, fullmatch is the one that says what you mean.
It also avoids a trap. $ matches at the end of the string and also just before a final newline:
re.search(r'^\d+$', '12\n') -> <re.Match ... match='12'>
re.fullmatch(r'\d+', '12\n') -> None
re.search(r'^\d+\Z', '12\n') -> None
The $ version accepted 12 followed by a newline. \Z (Python’s true end of string) and fullmatch both rejected it. If your input came from a file or a form, this matters.
Raw strings
Python processes backslashes in strings before the regex ever sees them. I checked:
re.search('\bcat\b', 'a cat') -> None
re.search(r'\bcat\b', 'a cat') -> <re.Match ... span=(2, 5), match='cat'>
len('\b'), len(r'\b') -> 1 2
In a normal string, '\b' is one character, backspace, so the first search looked for the wrong thing and found nothing. The r prefix leaves the backslash alone, so the regex engine receives \b, two characters. Always write patterns as raw strings. An invalid escape like '\d' in a normal string is a DeprecationWarning in 3.9 that is off by default, and running with -W error turned it into SyntaxError: invalid escape sequence \d.
compile, and the pattern object
re.compile(pattern, flags) returns a pattern object with the same functions as methods:
pat = re.compile(r'(?P<user>\w+)@(?P<host>[\w.]+)')
pat.pattern # '(?P<user>\w+)@(?P<host>[\w.]+)'
pat.groups # 2
pat.groupindex # {'user': 1, 'host': 2}
pat.flags # 32 (re.UNICODE, the default for str patterns)
Compile when you reuse a pattern, or just to give it a name. The methods take extra pos and endpos arguments, which the module-level functions lack. On 'ab12', p.match('ab12', 2) matched at position 2, p.match('ab12', 1) returned None, and p.search('12ab', 0, 1) saw only the first character and matched 1. I haven’t measured a speed difference, so I won’t claim one.
Finding more than one match
pat.findall(text) -> [('ada', 'example.com'), ('grace', 'navy.mil')]
[m.group() for m in pat.finditer(text)] -> ['ada@example.com', 'grace@navy.mil']
findall returns strings, or tuples of groups when the pattern has groups, a quirk covered in the non-capturing groups lesson. finditer yields match objects, one at a time. When in doubt, use finditer. re.sub and re.split have their own lessons.
The match object
m = pat.search(text)
m.group() 'ada@example.com'
m.groups() ('ada', 'example.com')
m.groupdict() {'user': 'ada', 'host': 'example.com'}
m.span() (0, 15) m.span('host') (4, 15)
m.lastindex 2 m.lastgroup 'host'
m.expand(r'\g<host>: \g<user>') 'example.com: ada'
start(), end() and span() give positions, with an optional group name or number. m.string is the input and m.re the pattern object. A match object is truthy, and a failed search returns None, which is falsy but has no .group():
re.search(r'\d+', 'no digits').group()
AttributeError: 'NoneType' object has no attribute 'group'
So test first. if (m := re.search(r'\d+', 'a 42')): print(m.group()) printed 42 and uses the walrus operator, available in 3.8 and later.
What Python 3.9 does not have
These three patterns failed to compile in 3.9.6:
(?>a+)b re.error: unknown extension ?>
a++b re.error: multiple repeat
(?<=a+)b re.error: look-behind requires fixed-width pattern
The first is an atomic group and the second a possessive quantifier. Python 3.11 added both, which is a matter of record I did not run, and the pending lesson on atomic groups covers what they do. The third is the fixed-width lookbehind rule from the lookbehind lesson, which I didn’t test on newer versions.
About the video
The embedded video is Corey Schafer’s “Python Tutorial: re Module - How to Write and Match Regular Expressions (Regex)”, published 24 October 2017 and 53 minutes 17 seconds long. It is the longest pick in this group. The description says it teaches reading, writing and matching regular expressions with the re module, for patterns like email addresses, phone numbers and URLs, and links the code on GitHub. It has no chapters, so I couldn’t clip it by topic, and I couldn’t read a transcript. I can’t say whether it covers fullmatch or the 3.9 limitations above. If an hour is too long, Reuven Lerner’s five-minute video on search, match and findall is the quick one. English per its title and description.
What I did not run
Python 3.10 and later (including 3.11’s atomic groups), the regex third-party module, and compiled-pattern timing.
Next
Python and JavaScript are two hosts for the same ideas. The shell is a third, with its own dialect rules: regex on the command line.
Check yourself
Which of re.search, re.match and re.fullmatch would you use to validate that a whole string is three digits, and why?
re.fullmatch(r'\d{3}', s). It must cover the entire string, so 1234 fails. re.match would accept 1234 because it anchors only the start, and ^\d{3}$ would accept 123 followed by a newline.
Why does re.search('\bcat\b', 'a cat') return None?
In a normal string, \b is a backspace character, so the pattern is 'backspace cat backspace'. Write the pattern as a raw string, r'\bcat\b', and it matches.
What does re.findall return for a pattern with two groups, and what do you use to get match objects instead?
A list of tuples, one tuple per match, holding just the groups. Use re.finditer to get match objects, from which you can call group(), span() and groupdict().
How do you avoid an AttributeError when a search might fail?
Check the result first: m = re.search(...); if m: use m.group(). The match object is truthy and None is falsy. In Python 3.8 and later you can write if (m := re.search(...)): in one line.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.