howto/regex

HOWTO/正则表达式

Author:

A.M. Kuchling

Release:

0.05

I do not know how to do it, like how to do is wrong

简介

此文档是如何使用正则表达式模块 re 的一份简要介绍,比起库参考手册更容易理解。

详述

在 Python 1.5 中加入的 re 模块提供了 Perl 风格的正则表达式引擎。早期版本的 Python 用的 regex 模块,提供了 emacs 风格正则表达式,在 Python 2.5 版本正式删除了 regex

正则表达式(称为 REs,regexes 或 regex 模式)基本上可以称为一个特殊的编程语言,通过 re 模块嵌入到 Python 中。正则表达式是把一个模式规则应用到一些字符串集合上,这些字符串可以是英语句子,e-mail 地址,TeX 命令或者其它,然后能获得诸如此字符串完全匹配所给模式吗,在这个字符串中有任何字串匹配所给模式吗等问题的答案。也可以用来修改字符串或者任意分割字符串。

正则表达式首先被编译成字节码,然后被正则表达式引擎执行,引擎是用 C 语言写的。如果要掌握高级用法就需要对引擎的内部机制有所了解,然后按照一定的方法书写 RE 便于产生执行速度更快的字节码。此文档并不涉及 RE 的优化。

正则表达式语言相对比较小功能有限,并不能指望它能胜任所有的字符串处理任务。然而,还是有一些看起来相当复杂的字符串能够用正则表达式来处理的。当然也可以用 Python 代码来处理,不过与 RE 比起来速度慢而且不容易理解。

简单模式

我们从最简单的 RE 开始学习。既然 RE 是用在 字符串上的,那么我们就从最常见的任务开始–字符匹配。

因为正则表达式(确定性和非确定性的有限状态自动机)是计算机科学的基础,你可以参考任何一本有关编译器的书来获得更详细的信息。

字符匹配

大部分字符和字母仅仅是匹配自身。比如正则表达式“test”精确匹配字符串“test”(关闭大小写敏感模式后可匹配“Test”,“TEST”等)

但是另外有一些特殊的字符叫 metacharacters 并不匹配自身,它们用来修饰 RE 的其它部分,代表一些特殊的匹配行为。此文档的大部分内容都是在讨论这些元字符。

这是完整的元字符列表,它们代表的意义将在后面讨论: . ^ $ * + ? { [ ] \ | ( )

我们先来看 [ 和 ] 两个元字符,它们用来指定一个字符类。每个字符都必须单独列出,如果是字母表中一系列连续字符集的话可以用“-”指定范围。如 [abc] 将匹配字符 a, b 或者 c。这与 [a-c] 相同。如果你希望仅仅匹配小写字母,那么 RE 应该是 [a-z]。

一些元字符放到字符类中就变成普通字符了。例如 [akm$] 将会匹配 a, k, m 或 $ 中的任一字符,此时 $ 字符失去了元字符的特殊意义而成为普通字符。 译者注:在字符类中仍然是元字符的有三个,它们是 ^ \ -

可以对字符类取反,也就是匹配字符类列出的字符除外的其它字符,在字符类最前面加上“^”即表示取反。例如 [^5] 表示匹配除 5 以外的其它字符。

也许最重要的元字符是反斜线 \ ,因为在 Python 字符串中,反斜线后跟某些字符代表了特殊的字符系列。同时反斜线也用于解除所有元字符的特殊意义以便于可以匹配这些字符。例如,如果你要匹配 “[” 或者 “\” 你应该前置一个 \ 用于解除元字符的特殊意义使之变成普通字符:”\[“, “\\”。

以 \ 引导的一些特殊系列代表了一些经常使用的预定义的字符集,如数字集, 字母集, 非空白字符集等。以下的预定义特殊系列可用:

\d 匹配任何一个十进制数字,与字符类 [0-9] 等同。

\D 是 \d 的取反,匹配任何非十进制数字字符,等同于 [^0-9]。

\s 匹配任何空白字符,等同于 [\t\n\r\f\v]。

\S 是 \s 的取反,匹配任何非空白字符,等同于 [^\t\n\r\f\v]。

\w 匹配任何数字字母字符,等同于 [a-zA-Z0-9]。

\W 是 \w 的取反, 匹配任何非数字字母字符,等同于 [^a-zA-Z0-9]。

这些系列可以放到字符类中。如 [\s,.] 是一个字符类,表示匹配任何空白字符或者 , 或者 .

这一节要介绍的最后一个元字符是 . 它匹配除了换行符之外的任何一个字符。如果设置了 re.DOTALL 模式则换行符也将被匹配。

重复

第一件所有字符串成员函数都没法处理而正则表达式能处理的就是匹配可变字符集。当然,RE 的强大能力不仅仅如此。甚至可以指定 RE 的特定部分重复指定的次数。

第一个重复意义的元字符是 * 该元字符指定其之前的系列可以匹配零或多次,而不是精确的匹配一次。

例如,”ca*t” 可以匹配”ct”, “cat”, “caaat”等等。RE 引擎内部有一个与 C 类似的 int 型整数限制了匹配的最大次数不超过 20 亿。当然,由于内存的限制不可能创建如此大的字符串也就不会突破这个限制了。

重复操作符如 “*” 和 “+” 都是 greedy 匹配的,当匹配时它会试图匹配尽可能多的字符,直到后面的部分不能匹配,然后回退,并减少重复次数继续尝试匹配。

我们一步步分析一个例子就能很好的理解这个原理了,考虑正则表达式 “a[bcd]*b” 它将匹配一个 “a” 后跟重复零次或多次的字符类 [abc] 再以 “b” 结束的字符系列。现在假设用于字符串 “abcbd”

System Message: ERROR/3 (<string>, line 166)

Malformed table.

+------+-----------+---------------------------------+
| Step | Matched   | Explanation                     |
+======+===========+=================================+
| 1    | "a"       |字符 "a" 与 RE 匹配.              |
+------+-----------+---------------------------------+
| 2    | ``abcbd`` | 引擎匹配 ``[bcd]*``零或多次,     |
|      |           | 并且贪婪匹配尽可能多的字符,结果   |
|      |           | 到达了字符串末尾。               |
+------+-----------+---------------------------------+
| 3    | *Failure* | 引擎试图匹配 RE 的末尾字符       |
|      |           | ``b``, 但是已经到达了字符结尾,  |
|      |           | 字符串中没有字符可以被匹配, 因此 |
|      |           | 匹配失败。                      |
+------+-----------+---------------------------------+
| 4    | ``abcb``  | 回退,并且让  ``[bcd]*`` 的匹配  |
|      |           | 减少一个字符                     |
+------+-----------+---------------------------------+
| 5    | *Failure* | 再次试图匹配字符 ``b`` 但是      |
|      |           | 当前位置是字符串中最后一个字符    |
|      |           |  "d" 不能匹配 RE 的"b" 失败。    |
+------+-----------+---------------------------------+
| 6    | ``abc``   | 再次回退, 使得系列              |
|      |           | ``[bcd]*`` 仅仅匹配             |
|      |           | ``bc``.                         |
+------+-----------+---------------------------------+
| 6    | ``abcb``  | 再次试图匹配字符 ``b``这一次     |
|      |           | 正好匹配了字符串的最后一个字符    |
|      |           |  ``'b'``,因此匹配成功。         |
+------+-----------+---------------------------------+

现在到达了 RE 的末尾,并且与”abcb”匹配。从此演示中我们知道 RE 引擎首先尽可能多的匹配,如果不能成功匹配则回退一个字符并再次尝试剩余的部分,直到匹配成功或者回退到字符类系列”[abc]*”匹配的字符为零个时,说明字符串与 RE 不匹配,匹配失败。

另一个重复元字符是 “+” 代表匹配一次或多次。它与 “*” 的区别可要看清了,”*”匹配零次或多次意味着字符可以根本不出现,而”+”则要求必须至少出现一次。例如”ca+t”将会匹配”cat”, “caaat”, 但是不匹配”ct”

还有两个重复修饰符。问号”?”表示零次或一次。可以想象为其修饰的字符系列是可选的意思。比如,”home-?brew”可以匹配”homebrew”或”home-brew”

最复杂的重复修饰符是”{m,n}”,m 和 n 是十进制数字表示匹配次数最少是 m 次,最多是 n 次。例如”a/{1,3}b”将匹配”a/b”, “a//b”, 和”a///b”。它不匹配”ab”或者”a////b”。

你可以省略 m 或者 n ,当省略m时最小下限是0,省略n时最大上限是先前提到的20亿–相当于是无限大了。

还原论倾向的读者也许会指出{0,}等同于 “*” {1,}等同于 “+” 而{0,1}等同于 “?” 。最好是使用 “*” “+” “?” 因为它们简短好阅读。

使用正则表达式

我们已经了解了一些简单的 RE ,那么我们在 Python 中怎么使用呢?利用 re 模块提供的 RE 引擎接口我们可以首先编译 REs 表达式成 RE 对象然后用此对象来执行匹配。

编译正则表达式

正则表达式首先编译成 “RegexObject” 类的实例,具有诸如模式匹配,字符串替换等成员函数:
>>> import re
>>> p = re.compile(‘ab*’)
>>> p
<re.RegexObject instance at 80b4150>
re.compile() 也接受一个可选参数 flags 用来指定不同的特性和语法,后面会讲到可选的设置,现在先来看一个简单的:
>>> p = re.compile(‘ab*’, re.IGNORECASE)

RE 作为一个字符串传递给函数 re.compile() 。REs 作为字符串处理是因为正则表达式本身并不是 Python 语言核心的一部分,并且为了表述正则表达式,并没有创建特殊的语法。(有些程序甚至不需要 REs ,因此没有必要为了包含它们而增加语言细则的负担)。于是,模块 re 作为一个C扩展包含到 Python 中,就像是 socket, zlib 模块一样。

把 REs 看作字符串保持了 Python 语言的简洁性,但是引入了一个不好的缺点。下一节专门讨论这个。

反斜线灾难

先前说过,正则表达式使用反斜线”\”引导特殊字符系列或者把元字符转义为普通字符使用。在 Python 中反斜线也是用作转义字符,这就导致了冲突。

假设你需要写一个 RE 来匹配字符串”\section”,这在 LaTeX 文件中可以见到。为了搞清如何编写程序,我们从需要匹配的字符串 “\section” 开始。接下来,必须对反斜线和其它元字符使用反斜线进行转义,结果传递给 re.compile() 的应该是 “\\section” 。然而,为了用 Python 字符串来表示,还需要再对此字符串中的反斜线进行转义。

Characters Stage
\section Text string to be matched
\\section Escaped backslash for re.compile()
"\\\\section" Escaped backslashes for a string literal

简言之,为了匹配一个反斜线字符,在 RE 字符串中必须写四个反斜线字符,这是因为传递给正则表达式引擎的 RE 必须是 “\\section”,然而 RE 是用 Python 字符串来表示的,因此每个反斜线字符还需要转义。这就导致 REs 中出现大量的反斜线字符,十分难理解。

解决办法是使用 Python 的原始字符串–字符串前面加字母 ‘r’。原始字符串中的所有字符都当做普通字符处理没有任何特殊含义。因此 r”\n” 是 “\” 和 “n” 两个字符。而 “\n” 则表示一个字符即换行符。Python 中的正则表达式都用原始字符串来表示。

Regular String Raw string
"ab*" r"ab*"
"\\\\section" r"\\section"
"\\w+\\s+\\1" r"\w+\s+\1"

执行匹配

当我们有了一个编译成字节码的正则表达式对象后可以用来做什么呢? RegexObject 类的实例有很多方法和属性,在这里仅仅讨论最常用的一些,完整列表可参考 the Library Reference

Method/Attribute Purpose
match() Determine if the RE matches at the beginning of the string.
search() Scan through a string, looking for any location where this RE matches.
findall() Find all substrings where the RE matches, and returns them as a list.
finditer() Find all substrings where the RE matches, and returns them as an iterator.

如果没找到匹配,则 match()search() 返回”None” 。如果匹配成功,则返回一个 “MatchObject” 对象实例,包含所有匹配信息,如从哪儿开始到哪儿结束,匹配的子串等等。

可以导入 re 模块来交互式学习和使用正则表达式。如果安装了 Tkinter ,那么随 Python 发行包一起发行的演示程序 Tools/scripts/redemo.py 值得看看。输入 REs 和需要匹配的字符串后,它会显示匹配的结果。 redemo.py 对调试正则表达式非常有用。Phil Schwartz 的 Kodos 也是一个开发正则表达式的交互式工具。

此 HOWTO 使用标准 Python 解释器来执行演示范例。首先启动 Python 解释器,导入模块 re 并编译成 RE:

Python 2.2.2 (#1, Feb 10 2003, 12:57:01)
>>> import re
>>> p = re.compile('[a-z]+')
>>> p
<_sre.SRE_Pattern object at 80c3c28>

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 MatchObject, so you should store the result in a variable for later use. :

>>> m = p.match('tempo')
>>> m
<_sre.SRE_Match object at 80c4f68>

Now you can query the MatchObject for information about the matching string. MatchObject instances also have several methods and attributes; the most important ones are:

Method/Attribute Purpose
group() Return the string matched by the RE
start() Return the starting position of the match
end() Return the ending position of the match
span() 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 RegexObject instances 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.MatchObject instance at 80c9650>
>>> m.group()
'message'
>>> m.span()
(4, 11)

In actual programs, the most common style is to store the MatchObject 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 RegexObject methods return all of the matches for a pattern. findall() returns a list of matching strings:

>>> p = re.compile('\d+')
>>> p.findall('12 drummers drumming, 11 pipers piping, 10 lords a-leaping')
['12', '11', '10']

findall() has to create the entire list before it can be returned as the result. The finditer() method returns a sequence of MatchObject instances as an iterator. [1] :

>>> iterator = p.finditer('12 drummers drumming, 11 ... 10 ...')
>>> iterator
<callable-iterator object at 0x401833ac>
>>> for match in iterator:
...     print(match.span())
...
(0, 2)
(22, 24)
(29, 31)

Module-Level Functions

You don’t have to create a RegexObject 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 RegexObject method, with the RE string added as the first argument, and still return either None or a MatchObject 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.MatchObject instance at 80c5978>

Under the hood, these functions simply produce a RegexObject 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 are faster.

Should you use these module-level functions, or should you get the RegexObject and call its methods yourself? That choice depends on how frequently the RE will be used, and on your personal coding style. If the RE is being used at only one point in the code, then the module functions are probably more convenient. If a program contains a lot of regular expressions, or re-uses the same ones in several locations, then it might be worthwhile to collect all the definitions in one place, in a section of code that compiles all the REs ahead of time. To take an example from the standard library, here’s an extract from xmllib.py:

ref = re.compile( ... )
entityref = re.compile( ... )
charref = re.compile( ... )
starttagopen = re.compile( ... )

I generally prefer to work with the compiled object, even for one-time uses, but few people will be as much of a purist about this as I am.

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
DOTALL, S Make . match any character, including newlines
IGNORECASE, I Do case-insensitive matches
LOCALE, L Do a locale-aware match
MULTILINE, M Multi-line matching, affecting ^ and $
VERBOSE, X Enable verbose REs, which can be organized more cleanly and understandably.
I
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, and Spam will match Spam, spam, or spAM. This lowercasing doesn’t take the current locale into account; it will if you also set the LOCALE flag.

L
LOCALE

Make \w, \W, \b, and \B, dependent on the current locale.

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 French text, you’d want to be able to write \w+ to match words, but \w only matches the character class [A-Za-z]; it won’t match 'é' or 'ç'. If your system is configured properly and a French locale is selected, certain C functions will tell the program that 'é' should also be considered a letter. Setting the LOCALE 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.

M
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).

S
DOTALL

Makes the '.' special character match any character at all, including a newline; without this flag, '.' will match anything except a newline.

X
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. In MULTILINE 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.MatchObject instance at 80c1520>
>>> print(re.search('^From', 'Reciting From Memory'))
None
$

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.MatchObject instance at 80adfa8>
>>> print(re.search('}$', '{block} '))
None
>>> print(re.search('}$', '{block}\n'))
<re.MatchObject instance at 80adfa8>

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. In MULTILINE 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.
\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.MatchObject instance at 80c8f28>
>>> 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.MatchObject instance at 80c3ee0>

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 repeating qualifier, 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 MatchObject 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')
>>> 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 added several additional features to standard regular expressions, and the Python re module supports most of them. It would have been difficult to choose new single-keystroke metacharacters or new special sequences beginning with \ to represent the new features without making Perl’s regular expressions confusingly different from standard REs. If you 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 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. Currently there are two such extensions: (?P<name>...) defines a named group, and (?P=name) is a backreference to a named group. If future versions of Perl 5 add similar features using a different syntax, the re module will be changed to support the new syntax, while preserving the Python-specific syntax for compatibility’s sake.

Now that we’ve looked at the general extension syntax, we can return to the features that simplify working with groups in complex REs. Since groups are numbered from left to right and a complex expression may use many groups, it can become difficult to keep track of the correct numbering. Modifying such a complex RE is annoying, too: insert a new group near the beginning and you change the numbers of everything that follows it.

Sometimes you’ll want to use a group to collect 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 also behave exactly like capturing groups, and additionally associate a name with a group. The MatchObject 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'

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 can also be written as (?P<word>\b\w+)\s+(?P=word):

>>> p = re.compile(r'(?P<word>\b\w+)\s+(?P=word)')
>>> 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; I’ve put it inside a character class. 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.

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 RegexObject methods:

Method/Attribute Purpose
split() Split the string into a list, splitting it wherever the RE matches
sub() Find all substrings where the RE matches, and replace them with a different string
subn() Does the same thing as sub(), but returns the new string and the number of replacements

Splitting Strings

The split() method of a RegexObject 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; 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('[\W]+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split('([\W]+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split('[\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 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 \j 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 MatchObject 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 a string or a RegexObject; if you need to specify regular expression flags, you must either use a RegexObject as the first parameter, or use embedded modifiers in the pattern, 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 qualifiers *?, +?, ??, 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.)

Not 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.

Footnotes

[1]Introduced in Python 2.2.2.