ZetCode

Python regular expressions

last modified November 18, 2026 Python 3.15

In this article we show how to use regular expressions in Python.

Regular expressions are used for text searching and more advanced text manipulation. They are built into tools such as grep and sed, text editors such as vi and Emacs, and programming languages such as Perl, JavaScript, and Python.

The re module

In Python, the re module provides regular expression matching operations.

A pattern is a regular expression that defines the text we are searching for or manipulating. It consists of literal characters and metacharacters. We can use the pattern directly with module-level functions such as re.search, or compile it first with re.compile and call the methods of the resulting Pattern object. The module caches recently used patterns, so compiling is mainly a matter of readability when a pattern is used many times.

The functions return a Match object on success and None otherwise; findall and finditer return all matches.

Raw strings

Regular expressions use the backslash for special sequences, and so do Python string literals. We write patterns as raw strings, prefixed with r, in which the backslash has no special meaning.

raw_strings.py
import re

print(len('\b'), len(r'\b'))

print(re.findall('\bfox\b', 'a fox and foxes'))
print(re.findall(r'\bfox\b', 'a fox and foxes'))

In a normal string, '\b' is a single backspace character, so the pattern looks for backspaces and finds nothing. In the raw string, r'\b' is a backslash followed by b, which the regex engine reads as a word boundary. Other sequences such as '\d' are invalid string escapes and produce a SyntaxWarning.

$ python raw_strings.py
1 2
[]
['fox']

Regular expression syntax

The following table shows the most common regular expression elements.

RegexMeaning
.Matches any character except a newline.
?Matches the preceding element once or not at all.
+Matches the preceding element once or more times.
*Matches the preceding element zero or more times.
{m,n}Matches the preceding element m to n times.
^Matches the start of the string (of a line with MULTILINE).
$Matches the end of the string or before a final newline.
\A, \zMatch only at the start and the very end of the string.
\bMatches a word boundary.
|Alternation operator.
[abc]Matches a, or b, or c.
[a-c]Range; matches a, or b, or c.
[^abc]Negation; matches any character except a, b, and c.
\dMatches a decimal digit.
\sMatches a whitespace character.
\wMatches a word character: a letter, digit, or underscore.
(...)A capturing group.
(?:...)A non-capturing group.

In str patterns, \d, \s, and \w match Unicode characters, not only ASCII; \w matches letters of any alphabet. The re.ASCII flag restricts them to ASCII.

The regex functions

The following table lists the main functions of the module. All of them are also available as methods of compiled patterns.

FunctionDescription
prefixmatch, matchDetermines if the pattern matches at the beginning of the string.
fullmatchDetermines if the pattern matches the whole string.
searchScans the string, looking for the first location where the pattern matches.
findallFinds all matches and returns them as a list of strings.
finditerFinds all matches and returns an iterator of match objects.
splitSplits the string by the occurrences of the pattern.
sub, subnReplace the occurrences of the pattern.

Python 3.15 added prefixmatch as a clearer name for match. The old name is soft deprecated: it keeps working and there are no plans to remove it, but new code should prefer prefixmatch.

The match function

The match function returns a match object if zero or more characters at the beginning of the string match the pattern.

match_fun.py
import re

words = ('book', 'bookworm', 'Bible',
         'bookish', 'cookbook', 'bookstore', 'pocketbook')

pattern = re.compile(r'book')

for word in words:
    if pattern.match(word):
        print(f'The {word} matches')

We compile the pattern and call its match method on each word. Only the words that start with book match; cookbook contains the pattern but does not start with it.

$ python match_fun.py
The book matches
The bookworm matches
The bookish matches
The bookstore matches

The prefixmatch function

The name match is often mistaken for a function that matches the whole string. Python 3.15 introduced prefixmatch, which makes the behaviour explicit.

prefixmatch_fun.py
import re

words = ('book', 'bookworm', 'cookbook')

for word in words:
    print(word, re.prefixmatch(r'book', word))

print(re.prefixmatch is re.match)

The re.prefixmatch function is the same function object as re.match, and compiled patterns have both methods as well. Code that must run on Python 3.14 and older keeps using match; the examples in the rest of this article use it too.

$ python prefixmatch_fun.py
book <re.Match object; span=(0, 4), match='book'>
bookworm <re.Match object; span=(0, 4), match='book'>
cookbook None
True

The fullmatch function

The fullmatch function returns a match object only if the whole string matches the pattern.

fullmatch_fun.py
import re

words = ('book', 'bookworm', 'Bible',
         'bookish', 'cookbook', 'bookstore', 'pocketbook')

pattern = re.compile(r'book')

for word in words:
    if pattern.fullmatch(word):
        print(f'The {word} matches')

Only the word book matches. fullmatch is the right choice for validating input, since the pattern does not need the ^ and $ anchors.

$ python fullmatch_fun.py
The book matches

The search function

The search function looks for the first location where the pattern matches, anywhere in the string.

search_fun.py
import re

words = ('book', 'bookworm', 'Bible',
         'bookish', 'cookbook', 'bookstore', 'pocketbook')

pattern = re.compile(r'book')

for word in words:
    if pattern.search(word):
        print(f'The {word} matches')

All words that contain book anywhere match.

$ python search_fun.py
The book matches
The bookworm matches
The bookish matches
The cookbook matches
The bookstore matches
The pocketbook matches

The match object

A successful match returns a Match object. It tells us what was matched and where.

match_object.py
import re

text = 'The order 4512 was shipped on 2026-11-18.'

if m := re.search(r'\d{4}-\d{2}-\d{2}', text):
    print(m)
    print(m.group())
    print(m.start(), m.end(), m.span())
    print(text[m.start():m.end()])

m = re.search(r'\d{5}', text)
print(m)

The walrus operator assigns the result and tests it in one step. The group method returns the matched text; start, end, and span return its position. A match object is always true, and a failed search returns None.

$ python match_object.py
<re.Match object; span=(30, 40), match='2026-11-18'>
2026-11-18
30 40 (30, 40)
2026-11-18
None

Dot metacharacter

The dot (.) metacharacter stands for any single character in the text, except the newline.

dot_meta.py
import re

words = ('seven', 'even', 'prevent', 'revenge', 'maven',
         'eleven', 'amen', 'event')

pattern = re.compile(r'.even')

for word in words:
    if pattern.match(word):
        print(f'The {word} matches')

We look for words that start with any character followed by even. The word even itself does not match, because the dot requires one character.

$ python dot_meta.py
The seven matches
The revenge matches

Question mark metacharacter

The question mark (?) metacharacter makes the preceding element optional; it matches it zero times or once.

question_mark_meta.py
import re

words = ('seven', 'even', 'prevent', 'revenge', 'maven',
         'eleven', 'amen', 'event')

pattern = re.compile(r'.?even')

for word in words:
    if pattern.match(word):
        print(f'The {word} matches')

With the optional character, even and event match as well.

$ python question_mark_meta.py
The seven matches
The even matches
The revenge matches
The event matches

Quantifiers

Quantifiers specify how many times the preceding element must occur.

quantifiers.py
import re

text = 'a ab abb abbb abbbb'

print(re.findall(r'ab*', text))
print(re.findall(r'ab+', text))
print(re.findall(r'ab{2}', text))
print(re.findall(r'ab{2,3}', text))
print(re.findall(r'\bab{2,}\b', text))

b* matches zero or more b characters, b+ one or more, b{2} exactly two, and b{2,3} two or three. Without word boundaries, ab{2} finds the first two b's in longer words too. {2,} has no upper limit.

$ python quantifiers.py
['a', 'ab', 'abb', 'abbb', 'abbbb']
['ab', 'abb', 'abbb', 'abbbb']
['abb', 'abb', 'abb']
['abb', 'abbb', 'abbb']
['abb', 'abbb', 'abbbb']

Greedy and lazy quantifiers

Quantifiers are greedy by default: they match as much text as possible. A question mark after a quantifier makes it lazy.

greedy_lazy.py
import re

html = '<p>The <b>fox</b> and the <i>dog</i>.</p>'

print(re.findall(r'<.+>', html))
print(re.findall(r'<.+?>', html))
print(re.findall(r'<[^>]+>', html))

The greedy .+ runs to the last > in the text, so the whole string is one match. The lazy .+? stops at the first >. A negated character class, [^>]+, gives the same result and is usually more efficient. For real HTML, we use an HTML parser instead of regular expressions.

$ python greedy_lazy.py
['<p>The <b>fox</b> and the <i>dog</i>.</p>']
['<p>', '<b>', '</b>', '<i>', '</i>', '</p>']
['<p>', '<b>', '</b>', '<i>', '</i>', '</p>']

Anchors

Anchors match positions rather than characters. The ^ anchor matches at the start of the text and $ at the end.

anchors.py
import re

sentences = ('I am looking for Jane.',
             'Jane was walking along the river.',
             'Kate and Jane are close friends.')

pattern = re.compile(r'^Jane')

for sentence in sentences:
    if pattern.search(sentence):
        print(sentence)

We look for sentences that start with Jane. Although search scans the whole string, the anchor allows only a match at its beginning.

$ python anchors.py
Jane was walking along the river.

Multiline mode and end of text

With the re.MULTILINE flag, ^ and $ match at the start and end of each line.

multiline.py
import re

text = '''title: Python regex
author: Jan
draft: no
'''

print(re.findall(r'^\w+', text))
print(re.findall(r'^\w+', text, re.MULTILINE))

print(re.search(r'no$', text))
print(re.search(r'no\z', text))
print(re.search(r'no\n\z', text))

Without the flag, only the first word of the text is found. The $ anchor matches before a final newline, so no$ matches although the text ends with \n.

print(re.search(r'no\z', text))

The \z anchor, added in Python 3.14, matches only at the very end of the string; older versions spell it \Z.

$ python multiline.py
['title']
['title', 'author', 'draft']
<re.Match object; span=(39, 41), match='no'>
None
<re.Match object; span=(39, 42), match='no\n'>

Word boundaries

The \b anchor matches at the boundary between a word character and a non-word character.

word_boundary.py
import re

words = ('book', 'bookworm', 'Bible',
         'bookish', 'cookbook', 'bookstore', 'pocketbook')

text = ' '.join(words)
print(re.findall(r'\bbook\w*', text))
print(re.findall(r'\w*book\b', text))
print(re.findall(r'\bbook\b', text))

We find the words that start with book, end with book, and the exact word book.

$ python word_boundary.py
['book', 'bookworm', 'bookish', 'bookstore']
['book', 'cookbook', 'pocketbook']
['book']

Character classes

A character class matches any single character from a set given in square brackets.

character_class.py
import re

words = ('a gray bird', 'grey hair', 'great look')

pattern = re.compile(r'gr[ea]y')

for word in words:
    if pattern.search(word):
        print(f'{word} matches')

print(re.findall(r'[A-Z][a-z]+', 'Jane and Peter met Lucy in Rome.'))
print(re.findall(r'[^aeiou\s]+', 'an old falcon'))

The gr[ea]y pattern matches both gray and grey. [A-Z][a-z]+ finds capitalized words. With the caret, [^aeiou\s]+ matches runs of characters that are neither vowels nor whitespace.

$ python character_class.py
a gray bird matches
grey hair matches
['Jane', 'Peter', 'Lucy', 'Rome']
['n', 'ld', 'f', 'lc', 'n']

Predefined character classes

The \d, \w, and \s sequences are shorthands for common classes; \D, \W, and \S are their negations.

named_classes.py
import re

text = 'We met in 2013. She is now about 27 years old.'

print(re.findall(r'\d+', text))
print(re.findall(r'\b\w{4}\b', text))
print(re.split(r'\s+', 'one  two\tthree\nfour'))
print(re.findall(r'\S+', 'one  two\tthree\nfour'))

We find all numbers, the four-letter words, and split the text on runs of whitespace characters (spaces, tabs, newlines).

$ python named_classes.py
['2013', '27']
['2013']
['one', 'two', 'three', 'four']
['one', 'two', 'three', 'four']

Unicode and ASCII

For str patterns, the predefined classes are Unicode-aware.

unicode_classes.py
import re

text = 'Žltý kôň 42 ٤٢ café'

print(re.findall(r'\w+', text))
print(re.findall(r'\w+', text, re.ASCII))
print(re.findall(r'\d+', text))
print(re.findall(r'[0-9]+', text))

\w matches Slovak letters with diacritics. \d matches any decimal digit, including Arabic-Indic digits. With the re.ASCII flag, only ASCII characters match. To accept only the digits 0–9, we use the explicit [0-9] class.

$ python unicode_classes.py
['Žltý', 'kôň', '42', '٤٢', 'café']
['lt', 'k', '42', 'caf']
['42', '٤٢']
['42']

Case-insensitive match

The re.IGNORECASE flag, or re.I, makes the match case-insensitive. Flags can also be written inline at the start of the pattern.

case_insensitive.py
import re

words = ('dog', 'Dog', 'DOG', 'Doggy')

pattern = re.compile(r'dog', re.IGNORECASE)

for word in words:
    if pattern.match(word):
        print(f'{word} matches')

print(re.findall(r'(?i)dog\b', ' '.join(words)))

All four words match the pattern. The (?i) inline flag has the same effect as passing re.I.

$ python case_insensitive.py
dog matches
Dog matches
DOG matches
Doggy matches
['dog', 'Dog', 'DOG']

Alternations

The alternation operator | creates a regular expression with several choices.

alternations.py
import re

words = ('Jane', 'Thomas', 'Robert',
         'Lucy', 'Beky', 'John', 'Peter', 'Andy')

pattern = re.compile(r'Jane|Beky|Robert')

for word in words:
    if pattern.fullmatch(word):
        print(word)

print(re.findall(r'J(?:ane|ohn)', 'Jane, John, Jack'))

We match three names exactly. The alternation has the lowest precedence, so to apply it to a part of the pattern, we put it in a group: J(?:ane|ohn) matches Jane or John.

$ python alternations.py
Jane
Robert
Beky
['Jane', 'John']

The findall function

The findall function returns all non-overlapping matches as a list of strings.

findall_fun.py
import re

text = 'I saw a fox in the wood. The fox had red fur. Foxes are smart.'

found = re.findall(r'fox', text, re.I)
print(found)
print(len(found))

We find all occurrences of fox, ignoring case.

$ python findall_fun.py
['fox', 'fox', 'Fox']
3

The finditer function

The finditer function returns an iterator of match objects. It gives us the positions of the matches and reads them lazily.

finditer_fun.py
import re

text = 'I saw a fox in the wood. The fox had red fur.'

pattern = re.compile(r'fox')

for m in pattern.finditer(text):
    s, e = m.span()
    print(f'Found {m.group()!r} at {s}:{e}')

We print each match with its position.

$ python finditer_fun.py
Found 'fox' at 8:11
Found 'fox' at 29:32

Capturing groups

Parentheses create capturing groups. They let us extract parts of the match.

capturing_groups.py
import re

text = 'John: 034-5551234, Lucy: 02-5559876'

m = re.search(r'(\w+): (\d+)-(\d+)', text)
print(m.group(0))
print(m.group(1), m.group(2), m.group(3))
print(m.groups())

print(re.findall(r'(\w+): (\d+)-(\d+)', text))
print(re.findall(r'(\w+): \d+-\d+', text))

Group 0 is the whole match; groups 1, 2, and 3 are the name, the area code, and the number. The groups method returns all groups as a tuple.

print(re.findall(r'(\w+): (\d+)-(\d+)', text))
print(re.findall(r'(\w+): \d+-\d+', text))

When the pattern has groups, findall returns the groups instead of whole matches: a list of tuples for several groups, a list of strings for one group.

$ python capturing_groups.py
John: 034-5551234
John 034 5551234
('John', '034', '5551234')
[('John', '034', '5551234'), ('Lucy', '02', '5559876')]
['John', 'Lucy']

Named groups

The (?P<name>...) syntax gives a group a name. Named groups make complex patterns easier to read.

named_groups.py
import re

log = '''2026-11-18 09:12:01 ERROR Disk full
2026-11-18 09:15:44 INFO Backup started
2026-11-18 09:16:02 WARNING Slow response'''

pattern = re.compile(r'(?P<date>\S+) (?P<time>\S+) (?P<level>[A-Z]+) (?P<msg>.*)')

for m in pattern.finditer(log):
    print(m['level'], '-', m['msg'])

m = pattern.match(log)
print(m.groupdict())

We parse log lines. A match object can be indexed by the group name, and groupdict returns all named groups as a dictionary.

$ python named_groups.py
ERROR - Disk full
INFO - Backup started
WARNING - Slow response
{'date': '2026-11-18', 'time': '09:12:01', 'level': 'ERROR', 'msg': 'Disk full'}

Backreferences

A backreference such as \1 matches the same text that was captured by a group earlier in the pattern.

backreferences.py
import re

text = 'This is is a test of the the regex module.'

for m in re.finditer(r'\b(\w+)\s+\1\b', text):
    print(f'repeated word {m[1]!r} at {m.start()}')

print(re.sub(r'\b(\w+)\s+\1\b', r'\1', text))

print(re.findall(r'''(['"])(.*?)\1''', '''He said "hi" and 'bye'.'''))

The \b(\w+)\s+\1\b pattern finds a word followed by the same word. With sub, we remove the duplicates. The last pattern finds text in matching quotes: the closing quote must be the same character as the opening one.

$ python backreferences.py
repeated word 'is' at 5
repeated word 'the' at 21
This is a test of the regex module.
[('"', 'hi'), ("'", 'bye')]

Lookahead and lookbehind

Lookaround assertions check what follows or precedes the current position without including it in the match. (?=...) and (?!...) are positive and negative lookaheads, (?<=...) and (?<!...) lookbehinds.

lookaround.py
import re

prices = 'Apples cost $12, pears 30 EUR, plums $7 and 9 kiwis.'

print(re.findall(r'(?<=\$)\d+', prices))
print(re.findall(r'\d+(?= EUR)', prices))
print(re.findall(r'\b(?<!\$)\d+\b(?! EUR)', prices))

def is_strong(password):
    return re.fullmatch(r'(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}', password) is not None

for pw in ('secret', 'Secret12', 'secret12', 'S3cretPassword'):
    print(pw, is_strong(pw))

We find amounts in dollars, amounts in euros, and numbers that are neither. The dollar sign and the currency are not part of the matches.

re.fullmatch(r'(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}', password)

Several lookaheads at the start of the pattern check independent conditions: the password must contain a lowercase letter, an uppercase letter, and a digit, and be at least eight characters long.

$ python lookaround.py
['12', '7']
['30']
['9']
secret False
Secret12 True
secret12 False
S3cretPassword True

Splitting text

The re.split function splits a string by the occurrences of a pattern. Unlike str.split, it can use several different separators.

split_fun.py
import re

data = 'apple, pear;plum  kiwi,orange'

print(re.split(r'[,;\s]+', data))
print(re.split(r'([,;\s]+)', data))
print(re.split(r'[,;\s]+', data, maxsplit=2))

We split by commas, semicolons, and whitespace. If the pattern contains a capturing group, the separators are included in the result. The maxsplit argument limits the number of splits.

$ python split_fun.py
['apple', 'pear', 'plum', 'kiwi', 'orange']
['apple', ', ', 'pear', ';', 'plum', '  ', 'kiwi', ',', 'orange']
['apple', 'pear', 'plum  kiwi,orange']

Substitution

The re.sub function replaces the matches of a pattern; the re.subn function also returns the number of replacements.

sub_fun.py
import re

text = 'Call 0905 123 456 or 0911-654-321.'

print(re.sub(r'\d', '#', text))
print(re.sub(r'(\d{4})[ -](\d{3})[ -](\d{3})', r'\1/\2\3', text))
print(re.subn(r'\d', '#', text)[1])

We mask all digits and then reformat two phone numbers using group references in the replacement. More examples of replacing are in the Python replace string article.

$ python sub_fun.py
Call #### ### ### or ####-###-###.
Call 0905/123456 or 0911/654321.
20

Verbose patterns

The re.VERBOSE flag, or re.X, ignores whitespace in the pattern and allows comments. Long patterns become much easier to read.

verbose.py
import re

pattern = re.compile(r'''
    (?P<year>\d{4})   # year
    -
    (?P<month>0[1-9]|1[0-2])   # month 01-12
    -
    (?P<day>0[1-9]|[12]\d|3[01])   # day 01-31
''', re.VERBOSE)

for date in ('2026-11-18', '2026-13-01', '2026-02-31'):
    m = pattern.fullmatch(date)
    print(date, m.groupdict() if m else 'invalid')

The pattern validates the format of a date. A regular expression checks only the format: 2026-02-31 passes although February has no 31st day. To validate real dates, we parse them with datetime.date.fromisoformat.

$ python verbose.py
2026-11-18 {'year': '2026', 'month': '11', 'day': '18'}
2026-13-01 invalid
2026-02-31 {'year': '2026', 'month': '02', 'day': '31'}

Escaping special characters

To match metacharacters literally, we escape them with a backslash. The re.escape function escapes all special characters in a string, which is necessary when a pattern is built from user input.

escape_fun.py
import re

text = 'Prices: 1+1=2, (a+b)*c, 3.14'

term = '(a+b)*c'

print(re.escape(term))
print(re.search(re.escape(term), text))

print(re.search(term, text))

print(re.findall(r'\d\.\d+', text))
print(re.findall(r'\d.\d+', text))

The unescaped (a+b)*c is a valid pattern with a different meaning: zero or more repetitions of a group followed by c. It silently matches the c in Prices. Likewise, an unescaped dot matches any character, so \d.\d+ also finds 1+1.

$ python escape_fun.py
\(a\+b\)\*c
<re.Match object; span=(15, 22), match='(a+b)*c'>
<re.Match object; span=(3, 4), match='c'>
['3.14']
['1+1', '3.14']

Email example

In the following example, we check the format of email addresses.

emails.py
import re

emails = ('luke@gmail.com', 'andy@yahoocom',
          '34234sdfa#2345', 'f344@gmail.com', 'jane.doe@mail.example.co.uk')

pattern = re.compile(r'[\w.+-]+@[\w-]+(\.[\w-]+)*\.[a-zA-Z]{2,}')

for email in emails:
    if pattern.fullmatch(email):
        print(f'{email} matches')
    else:
        print(f'{email} does not match')

The local part consists of word characters, dots, plus signs, and hyphens. After the at sign come one or more domain labels separated by dots and a top-level domain of at least two letters. The pattern is a reasonable sanity check; the full email address syntax is far more complex, and the only reliable validation is to send a message to the address.

$ python emails.py
luke@gmail.com matches
andy@yahoocom does not match
34234sdfa#2345 does not match
f344@gmail.com matches
jane.doe@mail.example.co.uk matches

Invalid patterns

An invalid pattern raises re.error. Its attributes tell what is wrong and where.

regex_error.py
import re

patterns = [r'(\d+', r'[a-', r'a{3,1}', r'\q']

for p in patterns:
    try:
        re.compile(p)
    except re.error as e:
        print(f'{p!r}: {e.msg} at position {e.pos}')

The msg attribute holds the error message without the position, and pos is the index in the pattern where the error was found.

$ python regex_error.py
'(\\d+': missing ), unterminated subpattern at position 0
'[a-': unterminated character set at position 0
'a{3,1}': min repeat greater than max repeat at position 2
'\\q': bad escape \q at position 0

Source

re – Regular expression operations

Regular expression HOWTO

In this article we have worked with regular expressions in Python. See also Python replace string, Python split string, Python string, and Python f-string.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.