Unicode HOWTO

Unicode HOWTO¶
- Release:
1.12
This HOWTO discusses Python’s support for the Unicode specification for representing textual data, and explains various problems that people commonly encounter when trying to work with Unicode.
Introduction to Unicode¶
Definitions¶
Today’s programs need to be able to handle a wide variety of characters. Applications are often internationalized to display messages and output in a variety of user-selectable languages; the same program might need to output an error message in English, French, Japanese, Hebrew, or Russian. Web content can be written in any of these languages and can also include a variety of emoji symbols. Python’s string type uses the Unicode Standard for representing characters, which lets Python programs work with all these different possible characters.
Unicode (https://www.unicode.org/) is a specification that aims to list every character used by human languages and give each character its own unique code. The Unicode specifications are continually revised and updated to add new languages and symbols.
A character is the smallest possible component of a text. ‘A’, ‘B’, ‘C’, etc., are all different characters. So are ‘È’ and ‘Í’. Characters vary depending on the language or context you’re talking about. For example, there’s a character for “Roman Numeral One”, ‘Ⅰ’, that’s separate from the uppercase letter ‘I’. They’ll usually look the same, but these are two different characters that have different meanings.
The Unicode standard describes how characters are represented by
code points. A code point value is an integer in the range 0 to
0x10FFFF (about 1.1 million values, the
actual number assigned
is less than that). In the standard and in this document, a code point is written
using the notation U+265E
to mean the character with value
0x265e
(9,822 in decimal).
The Unicode standard contains a lot of tables listing characters and their corresponding code points:
0061 'a'; LATIN SMALL LETTER A
0062 'b'; LATIN SMALL LETTER B
0063 'c'; LATIN SMALL LETTER C
...
007B '{'; LEFT CURLY BRACKET
...
2167 'Ⅷ'; ROMAN NUMERAL EIGHT
2168 'Ⅸ'; ROMAN NUMERAL NINE
...
265E '♞'; BLACK CHESS KNIGHT
265F '♟'; BLACK CHESS PAWN
...
1F600 '😀'; GRINNING FACE
1F609 '😉'; WINKING FACE
...
Strictly, these definitions imply that it’s meaningless to say ‘this is
character U+265E
’. U+265E
is a code point, which represents some particular
character; in this case, it represents the character ‘BLACK CHESS KNIGHT’,
‘♞’. In
informal contexts, this distinction between code points and characters will
sometimes be forgotten.
A character is represented on a screen or on paper by a set of graphical elements that’s called a glyph. The glyph for an uppercase A, for example, is two diagonal strokes and a horizontal stroke, though the exact details will depend on the font being used. Most Python code doesn’t need to worry about glyphs; figuring out the correct glyph to display is generally the job of a GUI toolkit or a terminal’s font renderer.
Encodings¶
To summarize the previous section: a Unicode string is a sequence of
code points, which are numbers from 0 through 0x10FFFF
(1,114,111
decimal). This sequence of code points needs to be represented in
memory as a set of code units, and code units are then mapped
to 8-bit bytes. The rules for translating a Unicode string into a
sequence of bytes are called a character encoding, or just
an encoding.
The first encoding you might think of is using 32-bit integers as the code unit, and then using the CPU’s representation of 32-bit integers. In this representation, the string “Python” might look like this:
P y t h o n
0x50 00 00 00 79 00 00 00 74 00 00 00 68 00 00 00 6f 00 00 00 6e 00 00 00
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
This representation is straightforward but using it presents a number of problems.
It’s not portable; different processors order the bytes differently.
It’s very wasteful of space. In most texts, the majority of the code points are less than 127, or less than 255, so a lot of space is occupied by
0x00
bytes. The above string takes 24 bytes compared to the 6 bytes needed for an ASCII representation. Increased RAM usage doesn’t matter too much (desktop computers have gigabytes of RAM, and strings aren’t usually that large), but expanding our usage of disk and network bandwidth by a factor of 4 is intolerable.It’s not compatible with existing C functions such as
strlen()
, so a new family of wide string functions would need to be used.
Therefore this encoding isn’t used very much, and people instead choose other encodings that are more efficient and convenient, such as UTF-8.
UTF-8 is one of the most commonly used encodings, and Python often defaults to using it. UTF stands for “Unicode Transformation Format”, and the ‘8’ means that 8-bit values are used in the encoding. (There are also UTF-16 and UTF-32 encodings, but they are less frequently used than UTF-8.) UTF-8 uses the following rules:
If the code point is < 128, it’s represented by the corresponding byte value.
If the code point is >= 128, it’s turned into a sequence of two, three, or four bytes, where each byte of the sequence is between 128 and 255.
UTF-8 has several convenient properties:
It can handle any Unicode code point.
A Unicode string is turned into a sequence of bytes that contains embedded zero bytes only where they represent the null character (U+0000). This means that UTF-8 strings can be processed by C functions such as
strcpy()
and sent through protocols that can’t handle zero bytes for anything other than end-of-string markers.A string of ASCII text is also valid UTF-8 text.
UTF-8 is fairly compact; the majority of commonly used characters can be represented with one or two bytes.
If bytes are corrupted or lost, it’s possible to determine the start of the next UTF-8-encoded code point and resynchronize. It’s also unlikely that random 8-bit data will look like valid UTF-8.
UTF-8 is a byte oriented encoding. The encoding specifies that each character is represented by a specific sequence of one or more bytes. This avoids the byte-ordering issues that can occur with integer and word oriented encodings, like UTF-16 and UTF-32, where the sequence of bytes varies depending on the hardware on which the string was encoded.
References¶
The Unicode Consortium site has character charts, a glossary, and PDF versions of the Unicode specification. Be prepared for some difficult reading. A chronology of the origin and development of Unicode is also available on the site.
On the Computerphile Youtube channel, Tom Scott briefly discusses the history of Unicode and UTF-8 (9 minutes 36 seconds).
To help understand the standard, Jukka Korpela has written an introductory guide to reading the Unicode character tables.
Another good introductory article was written by Joel Spolsky. If this introduction didn’t make things clear to you, you should try reading this alternate article before continuing.
Wikipedia entries are often helpful; see the entries for “character encoding” and UTF-8, for example.
Python’s Unicode Support¶
Now that you’ve learned the rudiments of Unicode, we can look at Python’s Unicode features.
The String Type¶
Since Python 3.0, the language’s str
type contains Unicode
characters, meaning any string created using "unicode rocks!"
, 'unicode
rocks!'
, or the triple-quoted string syntax is stored as Unicode.
The default encoding for Python source code is UTF-8, so you can simply include a Unicode character in a string literal:
try:
with open('/tmp/input.txt', 'r') as f:
...
except OSError:
# 'File not found' error message.
print("Fichier non trouvé")
Side note: Python 3 also supports using Unicode characters in identifiers:
répertoire = "/tmp/records.log"
with open(répertoire, "w") as f:
f.write("test\n")
If you can’t enter a particular character in your editor or want to keep the source code ASCII-only for some reason, you can also use escape sequences in string literals. (Depending on your system, you may see the actual capital-delta glyph instead of a u escape.)
>>> "\N{GREEK CAPITAL LETTER DELTA}" # Using the character name
'\u0394'
>>> "\u0394" # Using a 16-bit hex value
'\u0394'
>>> "\U00000394" # Using a 32-bit hex value
'\u0394'
In addition, one can create a string using the decode()
method of
bytes
. This method takes an encoding argument, such as UTF-8
,
and optionally an errors argument.
The errors argument specifies the response when the input string can’t be
converted according to the encoding’s rules. Legal values for this argument are
'strict'
(raise a UnicodeDecodeError
exception), 'replace'
(use
U+FFFD
, REPLACEMENT CHARACTER
), 'ignore'
(just leave the
character out of the Unicode result), or 'backslashreplace'
(inserts a
\xNN
escape sequence).
The following examples show the differences:
>>> b'\x80abc'.decode("utf-8", "strict")
Traceback (most recent call last):
...
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0:
invalid start byte
>>> b'\x80abc'.decode("utf-8", "replace")
'\ufffdabc'
>>> b'\x80abc'.decode("utf-8", "backslashreplace")
'\\x80abc'
>>> b'\x80abc'.decode("utf-8", "ignore")
'abc'
Encodings are specified as strings containing the encoding’s name. Python
comes with roughly 100 different encodings; see the Python Library Reference at
Standard Encodings for a list. Some encodings have multiple names; for
example, 'latin-1'
, 'iso_8859_1'
and '8859
’ are all synonyms for
the same encoding.
One-character Unicode strings can also be created with the chr()
built-in function, which takes integers and returns a Unicode string of length 1
that contains the corresponding code point. The reverse operation is the
built-in ord()
function that takes a one-character Unicode string and
returns the code point value:
>>> chr(57344)
'\ue000'
>>> ord('\ue000')
57344
Converting to Bytes¶
The opposite method of bytes.decode()
is str.encode()
,
which returns a bytes
representation of the Unicode string, encoded in the
requested encoding.
The errors parameter is the same as the parameter of the
decode()
method but supports a few more possible handlers. As well as
'strict'
, 'ignore'
, and 'replace'
(which in this case
inserts a question mark instead of the unencodable character), there is
also 'xmlcharrefreplace'
(inserts an XML character reference),
backslashreplace
(inserts a \uNNNN
escape sequence) and
namereplace
(inserts a \N{...}
escape sequence).
The following example shows the different results:
>>> u = chr(40960) + 'abcd' + chr(1972)
>>> u.encode('utf-8')
b'\xea\x80\x80abcd\xde\xb4'
>>> u.encode('ascii')
Traceback (most recent call last):
...
UnicodeEncodeError: 'ascii' codec can't encode character '\ua000' in
position 0: ordinal not in range(128)
>>> u.encode('ascii', 'ignore')
b'abcd'
>>> u.encode('ascii', 'replace')
b'?abcd?'
>>> u.encode('ascii', 'xmlcharrefreplace')
b'ꀀabcd޴'
>>> u.encode('ascii', 'backslashreplace')
b'\\ua000abcd\\u07b4'
>>> u.encode('ascii', 'namereplace')
b'\\N{YI SYLLABLE IT}abcd\\u07b4'
The low-level routines for registering and accessing the available
encodings are found in the codecs
module. Implementing new
encodings also requires understanding the codecs
module.
However, the encoding and decoding functions returned by this module
are usually more low-level than is comfortable, and writing new encodings
is a specialized task, so the module won’t be covered in this HOWTO.
Unicode Literals in Python Source Code¶
In Python source code, specific Unicode code points can be written using the
\u
escape sequence, which is followed by four hex digits giving the code
point. The \U
escape sequence is similar, but expects eight hex digits,
not four:
>>> s = "a\xac\u1234\u20ac\U00008000"
... # ^^^^ two-digit hex escape
... # ^^^^^^ four-digit Unicode escape
... # ^^^^^^^^^^ eight-digit Unicode escape
>>> [ord(c) for c in s]
[97, 172, 4660, 8364, 32768]
Using escape sequences for code points greater than 127 is fine in small doses,
but becomes an annoyance if you’re using many accented characters, as you would
in a program with messages in French or some other accent-using language. You
can also assemble strings using the chr()
built-in function, but this is
even more tedious.
Ideally, you’d want to be able to write literals in your language’s natural encoding. You could then edit Python source code with your favorite editor which would display the accented characters naturally, and have the right characters used at runtime.
Python supports writing source code in UTF-8 by default, but you can use almost any encoding if you declare the encoding being used. This is done by including a special comment as either the first or second line of the source file:
#!/usr/bin/env python
# -*- coding: latin-1 -*-
u = 'abcdé'
print(ord(u[-1]))
The syntax is inspired by Emacs’s notation for specifying variables local to a
file. Emacs supports many different variables, but Python only supports
‘coding’. The -*-
symbols indicate to Emacs that the comment is special;
they have no significance to Python but are a convention. Python looks for
coding: name
or coding=name
in the comment.
If you don’t include such a comment, the default encoding used will be UTF-8 as already mentioned. See also PEP 263 for more information.
Unicode Properties¶
The Unicode specification includes a database of information about code points. For each defined code point, the information includes the character’s name, its category, the numeric value if applicable (for characters representing numeric concepts such as the Roman numerals, fractions such as one-third and four-fifths, etc.). There are also display-related properties, such as how to use the code point in bidirectional text.
The following program displays some information about several characters, and prints the numeric value of one particular character:
import unicodedata
u = chr(233) + chr(0x0bf2) + chr(3972) + chr(6000) + chr(13231)
for i, c in enumerate(u):
print(i, '%04x' % ord(c), unicodedata.category(c), end=" ")
print(unicodedata.name(c))
# Get numeric value of second character
print(unicodedata.numeric(u[1]))
When run, this prints:
0 00e9 Ll LATIN SMALL LETTER E WITH ACUTE
1 0bf2 No TAMIL NUMBER ONE THOUSAND
2 0f84 Mn TIBETAN MARK HALANTA
3 1770 Lo TAGBANWA LETTER SA
4 33af So SQUARE RAD OVER S SQUARED
1000.0
The category codes are abbreviations describing the nature of the character.
These are grouped into categories such as “Letter”, “Number”, “Punctuation”, or
“Symbol”, which in turn are broken up into subcategories. To take the codes
from the above output, 'Ll'
means ‘Letter, lowercase’, 'No'
means
“Number, other”, 'Mn'
is “Mark, nonspacing”, and 'So'
is “Symbol,
other”. See
the General Category Values section of the Unicode Character Database documentation for a
list of category codes.
Comparing Strings¶
Unicode adds some complication to comparing strings, because the same set of characters can be represented by different sequences of code points. For example, a letter like ‘ê’ can be represented as a single code point U+00EA, or as U+0065 U+0302, which is the code point for ‘e’ followed by a code point for ‘COMBINING CIRCUMFLEX ACCENT’. These will produce the same output when printed, but one is a string of length 1 and the other is of length 2.
One tool for a case-insensitive comparison is the
casefold()
string method that converts a string to a
case-insensitive form following an algorithm described by the Unicode
Standard. This algorithm has special handling for characters such as
the German letter ‘ß’ (code point U+00DF), which becomes the pair of
lowercase letters ‘ss’.
>>> street = 'Gürzenichstraße'
>>> street.casefold()
'gürzenichstrasse'
A second tool is the unicodedata
module’s
normalize()
function that converts strings to one
of several normal forms, where letters followed by a combining character are
replaced with single characters. normalize()
can
be used to perform string comparisons that won’t falsely report
inequality if two strings use combining characters differently:
import unicodedata
def compare_strs(s1, s2):
def NFD(s):
return unicodedata.normalize('NFD', s)
return NFD(s1) == NFD(s2)
single_char = 'ê'
multiple_chars = '\N{LATIN SMALL LETTER E}\N{COMBINING CIRCUMFLEX ACCENT}'
print('length of first string=', len(single_char))
print('length of second string=', len(multiple_chars))
print(compare_strs(single_char, multiple_chars))
When run, this outputs:
$ python compare-strs.py
length of first string= 1
length of second string= 2
True
The first argument to the normalize()
function is a
string giving the desired normalization form, which can be one of
‘NFC’, ‘NFKC’, ‘NFD’, and ‘NFKD’.
The Unicode Standard also specifies how to do caseless comparisons:
import unicodedata
def compare_caseless(s1, s2):
def NFD(s):
return unicodedata.normalize('NFD', s)
return NFD(NFD(s1).casefold()) == NFD(NFD(s2).casefold())
# Example usage
single_char = 'ê'
multiple_chars = '\N{LATIN CAPITAL LETTER E}\N{COMBINING CIRCUMFLEX ACCENT}'
print(compare_caseless(single_char, multiple_chars))
This will print True
. (Why is NFD()
invoked twice? Because
there are a few characters that make casefold()
return a
non-normalized string, so the result needs to be normalized again. See
section 3.13 of the Unicode Standard for a discussion and an example.)
Unicode Regular Expressions¶
The regular expressions supported by the re
module can be provided
either as bytes or strings. Some of the special character sequences such as
\d
and \w
have different meanings depending on whether
the pattern is supplied as bytes or a string. For example,
\d
will match the characters [0-9]
in bytes but
in strings will match any character that’s in the 'Nd'
category.
The string in this example has the number 57 written in both Thai and Arabic numerals:
import re
p = re.compile(r'\d+')
s = "Over \u0e55\u0e57 57 flavours"
m = p.search(s)
print(repr(m.group()))
When executed, \d+
will match the Thai numerals and print them
out. If you supply the re.ASCII
flag to
compile()
, \d+
will match the substring “57” instead.
Similarly, \w
matches a wide variety of Unicode characters but
only [a-zA-Z0-9_]
in bytes or if re.ASCII
is supplied,
and \s
will match either Unicode whitespace characters or
[ \t\n\r\f\v]
.
References¶
Some good alternative discussions of Python’s Unicode support are:
Processing Text Files in Python 3, by Nick Coghlan.
Pragmatic Unicode, a PyCon 2012 presentation by Ned Batchelder.
The str
type is described in the Python library reference at
Text Sequence Type — str.
The documentation for the unicodedata
module.
The documentation for the codecs
module.
Marc-André Lemburg gave a presentation titled “Python and Unicode” (PDF slides) at
EuroPython 2002. The slides are an excellent overview of the design of Python
2’s Unicode features (where the Unicode string type is called unicode
and
literals start with u
).
Reading and Writing Unicode Data¶
Once you’ve written some code that works with Unicode data, the next problem is input/output. How do you get Unicode strings into your program, and how do you convert Unicode into a form suitable for storage or transmission?
It’s possible that you may not need to do anything depending on your input sources and output destinations; you should check whether the libraries used in your application support Unicode natively. XML parsers often return Unicode data, for example. Many relational databases also support Unicode-valued columns and can return Unicode values from an SQL query.
Unicode data is usually converted to a particular encoding before it gets
written to disk or sent over a socket. It’s possible to do all the work
yourself: open a file, read an 8-bit bytes object from it, and convert the bytes
with bytes.decode(encoding)
. However, the manual approach is not recommended.
One problem is the multi-byte nature of encodings; one Unicode character can be represented by several bytes. If you want to read the file in arbitrary-sized chunks (say, 1024 or 4096 bytes), you need to write error-handling code to catch the case where only part of the bytes encoding a single Unicode character are read at the end of a chunk. One solution would be to read the entire file into memory and then perform the decoding, but that prevents you from working with files that are extremely large; if you need to read a 2 GiB file, you need 2 GiB of RAM. (More, really, since for at least a moment you’d need to have both the encoded string and its Unicode version in memory.)
The solution would be to use the low-level decoding interface to catch the case
of partial coding sequences. The work of implementing this has already been
done for you: the built-in open()
function can return a file-like object
that assumes the file’s contents are in a specified encoding and accepts Unicode
parameters for methods such as read()
and
write()
. This works through open()
's encoding and
errors parameters which are interpreted just like those in str.encode()
and bytes.decode()
.
Reading Unicode from a file is therefore simple:
with open('unicode.txt', encoding='utf-8') as f:
for line in f:
print(repr(line))
It’s also possible to open files in update mode, allowing both reading and writing:
with open('test', encoding='utf-8', mode='w+') as f:
f.write('\u4500 blah blah blah\n')
f.seek(0)
print(repr(f.readline()[:1]))
The Unicode character U+FEFF
is used as a byte-order mark (BOM), and is often
written as the first character of a file in order to assist with autodetection
of the file’s byte ordering. Some encodings, such as UTF-16, expect a BOM to be
present at the start of a file; when such an encoding is used, the BOM will be
automatically written as the first character and will be silently dropped when
the file is read. There are variants of these encodings, such as ‘utf-16-le’
and ‘utf-16-be’ for little-endian and big-endian encodings, that specify one
particular byte ordering and don’t skip the BOM.
In some areas, it is also convention to use a “BOM” at the start of UTF-8 encoded files; the name is misleading since UTF-8 is not byte-order dependent. The mark simply announces that the file is encoded in UTF-8. For reading such files, use the ‘utf-8-sig’ codec to automatically skip the mark if present.
Unicode filenames¶
Most of the operating systems in common use today support filenames
that contain arbitrary Unicode characters. Usually this is
implemented by converting the Unicode string into some encoding that
varies depending on the system. Today Python is converging on using
UTF-8: Python on MacOS has used UTF-8 for several versions, and Python
3.6 switched to using UTF-8 on Windows as well. On Unix systems,
there will only be a filesystem encoding. if you’ve set the LANG
or LC_CTYPE
environment variables; if
you haven’t, the default encoding is again UTF-8.
The sys.getfilesystemencoding()
function returns the encoding to use on
your current system, in case you want to do the encoding manually, but there’s
not much reason to bother. When opening a file for reading or writing, you can
usually just provide the Unicode string as the filename, and it will be
automatically converted to the right encoding for you:
filename = 'filename\u4500abc'
with open(filename, 'w') as f:
f.write('blah\n')
Functions in the os
module such as os.stat()
will also accept Unicode
filenames.
The os.listdir()
function returns filenames, which raises an issue: should it return
the Unicode version of filenames, or should it return bytes containing
the encoded versions? os.listdir()
can do both, depending on whether you
provided the directory path as bytes or a Unicode string. If you pass a
Unicode string as the path, filenames will be decoded using the filesystem’s
encoding and a list of Unicode strings will be returned, while passing a byte
path will return the filenames as bytes. For example,
assuming the default filesystem encoding is UTF-8, running the following program:
fn = 'filename\u4500abc'
f = open(fn, 'w')
f.close()
import os
print(os.listdir(b'.'))
print(os.listdir('.'))
will produce the following output:
$ python listdir-test.py
[b'filename\xe4\x94\x80abc', ...]
['filename\u4500abc', ...]
The first list contains UTF-8-encoded filenames, and the second list contains the Unicode versions.
Note that on most occasions, you should can just stick with using Unicode with these APIs. The bytes APIs should only be used on systems where undecodable file names can be present; that’s pretty much only Unix systems now.
Tips for Writing Unicode-aware Programs¶
This section provides some suggestions on writing software that deals with Unicode.
The most important tip is:
Software should only work with Unicode strings internally, decoding the input data as soon as possible and encoding the output only at the end.
If you attempt to write processing functions that accept both Unicode and byte
strings, you will find your program vulnerable to bugs wherever you combine the
two different kinds of strings. There is no automatic encoding or decoding: if
you do e.g. str + bytes
, a TypeError
will be raised.
When using data coming from a web browser or some other untrusted source, a common technique is to check for illegal characters in a string before using the string in a generated command line or storing it in a database. If you’re doing this, be careful to check the decoded string, not the encoded bytes data; some encodings may have interesting properties, such as not being bijective or not being fully ASCII-compatible. This is especially true if the input data also specifies the encoding, since the attacker can then choose a clever way to hide malicious text in the encoded bytestream.
Converting Between File Encodings¶
The StreamRecoder
class can transparently convert between
encodings, taking a stream that returns data in encoding #1
and behaving like a stream returning data in encoding #2.
For example, if you have an input file f that’s in Latin-1, you
can wrap it with a StreamRecoder
to return bytes encoded in
UTF-8:
new_f = codecs.StreamRecoder(f,
# en/decoder: used by read() to encode its results and
# by write() to decode its input.
codecs.getencoder('utf-8'), codecs.getdecoder('utf-8'),
# reader/writer: used to read and write to the stream.
codecs.getreader('latin-1'), codecs.getwriter('latin-1') )
Files in an Unknown Encoding¶
What can you do if you need to make a change to a file, but don’t know
the file’s encoding? If you know the encoding is ASCII-compatible and
only want to examine or modify the ASCII parts, you can open the file
with the surrogateescape
error handler:
with open(fname, 'r', encoding="ascii", errors="surrogateescape") as f:
data = f.read()
# make changes to the string 'data'
with open(fname + '.new', 'w',
encoding="ascii", errors="surrogateescape") as f:
f.write(data)
The surrogateescape
error handler will decode any non-ASCII bytes
as code points in a special range running from U+DC80 to
U+DCFF. These code points will then turn back into the
same bytes when the surrogateescape
error handler is used to
encode the data and write it back out.
References¶
One section of Mastering Python 3 Input/Output, a PyCon 2010 talk by David Beazley, discusses text processing and binary data handling.
The PDF slides for Marc-André Lemburg’s presentation “Writing Unicode-aware Applications in Python” discuss questions of character encodings as well as how to internationalize and localize an application. These slides cover Python 2.x only.
The Guts of Unicode in Python is a PyCon 2013 talk by Benjamin Peterson that discusses the internal Unicode representation in Python 3.3.
Acknowledgements¶
The initial draft of this document was written by Andrew Kuchling. It has since been revised further by Alexander Belopolsky, Georg Brandl, Andrew Kuchling, and Ezio Melotti.
Thanks to the following people who have noted errors or offered suggestions on this article: Éric Araujo, Nicholas Bastin, Nick Coghlan, Marius Gedminas, Kent Johnson, Ken Krugler, Marc-André Lemburg, Martin von Löwis, Terry J. Reedy, Serhiy Storchaka, Eryk Sun, Chad Whitacre, Graham Wideman.


Regular Expression HOWTO

Regular Expression HOWTO¶
- Author:
A.M. Kuchling <amk@amk.ca>
Introduction¶
Regular expressions (called REs, or regexes, or regex patterns) are essentially
a tiny, highly specialized programming language embedded inside Python and made
available through the re
module. Using this little language, you specify
the rules for the set of possible strings that you want to match; this set might
contain English sentences, or e-mail addresses, or TeX commands, or anything you
like. You can then ask questions such as “Does this string match the pattern?”,
or “Is there a match for the pattern anywhere in this string?”. You can also
use REs to modify a string or to split it apart in various ways.
Regular expression patterns are compiled into a series of bytecodes which are then executed by a matching engine written in C. For advanced use, it may be necessary to pay careful attention to how the engine will execute a given RE, and write the RE in a certain way in order to produce bytecode that runs faster. Optimization isn’t covered in this document, because it requires that you have a good understanding of the matching engine’s internals.
The regular expression language is relatively small and restricted, so not all possible string processing tasks can be done using regular expressions. There are also tasks that can be done with regular expressions, but the expressions turn out to be very complicated. In these cases, you may be better off writing Python code to do the processing; while Python code will be slower than an elaborate regular expression, it will also probably be more understandable.
Simple Patterns¶
We’ll start by learning about the simplest possible regular expressions. Since regular expressions are used to operate on strings, we’ll begin with the most common task: matching characters.
For a detailed explanation of the computer science underlying regular expressions (deterministic and non-deterministic finite automata), you can refer to almost any textbook on writing compilers.
Matching Characters¶
Most letters and characters will simply match themselves. For example, the
regular expression test
will match the string test
exactly. (You can
enable a case-insensitive mode that would let this RE match Test
or TEST
as well; more about this later.)
There are exceptions to this rule; some characters are special metacharacters, and don’t match themselves. Instead, they signal that some out-of-the-ordinary thing should be matched, or they affect other portions of the RE by repeating them or changing their meaning. Much of this document is devoted to discussing various metacharacters and what they do.
Here’s a complete list of the metacharacters; their meanings will be discussed in the rest of this HOWTO.
. ^ $ * + ? { } [ ] \ | ( )
The first metacharacters we’ll look at are [
and ]
. They’re used for
specifying a character class, which is a set of characters that you wish to
match. Characters can be listed individually, or a range of characters can be
indicated by giving two characters and separating them by a '-'
. For
example, [abc]
will match any of the characters a
, b
, or c
; this
is the same as [a-c]
, which uses a range to express the same set of
characters. If you wanted to match only lowercase letters, your RE would be
[a-z]
.
Metacharacters (except \
) are not active inside classes. For example, [akm$]
will
match any of the characters 'a'
, 'k'
, 'm'
, or '$'
; '$'
is
usually a metacharacter, but inside a character class it’s stripped of its
special nature.
You can match the characters not listed within the class by complementing
the set. This is indicated by including a '^'
as the first character of the
class. For example, [^5]
will match any character except '5'
. If the
caret appears elsewhere in a character class, it does not have special meaning.
For example: [5^]
will match either a '5'
or a '^'
.
Perhaps the most important metacharacter is the backslash, \
. As in Python
string literals, the backslash can be followed by various characters to signal
various special sequences. It’s also used to escape all the metacharacters so
you can still match them in patterns; for example, if you need to match a [
or \
, you can precede them with a backslash to remove their special
meaning: \[
or \\
.
Some of the special sequences beginning with '\'
represent
predefined sets of characters that are often useful, such as the set
of digits, the set of letters, or the set of anything that isn’t
whitespace.
Let’s take an example: \w
matches any alphanumeric character. If
the regex pattern is expressed in bytes, this is equivalent to the
class [a-zA-Z0-9_]
. If the regex pattern is a string, \w
will
match all the characters marked as letters in the Unicode database
provided by the unicodedata
module. You can use the more
restricted definition of \w
in a string pattern by supplying the
re.ASCII
flag when compiling the regular expression.
The following list of special sequences isn’t complete. For a complete list of sequences and expanded class definitions for Unicode string patterns, see the last part of Regular Expression Syntax in the Standard Library reference. In general, the Unicode versions match any character that’s in the appropriate category in the Unicode database.
\d
Matches any decimal digit; this is equivalent to the class
[0-9]
.\D
Matches any non-digit character; this is equivalent to the class
[^0-9]
.\s
Matches any whitespace character; this is equivalent to the class
[ \t\n\r\f\v]
.\S
Matches any non-whitespace character; this is equivalent to the class
[^ \t\n\r\f\v]
.\w
Matches any alphanumeric character; this is equivalent to the class
[a-zA-Z0-9_]
.\W
Matches any non-alphanumeric character; this is equivalent to the class
[^a-zA-Z0-9_]
.
These sequences can be included inside a character class. For example,
[\s,.]
is a character class that will match any whitespace character, or
','
or '.'
.
The final metacharacter in this section is .
. It matches anything except a
newline character, and there’s an alternate mode (re.DOTALL
) where it will
match even a newline. .
is often used where you want to match “any
character”.
Repeating Things¶
Being able to match varying sets of characters is the first thing regular expressions can do that isn’t already possible with the methods available on strings. However, if that was the only additional capability of regexes, they wouldn’t be much of an advance. Another capability is that you can specify that portions of the RE must be repeated a certain number of times.
The first metacharacter for repeating things that we’ll look at is *
. *
doesn’t match the literal character '*'
; instead, it specifies that the
previous character can be matched zero or more times, instead of exactly once.
For example, ca*t
will match 'ct'
(0 'a'
characters), 'cat'
(1 'a'
),
'caaat'
(3 'a'
characters), and so forth.
Repetitions such as *
are greedy; when repeating a RE, the matching
engine will try to repeat it as many times as possible. If later portions of the
pattern don’t match, the matching engine will then back up and try again with
fewer repetitions.
A step-by-step example will make this more obvious. Let’s consider the
expression a[bcd]*b
. This matches the letter 'a'
, zero or more letters
from the class [bcd]
, and finally ends with a 'b'
. Now imagine matching
this RE against the string 'abcbd'
.
Step |
Matched |
Explanation |
|---|---|---|
1 |
|
The |
2 |
|
The engine matches |
3 |
Failure |
The engine tries to match
|
4 |
|
Back up, so that |
5 |
Failure |
Try |
6 |
|
Back up again, so that
|
6 |
|
Try |
The end of the RE has now been reached, and it has matched 'abcb'
. This
demonstrates how the matching engine goes as far as it can at first, and if no
match is found it will then progressively back up and retry the rest of the RE
again and again. It will back up until it has tried zero matches for
[bcd]*
, and if that subsequently fails, the engine will conclude that the
string doesn’t match the RE at all.
Another repeating metacharacter is +
, which matches one or more times. Pay
careful attention to the difference between *
and +
; *
matches
zero or more times, so whatever’s being repeated may not be present at all,
while +
requires at least one occurrence. To use a similar example,
ca+t
will match 'cat'
(1 'a'
), 'caaat'
(3 'a'
s), but won’t
match 'ct'
.
There are two more repeating operators or quantifiers. The question mark character, ?
,
matches either once or zero times; you can think of it as marking something as
being optional. For example, home-?brew
matches either 'homebrew'
or
'home-brew'
.
The most complicated quantifier is {m,n}
, where m and n are
decimal integers. This quantifier means there must be at least m repetitions,
and at most n. For example, a/{1,3}b
will match 'a/b'
, 'a//b'
, and
'a///b'
. It won’t match 'ab'
, which has no slashes, or 'a////b'
, which
has four.
You can omit either m or n; in that case, a reasonable value is assumed for the missing value. Omitting m is interpreted as a lower limit of 0, while omitting n results in an upper bound of infinity.
The simplest case {m}
matches the preceding item exactly m times.
For example, a/{2}b
will only match 'a//b'
.
Readers of a reductionist bent may notice that the three other quantifiers can
all be expressed using this notation. {0,}
is the same as *
, {1,}
is equivalent to +
, and {0,1}
is the same as ?
. It’s better to use
*
, +
, or ?
when you can, simply because they’re shorter and easier
to read.
Using Regular Expressions¶
Now that we’ve looked at some simple regular expressions, how do we actually use
them in Python? The re
module provides an interface to the regular
expression engine, allowing you to compile REs into objects and then perform
matches with them.
Compiling Regular Expressions¶
Regular expressions are compiled into pattern objects, which have methods for various operations such as searching for pattern matches or performing string substitutions.
>>> import re
>>> p = re.compile('ab*')
>>> p
re.compile('ab*')
re.compile()
also accepts an optional flags argument, used to enable
various special features and syntax variations. We’ll go over the available
settings later, but for now a single example will do:
>>> p = re.compile('ab*', re.IGNORECASE)
The RE is passed to re.compile()
as a string. REs are handled as strings
because regular expressions aren’t part of the core Python language, and no
special syntax was created for expressing them. (There are applications that
don’t need REs at all, so there’s no need to bloat the language specification by
including them.) Instead, the re
module is simply a C extension module
included with Python, just like the socket
or zlib
modules.
Putting REs in strings keeps the Python language simpler, but has one disadvantage which is the topic of the next section.
The Backslash Plague¶
As stated earlier, regular expressions use the backslash character ('\'
) to
indicate special forms or to allow special characters to be used without
invoking their special meaning. This conflicts with Python’s usage of the same
character for the same purpose in string literals.
Let’s say you want to write a RE that matches the string \section
, which
might be found in a LaTeX file. To figure out what to write in the program
code, start with the desired string to be matched. Next, you must escape any
backslashes and other metacharacters by preceding them with a backslash,
resulting in the string \\section
. The resulting string that must be passed
to re.compile()
must be \\section
. However, to express this as a
Python string literal, both backslashes must be escaped again.
Characters |
Stage |
|---|---|
|
Text string to be matched |
|
Escaped backslash for |
|
Escaped backslashes for a string literal |
In short, to match a literal backslash, one has to write '\\\\'
as the RE
string, because the regular expression must be \\
, and each backslash must
be expressed as \\
inside a regular Python string literal. In REs that
feature backslashes repeatedly, this leads to lots of repeated backslashes and
makes the resulting strings difficult to understand.
The solution is to use Python’s raw string notation for regular expressions;
backslashes are not handled in any special way in a string literal prefixed with
'r'
, so r"\n"
is a two-character string containing '\'
and 'n'
,
while "\n"
is a one-character string containing a newline. Regular
expressions will often be written in Python code using this raw string notation.
In addition, special escape sequences that are valid in regular expressions,
but not valid as Python string literals, now result in a
DeprecationWarning
and will eventually become a SyntaxError
,
which means the sequences will be invalid if raw string notation or escaping
the backslashes isn’t used.
Regular String |
Raw string |
|---|---|
|
|
|
|
|
|
Performing Matches¶
Once you have an object representing a compiled regular expression, what do you
do with it? Pattern objects have several methods and attributes.
Only the most significant ones will be covered here; consult the re
docs
for a complete listing.
Method/Attribute |
Purpose |
|---|---|
|
Determine if the RE matches at the beginning of the string. |
|
Scan through a string, looking for any location where this RE matches. |
|
Find all substrings where the RE matches, and returns them as a list. |
|
Find all substrings where the RE matches, and returns them as an iterator. |
match()
and search()
return None
if no match can be found. If
they’re successful, a match object instance is returned,
containing information about the match: where it starts and ends, the substring
it matched, and more.
You can learn about this by interactively experimenting with the re
module.
This HOWTO uses the standard Python interpreter for its examples. First, run the
Python interpreter, import the re
module, and compile a RE:
>>> import re
>>> p = re.compile('[a-z]+')
>>> p
re.compile('[a-z]+')
Now, you can try matching various strings against the RE [a-z]+
. An empty
string shouldn’t match at all, since +
means ‘one or more repetitions’.
match()
should return None
in this case, which will cause the
interpreter to print no output. You can explicitly print the result of
match()
to make this clear.
>>> p.match("")
>>> print(p.match(""))
None
Now, let’s try it on a string that it should match, such as tempo
. In this
case, match()
will return a match object, so you
should store the result in a variable for later use.
>>> m = p.match('tempo')
>>> m
<re.Match object; span=(0, 5), match='tempo'>
Now you can query the match object for information about the matching string. Match object instances also have several methods and attributes; the most important ones are:
Method/Attribute |
Purpose |
|---|---|
|
Return the string matched by the RE |
|
Return the starting position of the match |
|
Return the ending position of the match |
|
Return a tuple containing the (start, end) positions of the match |
Trying these methods will soon clarify their meaning:
>>> m.group()
'tempo'
>>> m.start(), m.end()
(0, 5)
>>> m.span()
(0, 5)
group()
returns the substring that was matched by the RE. start()
and end()
return the starting and ending index of the match. span()
returns both start and end indexes in a single tuple. Since the match()
method only checks if the RE matches at the start of a string, start()
will always be zero. However, the search()
method of patterns
scans through the string, so the match may not start at zero in that
case.
>>> print(p.match('::: message'))
None
>>> m = p.search('::: message'); print(m)
<re.Match object; span=(4, 11), match='message'>
>>> m.group()
'message'
>>> m.span()
(4, 11)
In actual programs, the most common style is to store the
match object in a variable, and then check if it was
None
. This usually looks like:
p = re.compile( ... )
m = p.match( 'string goes here' )
if m:
print('Match found: ', m.group())
else:
print('No match')
Two pattern methods return all of the matches for a pattern.
findall()
returns a list of matching strings:
>>> p = re.compile(r'\d+')
>>> p.findall('12 drummers drumming, 11 pipers piping, 10 lords a-leaping')
['12', '11', '10']
The r
prefix, making the literal a raw string literal, is needed in this
example because escape sequences in a normal “cooked” string literal that are
not recognized by Python, as opposed to regular expressions, now result in a
DeprecationWarning
and will eventually become a SyntaxError
. See
The Backslash Plague.
findall()
has to create the entire list before it can be returned as the
result. The finditer()
method returns a sequence of
match object instances as an iterator:
>>> iterator = p.finditer('12 drummers drumming, 11 ... 10 ...')
>>> iterator
<callable_iterator object at 0x...>
>>> for match in iterator:
... print(match.span())
...
(0, 2)
(22, 24)
(29, 31)
Module-Level Functions¶
You don’t have to create a pattern object and call its methods; the
re
module also provides top-level functions called match()
,
search()
, findall()
, sub()
, and so forth. These functions
take the same arguments as the corresponding pattern method with
the RE string added as the first argument, and still return either None
or a
match object instance.
>>> print(re.match(r'From\s+', 'Fromage amk'))
None
>>> re.match(r'From\s+', 'From amk Thu May 14 19:12:10 1998')
<re.Match object; span=(0, 5), match='From '>
Under the hood, these functions simply create a pattern object for you and call the appropriate method on it. They also store the compiled object in a cache, so future calls using the same RE won’t need to parse the pattern again and again.
Should you use these module-level functions, or should you get the pattern and call its methods yourself? If you’re accessing a regex within a loop, pre-compiling it will save a few function calls. Outside of loops, there’s not much difference thanks to the internal cache.
Compilation Flags¶
Compilation flags let you modify some aspects of how regular expressions work.
Flags are available in the re
module under two names, a long name such as
IGNORECASE
and a short, one-letter form such as I
. (If you’re
familiar with Perl’s pattern modifiers, the one-letter forms use the same
letters; the short form of re.VERBOSE
is re.X
, for example.)
Multiple flags can be specified by bitwise OR-ing them; re.I | re.M
sets
both the I
and M
flags, for example.
Here’s a table of the available flags, followed by a more detailed explanation of each one.
Flag |
Meaning |
|---|---|
Makes several escapes like |
|
Make |
|
Do case-insensitive matches. |
|
Do a locale-aware match. |
|
Multi-line matching, affecting |
|
Enable verbose REs, which can be organized more cleanly and understandably. |
- re.I
- re.IGNORECASE
Perform case-insensitive matching; character class and literal strings will match letters by ignoring case. For example,
[A-Z]
will match lowercase letters, too. Full Unicode matching also works unless theASCII
flag is used to disable non-ASCII matches. When the Unicode patterns[a-z]
or[A-Z]
are used in combination with theIGNORECASE
flag, they will match the 52 ASCII letters and 4 additional non-ASCII letters: ‘İ’ (U+0130, Latin capital letter I with dot above), ‘ı’ (U+0131, Latin small letter dotless i), ‘ſ’ (U+017F, Latin small letter long s) and ‘K’ (U+212A, Kelvin sign).Spam
will match'Spam'
,'spam'
,'spAM'
, or'ſpam'
(the latter is matched only in Unicode mode). This lowercasing doesn’t take the current locale into account; it will if you also set theLOCALE
flag.
- re.L
- re.LOCALE
Make
\w
,\W
,\b
,\B
and case-insensitive matching dependent on the current locale instead of the Unicode database.Locales are a feature of the C library intended to help in writing programs that take account of language differences. For example, if you’re processing encoded French text, you’d want to be able to write
\w+
to match words, but\w
only matches the character class[A-Za-z]
in bytes patterns; it won’t match bytes corresponding toé
orç
. If your system is configured properly and a French locale is selected, certain C functions will tell the program that the byte corresponding toé
should also be considered a letter. Setting theLOCALE
flag when compiling a regular expression will cause the resulting compiled object to use these C functions for\w
; this is slower, but also enables\w+
to match French words as you’d expect. The use of this flag is discouraged in Python 3 as the locale mechanism is very unreliable, it only handles one “culture” at a time, and it only works with 8-bit locales. Unicode matching is already enabled by default in Python 3 for Unicode (str) patterns, and it is able to handle different locales/languages.
- re.M
- re.MULTILINE
(
^
and$
haven’t been explained yet; they’ll be introduced in section More Metacharacters.)Usually
^
matches only at the beginning of the string, and$
matches only at the end of the string and immediately before the newline (if any) at the end of the string. When this flag is specified,^
matches at the beginning of the string and at the beginning of each line within the string, immediately following each newline. Similarly, the$
metacharacter matches either at the end of the string and at the end of each line (immediately preceding each newline).
- re.S
- re.DOTALL
Makes the
'.'
special character match any character at all, including a newline; without this flag,'.'
will match anything except a newline.
- re.A
- re.ASCII
Make
\w
,\W
,\b
,\B
,\s
and\S
perform ASCII-only matching instead of full Unicode matching. This is only meaningful for Unicode patterns, and is ignored for byte patterns.
- re.X
- re.VERBOSE
This flag allows you to write regular expressions that are more readable by granting you more flexibility in how you can format them. When this flag has been specified, whitespace within the RE string is ignored, except when the whitespace is in a character class or preceded by an unescaped backslash; this lets you organize and indent the RE more clearly. This flag also lets you put comments within a RE that will be ignored by the engine; comments are marked by a
'#'
that’s neither in a character class or preceded by an unescaped backslash.For example, here’s a RE that uses
re.VERBOSE
; see how much easier it is to read?charref = re.compile(r""" &[#] # Start of a numeric entity reference ( 0[0-7]+ # Octal form | [0-9]+ # Decimal form | x[0-9a-fA-F]+ # Hexadecimal form ) ; # Trailing semicolon """, re.VERBOSE)
Without the verbose setting, the RE would look like this:
charref = re.compile("&#(0[0-7]+" "|[0-9]+" "|x[0-9a-fA-F]+);")
In the above example, Python’s automatic concatenation of string literals has been used to break up the RE into smaller pieces, but it’s still more difficult to understand than the version using
re.VERBOSE
.
More Pattern Power¶
So far we’ve only covered a part of the features of regular expressions. In this section, we’ll cover some new metacharacters, and how to use groups to retrieve portions of the text that was matched.
More Metacharacters¶
There are some metacharacters that we haven’t covered yet. Most of them will be covered in this section.
Some of the remaining metacharacters to be discussed are zero-width
assertions. They don’t cause the engine to advance through the string;
instead, they consume no characters at all, and simply succeed or fail. For
example, \b
is an assertion that the current position is located at a word
boundary; the position isn’t changed by the \b
at all. This means that
zero-width assertions should never be repeated, because if they match once at a
given location, they can obviously be matched an infinite number of times.
|
Alternation, or the “or” operator. If A and B are regular expressions,
A|B
will match any string that matches either A or B.|
has very low precedence in order to make it work reasonably when you’re alternating multi-character strings.Crow|Servo
will match either'Crow'
or'Servo'
, not'Cro'
, a'w'
or an'S'
, and'ervo'
.To match a literal
'|'
, use\|
, or enclose it inside a character class, as in[|]
.^
Matches at the beginning of lines. Unless the
MULTILINE
flag has been set, this will only match at the beginning of the string. InMULTILINE
mode, this also matches immediately after each newline within the string.For example, if you wish to match the word
From
only at the beginning of a line, the RE to use is^From
.>>> print(re.search('^From', 'From Here to Eternity')) <re.Match object; span=(0, 4), match='From'> >>> print(re.search('^From', 'Reciting From Memory')) None
To match a literal
'^'
, use\^
.$
Matches at the end of a line, which is defined as either the end of the string, or any location followed by a newline character.
>>> print(re.search('}$', '{block}')) <re.Match object; span=(6, 7), match='}'> >>> print(re.search('}$', '{block} ')) None >>> print(re.search('}$', '{block}\n')) <re.Match object; span=(6, 7), match='}'>
To match a literal
'$'
, use\$
or enclose it inside a character class, as in[$]
.\A
Matches only at the start of the string. When not in
MULTILINE
mode,\A
and^
are effectively the same. InMULTILINE
mode, they’re different:\A
still matches only at the beginning of the string, but^
may match at any location inside the string that follows a newline character.\z
Matches only at the end of the string.
\Z
The same as
\z
. For compatibility with old Python versions.\b
Word boundary. This is a zero-width assertion that matches only at the beginning or end of a word. A word is defined as a sequence of alphanumeric characters, so the end of a word is indicated by whitespace or a non-alphanumeric character.
The following example matches
class
only when it’s a complete word; it won’t match when it’s contained inside another word.>>> p = re.compile(r'\bclass\b') >>> print(p.search('no class at all')) <re.Match object; span=(3, 8), match='class'> >>> print(p.search('the declassified algorithm')) None >>> print(p.search('one subclass is')) None
There are two subtleties you should remember when using this special sequence. First, this is the worst collision between Python’s string literals and regular expression sequences. In Python’s string literals,
\b
is the backspace character, ASCII value 8. If you’re not using raw strings, then Python will convert the\b
to a backspace, and your RE won’t match as you expect it to. The following example looks the same as our previous RE, but omits the'r'
in front of the RE string.>>> p = re.compile('\bclass\b') >>> print(p.search('no class at all')) None >>> print(p.search('\b' + 'class' + '\b')) <re.Match object; span=(0, 7), match='\x08class\x08'>
Second, inside a character class, where there’s no use for this assertion,
\b
represents the backspace character, for compatibility with Python’s string literals.\B
Another zero-width assertion, this is the opposite of
\b
, only matching when the current position is not at a word boundary.
Grouping¶
Frequently you need to obtain more information than just whether the RE matched
or not. Regular expressions are often used to dissect strings by writing a RE
divided into several subgroups which match different components of interest.
For example, an RFC-822 header line is divided into a header name and a value,
separated by a ':'
, like this:
From: author@example.com
User-Agent: Thunderbird 1.5.0.9 (X11/20061227)
MIME-Version: 1.0
To: editor@example.com
This can be handled by writing a regular expression which matches an entire header line, and has one group which matches the header name, and another group which matches the header’s value.
Groups are marked by the '('
, ')'
metacharacters. '('
and ')'
have much the same meaning as they do in mathematical expressions; they group
together the expressions contained inside them, and you can repeat the contents
of a group with a quantifier, such as *
, +
, ?
, or
{m,n}
. For example, (ab)*
will match zero or more repetitions of
ab
.
>>> p = re.compile('(ab)*')
>>> print(p.match('ababababab').span())
(0, 10)
Groups indicated with '('
, ')'
also capture the starting and ending
index of the text that they match; this can be retrieved by passing an argument
to group()
, start()
, end()
, and
span()
. Groups are
numbered starting with 0. Group 0 is always present; it’s the whole RE, so
match object methods all have group 0 as their default
argument. Later we’ll see how to express groups that don’t capture the span
of text that they match.
>>> p = re.compile('(a)b')
>>> m = p.match('ab')
>>> m.group()
'ab'
>>> m.group(0)
'ab'
Subgroups are numbered from left to right, from 1 upward. Groups can be nested; to determine the number, just count the opening parenthesis characters, going from left to right.
>>> p = re.compile('(a(b)c)d')
>>> m = p.match('abcd')
>>> m.group(0)
'abcd'
>>> m.group(1)
'abc'
>>> m.group(2)
'b'
group()
can be passed multiple group numbers at a time, in which case it
will return a tuple containing the corresponding values for those groups.
>>> m.group(2,1,2)
('b', 'abc', 'b')
The groups()
method returns a tuple containing the strings for all the
subgroups, from 1 up to however many there are.
>>> m.groups()
('abc', 'b')
Backreferences in a pattern allow you to specify that the contents of an earlier
capturing group must also be found at the current location in the string. For
example, \1
will succeed if the exact contents of group 1 can be found at
the current position, and fails otherwise. Remember that Python’s string
literals also use a backslash followed by numbers to allow including arbitrary
characters in a string, so be sure to use a raw string when incorporating
backreferences in a RE.
For example, the following RE detects doubled words in a string.
>>> p = re.compile(r'\b(\w+)\s+\1\b')
>>> p.search('Paris in the the spring').group()
'the the'
Backreferences like this aren’t often useful for just searching through a string — there are few text formats which repeat data in this way — but you’ll soon find out that they’re very useful when performing string substitutions.
Non-capturing and Named Groups¶
Elaborate REs may use many groups, both to capture substrings of interest, and to group and structure the RE itself. In complex REs, it becomes difficult to keep track of the group numbers. There are two features which help with this problem. Both of them use a common syntax for regular expression extensions, so we’ll look at that first.
Perl 5 is well known for its powerful additions to standard regular expressions.
For these new features the Perl developers couldn’t choose new single-keystroke metacharacters
or new special sequences beginning with \
without making Perl’s regular
expressions confusingly different from standard REs. If they chose &
as a
new metacharacter, for example, old expressions would be assuming that &
was
a regular character and wouldn’t have escaped it by writing \&
or [&]
.
The solution chosen by the Perl developers was to use (?...)
as the
extension syntax. ?
immediately after a parenthesis was a syntax error
because the ?
would have nothing to repeat, so this didn’t introduce any
compatibility problems. The characters immediately after the ?
indicate
what extension is being used, so (?=foo)
is one thing (a positive lookahead
assertion) and (?:foo)
is something else (a non-capturing group containing
the subexpression foo
).
Python supports several of Perl’s extensions and adds an extension
syntax to Perl’s extension syntax. If the first character after the
question mark is a P
, you know that it’s an extension that’s
specific to Python.
Now that we’ve looked at the general extension syntax, we can return to the features that simplify working with groups in complex REs.
Sometimes you’ll want to use a group to denote a part of a regular expression,
but aren’t interested in retrieving the group’s contents. You can make this fact
explicit by using a non-capturing group: (?:...)
, where you can replace the
...
with any other regular expression.
>>> m = re.match("([abc])+", "abc")
>>> m.groups()
('c',)
>>> m = re.match("(?:[abc])+", "abc")
>>> m.groups()
()
Except for the fact that you can’t retrieve the contents of what the group
matched, a non-capturing group behaves exactly the same as a capturing group;
you can put anything inside it, repeat it with a repetition metacharacter such
as *
, and nest it within other groups (capturing or non-capturing).
(?:...)
is particularly useful when modifying an existing pattern, since you
can add new groups without changing how all the other groups are numbered. It
should be mentioned that there’s no performance difference in searching between
capturing and non-capturing groups; neither form is any faster than the other.
A more significant feature is named groups: instead of referring to them by numbers, groups can be referenced by a name.
The syntax for a named group is one of the Python-specific extensions:
(?P<name>...)
. name is, obviously, the name of the group. Named groups
behave exactly like capturing groups, and additionally associate a name
with a group. The match object methods that deal with
capturing groups all accept either integers that refer to the group by number
or strings that contain the desired group’s name. Named groups are still
given numbers, so you can retrieve information about a group in two ways:
>>> p = re.compile(r'(?P<word>\b\w+\b)')
>>> m = p.search( '(((( Lots of punctuation )))' )
>>> m.group('word')
'Lots'
>>> m.group(1)
'Lots'
Additionally, you can retrieve named groups as a dictionary with
groupdict()
:
>>> m = re.match(r'(?P<first>\w+) (?P<last>\w+)', 'Jane Doe')
>>> m.groupdict()
{'first': 'Jane', 'last': 'Doe'}
Named groups are handy because they let you use easily remembered names, instead
of having to remember numbers. Here’s an example RE from the imaplib
module:
InternalDate = re.compile(r'INTERNALDATE "'
r'(?P<day>[ 123][0-9])-(?P<mon>[A-Z][a-z][a-z])-'
r'(?P<year>[0-9][0-9][0-9][0-9])'
r' (?P<hour>[0-9][0-9]):(?P<min>[0-9][0-9]):(?P<sec>[0-9][0-9])'
r' (?P<zonen>[-+])(?P<zoneh>[0-9][0-9])(?P<zonem>[0-9][0-9])'
r'"')
It’s obviously much easier to retrieve m.group('zonem')
, instead of having
to remember to retrieve group 9.
The syntax for backreferences in an expression such as (...)\1
refers to the
number of the group. There’s naturally a variant that uses the group name
instead of the number. This is another Python extension: (?P=name)
indicates
that the contents of the group called name should again be matched at the
current point. The regular expression for finding doubled words,
\b(\w+)\s+\1\b
can also be written as \b(?P<word>\w+)\s+(?P=word)\b
:
>>> p = re.compile(r'\b(?P<word>\w+)\s+(?P=word)\b')
>>> p.search('Paris in the the spring').group()
'the the'
Lookahead Assertions¶
Another zero-width assertion is the lookahead assertion. Lookahead assertions are available in both positive and negative form, and look like this:
(?=...)
Positive lookahead assertion. This succeeds if the contained regular expression, represented here by
...
, successfully matches at the current location, and fails otherwise. But, once the contained expression has been tried, the matching engine doesn’t advance at all; the rest of the pattern is tried right where the assertion started.(?!...)
Negative lookahead assertion. This is the opposite of the positive assertion; it succeeds if the contained expression doesn’t match at the current position in the string.
To make this concrete, let’s look at a case where a lookahead is useful.
Consider a simple pattern to match a filename and split it apart into a base
name and an extension, separated by a .
. For example, in news.rc
,
news
is the base name, and rc
is the filename’s extension.
The pattern to match this is quite simple:
.*[.].*$
Notice that the .
needs to be treated specially because it’s a
metacharacter, so it’s inside a character class to only match that
specific character. Also notice the trailing $
; this is added to
ensure that all the rest of the string must be included in the
extension. This regular expression matches foo.bar
and
autoexec.bat
and sendmail.cf
and printers.conf
.
Now, consider complicating the problem a bit; what if you want to match
filenames where the extension is not bat
? Some incorrect attempts:
.*[.][^b].*$
The first attempt above tries to exclude bat
by requiring
that the first character of the extension is not a b
. This is wrong,
because the pattern also doesn’t match foo.bar
.
.*[.]([^b]..|.[^a].|..[^t])$
The expression gets messier when you try to patch up the first solution by
requiring one of the following cases to match: the first character of the
extension isn’t b
; the second character isn’t a
; or the third character
isn’t t
. This accepts foo.bar
and rejects autoexec.bat
, but it
requires a three-letter extension and won’t accept a filename with a two-letter
extension such as sendmail.cf
. We’ll complicate the pattern again in an
effort to fix it.
.*[.]([^b].?.?|.[^a]?.?|..?[^t]?)$
In the third attempt, the second and third letters are all made optional in
order to allow matching extensions shorter than three characters, such as
sendmail.cf
.
The pattern’s getting really complicated now, which makes it hard to read and
understand. Worse, if the problem changes and you want to exclude both bat
and exe
as extensions, the pattern would get even more complicated and
confusing.
A negative lookahead cuts through all this confusion:
.*[.](?!bat$)[^.]*$
The negative lookahead means: if the expression bat
doesn’t match at this point, try the rest of the pattern; if bat$
does
match, the whole pattern will fail. The trailing $
is required to ensure
that something like sample.batch
, where the extension only starts with
bat
, will be allowed. The [^.]*
makes sure that the pattern works
when there are multiple dots in the filename.
Excluding another filename extension is now easy; simply add it as an
alternative inside the assertion. The following pattern excludes filenames that
end in either bat
or exe
:
.*[.](?!bat$|exe$)[^.]*$
Modifying Strings¶
Up to this point, we’ve simply performed searches against a static string. Regular expressions are also commonly used to modify strings in various ways, using the following pattern methods:
Method/Attribute |
Purpose |
|---|---|
|
Split the string into a list, splitting it wherever the RE matches |
|
Find all substrings where the RE matches, and replace them with a different string |
|
Does the same thing as |
Splitting Strings¶
The split()
method of a pattern splits a string apart
wherever the RE matches, returning a list of the pieces. It’s similar to the
split()
method of strings but provides much more generality in the
delimiters that you can split by; string split()
only supports splitting by
whitespace or by a fixed string. As you’d expect, there’s a module-level
re.split()
function, too.
- .split(string[, maxsplit=0])
Split string by the matches of the regular expression. If capturing parentheses are used in the RE, then their contents will also be returned as part of the resulting list. If maxsplit is nonzero, at most maxsplit splits are performed.
You can limit the number of splits made, by passing a value for maxsplit. When maxsplit is nonzero, at most maxsplit splits will be made, and the remainder of the string is returned as the final element of the list. In the following example, the delimiter is any sequence of non-alphanumeric characters.
>>> p = re.compile(r'\W+')
>>> p.split('This is a test, short and sweet, of split().')
['This', 'is', 'a', 'test', 'short', 'and', 'sweet', 'of', 'split', '']
>>> p.split('This is a test, short and sweet, of split().', 3)
['This', 'is', 'a', 'test, short and sweet, of split().']
Sometimes you’re not only interested in what the text between delimiters is, but also need to know what the delimiter was. If capturing parentheses are used in the RE, then their values are also returned as part of the list. Compare the following calls:
>>> p = re.compile(r'\W+')
>>> p2 = re.compile(r'(\W+)')
>>> p.split('This... is a test.')
['This', 'is', 'a', 'test', '']
>>> p2.split('This... is a test.')
['This', '... ', 'is', ' ', 'a', ' ', 'test', '.', '']
The module-level function re.split()
adds the RE to be used as the first
argument, but is otherwise the same.
>>> re.split(r'[\W]+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split(r'([\W]+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split(r'[\W]+', 'Words, words, words.', 1)
['Words', 'words, words.']
Search and Replace¶
Another common task is to find all the matches for a pattern, and replace them
with a different string. The sub()
method takes a replacement value,
which can be either a string or a function, and the string to be processed.
- .sub(replacement, string[, count=0])
Returns the string obtained by replacing the leftmost non-overlapping occurrences of the RE in string by the replacement replacement. If the pattern isn’t found, string is returned unchanged.
The optional argument count is the maximum number of pattern occurrences to be replaced; count must be a non-negative integer. The default value of 0 means to replace all occurrences.
Here’s a simple example of using the sub()
method. It replaces colour
names with the word colour
:
>>> p = re.compile('(blue|white|red)')
>>> p.sub('colour', 'blue socks and red shoes')
'colour socks and colour shoes'
>>> p.sub('colour', 'blue socks and red shoes', count=1)
'colour socks and red shoes'
The subn()
method does the same work, but returns a 2-tuple containing the
new string value and the number of replacements that were performed:
>>> p = re.compile('(blue|white|red)')
>>> p.subn('colour', 'blue socks and red shoes')
('colour socks and colour shoes', 2)
>>> p.subn('colour', 'no colours at all')
('no colours at all', 0)
Empty matches are replaced only when they’re not adjacent to a previous empty match.
>>> p = re.compile('x*')
>>> p.sub('-', 'abxd')
'-a-b--d-'
If replacement is a string, any backslash escapes in it are processed. That
is, \n
is converted to a single newline character, \r
is converted to a
carriage return, and so forth. Unknown escapes such as \&
are left alone.
Backreferences, such as \6
, are replaced with the substring matched by the
corresponding group in the RE. This lets you incorporate portions of the
original text in the resulting replacement string.
This example matches the word section
followed by a string enclosed in
{
, }
, and changes section
to subsection
:
>>> p = re.compile('section{ ( [^}]* ) }', re.VERBOSE)
>>> p.sub(r'subsection{\1}','section{First} section{second}')
'subsection{First} subsection{second}'
There’s also a syntax for referring to named groups as defined by the
(?P<name>...)
syntax. \g<name>
will use the substring matched by the
group named name
, and \g<number>
uses the corresponding group number.
\g<2>
is therefore equivalent to \2
, but isn’t ambiguous in a
replacement string such as \g<2>0
. (\20
would be interpreted as a
reference to group 20, not a reference to group 2 followed by the literal
character '0'
.) The following substitutions are all equivalent, but use all
three variations of the replacement string.
>>> p = re.compile('section{ (?P<name> [^}]* ) }', re.VERBOSE)
>>> p.sub(r'subsection{\1}','section{First}')
'subsection{First}'
>>> p.sub(r'subsection{\g<1>}','section{First}')
'subsection{First}'
>>> p.sub(r'subsection{\g<name>}','section{First}')
'subsection{First}'
replacement can also be a function, which gives you even more control. If replacement is a function, the function is called for every non-overlapping occurrence of pattern. On each call, the function is passed a match object argument for the match and can use this information to compute the desired replacement string and return it.
In the following example, the replacement function translates decimals into hexadecimal:
>>> def hexrepl(match):
... "Return the hex string for a decimal number"
... value = int(match.group())
... return hex(value)
...
>>> p = re.compile(r'\d+')
>>> p.sub(hexrepl, 'Call 65490 for printing, 49152 for user code.')
'Call 0xffd2 for printing, 0xc000 for user code.'
When using the module-level re.sub()
function, the pattern is passed as
the first argument. The pattern may be provided as an object or as a string; if
you need to specify regular expression flags, you must either use a
pattern object as the first parameter, or use embedded modifiers in the
pattern string, e.g. sub("(?i)b+", "x", "bbbb BBBB")
returns 'x x'
.
Common Problems¶
Regular expressions are a powerful tool for some applications, but in some ways their behaviour isn’t intuitive and at times they don’t behave the way you may expect them to. This section will point out some of the most common pitfalls.
Use String Methods¶
Sometimes using the re
module is a mistake. If you’re matching a fixed
string, or a single character class, and you’re not using any re
features
such as the IGNORECASE
flag, then the full power of regular expressions
may not be required. Strings have several methods for performing operations with
fixed strings and they’re usually much faster, because the implementation is a
single small C loop that’s been optimized for the purpose, instead of the large,
more generalized regular expression engine.
One example might be replacing a single fixed string with another one; for
example, you might replace word
with deed
. re.sub()
seems like the
function to use for this, but consider the replace()
method. Note that
replace()
will also replace word
inside words, turning swordfish
into sdeedfish
, but the naive RE word
would have done that, too. (To
avoid performing the substitution on parts of words, the pattern would have to
be \bword\b
, in order to require that word
have a word boundary on
either side. This takes the job beyond replace()
’s abilities.)
Another common task is deleting every occurrence of a single character from a
string or replacing it with another single character. You might do this with
something like re.sub('\n', ' ', S)
, but translate()
is capable of
doing both tasks and will be faster than any regular expression operation can
be.
In short, before turning to the re
module, consider whether your problem
can be solved with a faster and simpler string method.
match() versus search()¶
The match()
function only checks if the RE matches at the beginning of the
string while search()
will scan forward through the string for a match.
It’s important to keep this distinction in mind. Remember, match()
will
only report a successful match which will start at 0; if the match wouldn’t
start at zero, match()
will not report it.
>>> print(re.match('super', 'superstition').span())
(0, 5)
>>> print(re.match('super', 'insuperable'))
None
On the other hand, search()
will scan forward through the string,
reporting the first match it finds.
>>> print(re.search('super', 'superstition').span())
(0, 5)
>>> print(re.search('super', 'insuperable').span())
(2, 7)
Sometimes you’ll be tempted to keep using re.match()
, and just add .*
to the front of your RE. Resist this temptation and use re.search()
instead. The regular expression compiler does some analysis of REs in order to
speed up the process of looking for a match. One such analysis figures out what
the first character of a match must be; for example, a pattern starting with
Crow
must match starting with a 'C'
. The analysis lets the engine
quickly scan through the string looking for the starting character, only trying
the full match if a 'C'
is found.
Adding .*
defeats this optimization, requiring scanning to the end of the
string and then backtracking to find a match for the rest of the RE. Use
re.search()
instead.
Greedy versus Non-Greedy¶
When repeating a regular expression, as in a*
, the resulting action is to
consume as much of the pattern as possible. This fact often bites you when
you’re trying to match a pair of balanced delimiters, such as the angle brackets
surrounding an HTML tag. The naive pattern for matching a single HTML tag
doesn’t work because of the greedy nature of .*
.
>>> s = '<html><head><title>Title</title>'
>>> len(s)
32
>>> print(re.match('<.*>', s).span())
(0, 32)
>>> print(re.match('<.*>', s).group())
<html><head><title>Title</title>
The RE matches the '<'
in '<html>'
, and the .*
consumes the rest of
the string. There’s still more left in the RE, though, and the >
can’t
match at the end of the string, so the regular expression engine has to
backtrack character by character until it finds a match for the >
. The
final match extends from the '<'
in '<html>'
to the '>'
in
'</title>'
, which isn’t what you want.
In this case, the solution is to use the non-greedy quantifiers *?
, +?
,
??
, or {m,n}?
, which match as little text as possible. In the above
example, the '>'
is tried immediately after the first '<'
matches, and
when it fails, the engine advances a character at a time, retrying the '>'
at every step. This produces just the right result:
>>> print(re.match('<.*?>', s).group())
<html>
(Note that parsing HTML or XML with regular expressions is painful. Quick-and-dirty patterns will handle common cases, but HTML and XML have special cases that will break the obvious regular expression; by the time you’ve written a regular expression that handles all of the possible cases, the patterns will be very complicated. Use an HTML or XML parser module for such tasks.)
Using re.VERBOSE¶
By now you’ve probably noticed that regular expressions are a very compact notation, but they’re not terribly readable. REs of moderate complexity can become lengthy collections of backslashes, parentheses, and metacharacters, making them difficult to read and understand.
For such REs, specifying the re.VERBOSE
flag when compiling the regular
expression can be helpful, because it allows you to format the regular
expression more clearly.
The re.VERBOSE
flag has several effects. Whitespace in the regular
expression that isn’t inside a character class is ignored. This means that an
expression such as dog | cat
is equivalent to the less readable dog|cat
,
but [a b]
will still match the characters 'a'
, 'b'
, or a space. In
addition, you can also put comments inside a RE; comments extend from a #
character to the next newline. When used with triple-quoted strings, this
enables REs to be formatted more neatly:
pat = re.compile(r"""
\s* # Skip leading whitespace
(?P<header>[^:]+) # Header name
\s* : # Whitespace, and a colon
(?P<value>.*?) # The header's value -- *? used to
# lose the following trailing whitespace
\s*$ # Trailing whitespace to end-of-line
""", re.VERBOSE)
This is far more readable than:
pat = re.compile(r"\s*(?P<header>[^:]+)\s*:(?P<value>.*?)\s*$")
Feedback¶
Regular expressions are a complicated topic. Did this document help you understand them? Were there parts that were unclear, or Problems you encountered that weren’t covered here? If so, please send suggestions for improvements to the author.
The most complete book on regular expressions is almost certainly Jeffrey
Friedl’s Mastering Regular Expressions, published by O’Reilly. Unfortunately,
it exclusively concentrates on Perl and Java’s flavours of regular expressions,
and doesn’t contain any Python material at all, so it won’t be useful as a
reference for programming in Python. (The first edition covered Python’s
now-removed regex
module, which won’t help you much.) Consider checking
it out from your library.