blob: d6c6b0a0906a3d81d89e76e15a33c4a6eb9b4ab9 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001****************************
Georg Brandl6911e3c2007-09-04 07:15:32 +00002 Regular Expression HOWTO
Georg Brandl116aa622007-08-15 14:28:22 +00003****************************
4
5:Author: A.M. Kuchling
6:Release: 0.05
7
Christian Heimes5b5e81c2007-12-31 16:14:33 +00008.. TODO:
9 Document lookbehind assertions
10 Better way of displaying a RE, a string, and what it matches
11 Mention optional argument to match.groups()
12 Unicode (at least a reference)
Georg Brandl116aa622007-08-15 14:28:22 +000013
14
15.. topic:: Abstract
16
17 This document is an introductory tutorial to using regular expressions in Python
18 with the :mod:`re` module. It provides a gentler introduction than the
19 corresponding section in the Library Reference.
20
21
22Introduction
23============
24
25The :mod:`re` module was added in Python 1.5, and provides Perl-style regular
26expression patterns. Earlier versions of Python came with the :mod:`regex`
27module, which provided Emacs-style patterns. The :mod:`regex` module was
28removed completely in Python 2.5.
29
30Regular expressions (called REs, or regexes, or regex patterns) are essentially
31a tiny, highly specialized programming language embedded inside Python and made
32available through the :mod:`re` module. Using this little language, you specify
33the rules for the set of possible strings that you want to match; this set might
34contain English sentences, or e-mail addresses, or TeX commands, or anything you
35like. You can then ask questions such as "Does this string match the pattern?",
36or "Is there a match for the pattern anywhere in this string?". You can also
37use REs to modify a string or to split it apart in various ways.
38
39Regular expression patterns are compiled into a series of bytecodes which are
40then executed by a matching engine written in C. For advanced use, it may be
41necessary to pay careful attention to how the engine will execute a given RE,
42and write the RE in a certain way in order to produce bytecode that runs faster.
43Optimization isn't covered in this document, because it requires that you have a
44good understanding of the matching engine's internals.
45
46The regular expression language is relatively small and restricted, so not all
47possible string processing tasks can be done using regular expressions. There
48are also tasks that *can* be done with regular expressions, but the expressions
49turn out to be very complicated. In these cases, you may be better off writing
50Python code to do the processing; while Python code will be slower than an
51elaborate regular expression, it will also probably be more understandable.
52
53
54Simple Patterns
55===============
56
57We'll start by learning about the simplest possible regular expressions. Since
58regular expressions are used to operate on strings, we'll begin with the most
59common task: matching characters.
60
61For a detailed explanation of the computer science underlying regular
62expressions (deterministic and non-deterministic finite automata), you can refer
63to almost any textbook on writing compilers.
64
65
66Matching Characters
67-------------------
68
69Most letters and characters will simply match themselves. For example, the
70regular expression ``test`` will match the string ``test`` exactly. (You can
71enable a case-insensitive mode that would let this RE match ``Test`` or ``TEST``
72as well; more about this later.)
73
74There are exceptions to this rule; some characters are special
75:dfn:`metacharacters`, and don't match themselves. Instead, they signal that
76some out-of-the-ordinary thing should be matched, or they affect other portions
77of the RE by repeating them or changing their meaning. Much of this document is
78devoted to discussing various metacharacters and what they do.
79
80Here's a complete list of the metacharacters; their meanings will be discussed
81in the rest of this HOWTO. ::
82
83 . ^ $ * + ? { [ ] \ | ( )
84
85The first metacharacters we'll look at are ``[`` and ``]``. They're used for
86specifying a character class, which is a set of characters that you wish to
87match. Characters can be listed individually, or a range of characters can be
88indicated by giving two characters and separating them by a ``'-'``. For
89example, ``[abc]`` will match any of the characters ``a``, ``b``, or ``c``; this
90is the same as ``[a-c]``, which uses a range to express the same set of
91characters. If you wanted to match only lowercase letters, your RE would be
92``[a-z]``.
93
Georg Brandl116aa622007-08-15 14:28:22 +000094Metacharacters are not active inside classes. For example, ``[akm$]`` will
95match any of the characters ``'a'``, ``'k'``, ``'m'``, or ``'$'``; ``'$'`` is
96usually a metacharacter, but inside a character class it's stripped of its
97special nature.
98
99You can match the characters not listed within the class by :dfn:`complementing`
100the set. This is indicated by including a ``'^'`` as the first character of the
101class; ``'^'`` outside a character class will simply match the ``'^'``
102character. For example, ``[^5]`` will match any character except ``'5'``.
103
104Perhaps the most important metacharacter is the backslash, ``\``. As in Python
105string literals, the backslash can be followed by various characters to signal
106various special sequences. It's also used to escape all the metacharacters so
107you can still match them in patterns; for example, if you need to match a ``[``
108or ``\``, you can precede them with a backslash to remove their special
109meaning: ``\[`` or ``\\``.
110
111Some of the special sequences beginning with ``'\'`` represent predefined sets
112of characters that are often useful, such as the set of digits, the set of
113letters, or the set of anything that isn't whitespace. The following predefined
114special sequences are available:
115
116``\d``
117 Matches any decimal digit; this is equivalent to the class ``[0-9]``.
118
119``\D``
120 Matches any non-digit character; this is equivalent to the class ``[^0-9]``.
121
122``\s``
123 Matches any whitespace character; this is equivalent to the class ``[
124 \t\n\r\f\v]``.
125
126``\S``
127 Matches any non-whitespace character; this is equivalent to the class ``[^
128 \t\n\r\f\v]``.
129
130``\w``
131 Matches any alphanumeric character; this is equivalent to the class
132 ``[a-zA-Z0-9_]``.
133
134``\W``
135 Matches any non-alphanumeric character; this is equivalent to the class
136 ``[^a-zA-Z0-9_]``.
137
138These sequences can be included inside a character class. For example,
139``[\s,.]`` is a character class that will match any whitespace character, or
140``','`` or ``'.'``.
141
142The final metacharacter in this section is ``.``. It matches anything except a
143newline character, and there's an alternate mode (``re.DOTALL``) where it will
144match even a newline. ``'.'`` is often used where you want to match "any
145character".
146
147
148Repeating Things
149----------------
150
151Being able to match varying sets of characters is the first thing regular
152expressions can do that isn't already possible with the methods available on
153strings. However, if that was the only additional capability of regexes, they
154wouldn't be much of an advance. Another capability is that you can specify that
155portions of the RE must be repeated a certain number of times.
156
157The first metacharacter for repeating things that we'll look at is ``*``. ``*``
158doesn't match the literal character ``*``; instead, it specifies that the
159previous character can be matched zero or more times, instead of exactly once.
160
161For example, ``ca*t`` will match ``ct`` (0 ``a`` characters), ``cat`` (1 ``a``),
162``caaat`` (3 ``a`` characters), and so forth. The RE engine has various
163internal limitations stemming from the size of C's ``int`` type that will
164prevent it from matching over 2 billion ``a`` characters; you probably don't
165have enough memory to construct a string that large, so you shouldn't run into
166that limit.
167
168Repetitions such as ``*`` are :dfn:`greedy`; when repeating a RE, the matching
169engine will try to repeat it as many times as possible. If later portions of the
170pattern don't match, the matching engine will then back up and try again with
171few repetitions.
172
173A step-by-step example will make this more obvious. Let's consider the
174expression ``a[bcd]*b``. This matches the letter ``'a'``, zero or more letters
175from the class ``[bcd]``, and finally ends with a ``'b'``. Now imagine matching
176this RE against the string ``abcbd``.
177
178+------+-----------+---------------------------------+
179| Step | Matched | Explanation |
180+======+===========+=================================+
181| 1 | ``a`` | The ``a`` in the RE matches. |
182+------+-----------+---------------------------------+
183| 2 | ``abcbd`` | The engine matches ``[bcd]*``, |
184| | | going as far as it can, which |
185| | | is to the end of the string. |
186+------+-----------+---------------------------------+
187| 3 | *Failure* | The engine tries to match |
188| | | ``b``, but the current position |
189| | | is at the end of the string, so |
190| | | it fails. |
191+------+-----------+---------------------------------+
192| 4 | ``abcb`` | Back up, so that ``[bcd]*`` |
193| | | matches one less character. |
194+------+-----------+---------------------------------+
195| 5 | *Failure* | Try ``b`` again, but the |
196| | | current position is at the last |
197| | | character, which is a ``'d'``. |
198+------+-----------+---------------------------------+
199| 6 | ``abc`` | Back up again, so that |
200| | | ``[bcd]*`` is only matching |
201| | | ``bc``. |
202+------+-----------+---------------------------------+
203| 6 | ``abcb`` | Try ``b`` again. This time |
204| | | but the character at the |
205| | | current position is ``'b'``, so |
206| | | it succeeds. |
207+------+-----------+---------------------------------+
208
209The end of the RE has now been reached, and it has matched ``abcb``. This
210demonstrates how the matching engine goes as far as it can at first, and if no
211match is found it will then progressively back up and retry the rest of the RE
212again and again. It will back up until it has tried zero matches for
213``[bcd]*``, and if that subsequently fails, the engine will conclude that the
214string doesn't match the RE at all.
215
216Another repeating metacharacter is ``+``, which matches one or more times. Pay
217careful attention to the difference between ``*`` and ``+``; ``*`` matches
218*zero* or more times, so whatever's being repeated may not be present at all,
219while ``+`` requires at least *one* occurrence. To use a similar example,
220``ca+t`` will match ``cat`` (1 ``a``), ``caaat`` (3 ``a``'s), but won't match
221``ct``.
222
223There are two more repeating qualifiers. The question mark character, ``?``,
224matches either once or zero times; you can think of it as marking something as
225being optional. For example, ``home-?brew`` matches either ``homebrew`` or
226``home-brew``.
227
228The most complicated repeated qualifier is ``{m,n}``, where *m* and *n* are
229decimal integers. This qualifier means there must be at least *m* repetitions,
230and at most *n*. For example, ``a/{1,3}b`` will match ``a/b``, ``a//b``, and
231``a///b``. It won't match ``ab``, which has no slashes, or ``a////b``, which
232has four.
233
234You can omit either *m* or *n*; in that case, a reasonable value is assumed for
235the missing value. Omitting *m* is interpreted as a lower limit of 0, while
236omitting *n* results in an upper bound of infinity --- actually, the upper bound
237is the 2-billion limit mentioned earlier, but that might as well be infinity.
238
239Readers of a reductionist bent may notice that the three other qualifiers can
240all be expressed using this notation. ``{0,}`` is the same as ``*``, ``{1,}``
241is equivalent to ``+``, and ``{0,1}`` is the same as ``?``. It's better to use
242``*``, ``+``, or ``?`` when you can, simply because they're shorter and easier
243to read.
244
245
246Using Regular Expressions
247=========================
248
249Now that we've looked at some simple regular expressions, how do we actually use
250them in Python? The :mod:`re` module provides an interface to the regular
251expression engine, allowing you to compile REs into objects and then perform
252matches with them.
253
254
255Compiling Regular Expressions
256-----------------------------
257
258Regular expressions are compiled into :class:`RegexObject` instances, which have
259methods for various operations such as searching for pattern matches or
260performing string substitutions. ::
261
262 >>> import re
263 >>> p = re.compile('ab*')
Georg Brandl6911e3c2007-09-04 07:15:32 +0000264 >>> p
Georg Brandl116aa622007-08-15 14:28:22 +0000265 <re.RegexObject instance at 80b4150>
266
267:func:`re.compile` also accepts an optional *flags* argument, used to enable
268various special features and syntax variations. We'll go over the available
269settings later, but for now a single example will do::
270
271 >>> p = re.compile('ab*', re.IGNORECASE)
272
273The RE is passed to :func:`re.compile` as a string. REs are handled as strings
274because regular expressions aren't part of the core Python language, and no
275special syntax was created for expressing them. (There are applications that
276don't need REs at all, so there's no need to bloat the language specification by
277including them.) Instead, the :mod:`re` module is simply a C extension module
278included with Python, just like the :mod:`socket` or :mod:`zlib` modules.
279
280Putting REs in strings keeps the Python language simpler, but has one
281disadvantage which is the topic of the next section.
282
283
284The Backslash Plague
285--------------------
286
287As stated earlier, regular expressions use the backslash character (``'\'``) to
288indicate special forms or to allow special characters to be used without
289invoking their special meaning. This conflicts with Python's usage of the same
290character for the same purpose in string literals.
291
292Let's say you want to write a RE that matches the string ``\section``, which
293might be found in a LaTeX file. To figure out what to write in the program
294code, start with the desired string to be matched. Next, you must escape any
295backslashes and other metacharacters by preceding them with a backslash,
296resulting in the string ``\\section``. The resulting string that must be passed
297to :func:`re.compile` must be ``\\section``. However, to express this as a
298Python string literal, both backslashes must be escaped *again*.
299
300+-------------------+------------------------------------------+
301| Characters | Stage |
302+===================+==========================================+
303| ``\section`` | Text string to be matched |
304+-------------------+------------------------------------------+
305| ``\\section`` | Escaped backslash for :func:`re.compile` |
306+-------------------+------------------------------------------+
307| ``"\\\\section"`` | Escaped backslashes for a string literal |
308+-------------------+------------------------------------------+
309
310In short, to match a literal backslash, one has to write ``'\\\\'`` as the RE
311string, because the regular expression must be ``\\``, and each backslash must
312be expressed as ``\\`` inside a regular Python string literal. In REs that
313feature backslashes repeatedly, this leads to lots of repeated backslashes and
314makes the resulting strings difficult to understand.
315
316The solution is to use Python's raw string notation for regular expressions;
317backslashes are not handled in any special way in a string literal prefixed with
318``'r'``, so ``r"\n"`` is a two-character string containing ``'\'`` and ``'n'``,
319while ``"\n"`` is a one-character string containing a newline. Regular
320expressions will often be written in Python code using this raw string notation.
321
322+-------------------+------------------+
323| Regular String | Raw string |
324+===================+==================+
325| ``"ab*"`` | ``r"ab*"`` |
326+-------------------+------------------+
327| ``"\\\\section"`` | ``r"\\section"`` |
328+-------------------+------------------+
329| ``"\\w+\\s+\\1"`` | ``r"\w+\s+\1"`` |
330+-------------------+------------------+
331
332
333Performing Matches
334------------------
335
336Once you have an object representing a compiled regular expression, what do you
337do with it? :class:`RegexObject` instances have several methods and attributes.
Georg Brandl86def6c2008-01-21 20:36:10 +0000338Only the most significant ones will be covered here; consult the :mod:`re` docs
339for a complete listing.
Georg Brandl116aa622007-08-15 14:28:22 +0000340
341+------------------+-----------------------------------------------+
342| Method/Attribute | Purpose |
343+==================+===============================================+
344| ``match()`` | Determine if the RE matches at the beginning |
345| | of the string. |
346+------------------+-----------------------------------------------+
347| ``search()`` | Scan through a string, looking for any |
348| | location where this RE matches. |
349+------------------+-----------------------------------------------+
350| ``findall()`` | Find all substrings where the RE matches, and |
351| | returns them as a list. |
352+------------------+-----------------------------------------------+
353| ``finditer()`` | Find all substrings where the RE matches, and |
Georg Brandl9afde1c2007-11-01 20:32:30 +0000354| | returns them as an :term:`iterator`. |
Georg Brandl116aa622007-08-15 14:28:22 +0000355+------------------+-----------------------------------------------+
356
357:meth:`match` and :meth:`search` return ``None`` if no match can be found. If
358they're successful, a ``MatchObject`` instance is returned, containing
359information about the match: where it starts and ends, the substring it matched,
360and more.
361
362You can learn about this by interactively experimenting with the :mod:`re`
363module. If you have Tkinter available, you may also want to look at
364:file:`Tools/scripts/redemo.py`, a demonstration program included with the
365Python distribution. It allows you to enter REs and strings, and displays
366whether the RE matches or fails. :file:`redemo.py` can be quite useful when
367trying to debug a complicated RE. Phil Schwartz's `Kodos
368<http://www.phil-schwartz.com/kodos.spy>`_ is also an interactive tool for
369developing and testing RE patterns.
370
371This HOWTO uses the standard Python interpreter for its examples. First, run the
372Python interpreter, import the :mod:`re` module, and compile a RE::
373
374 Python 2.2.2 (#1, Feb 10 2003, 12:57:01)
375 >>> import re
376 >>> p = re.compile('[a-z]+')
377 >>> p
378 <_sre.SRE_Pattern object at 80c3c28>
379
380Now, you can try matching various strings against the RE ``[a-z]+``. An empty
381string shouldn't match at all, since ``+`` means 'one or more repetitions'.
382:meth:`match` should return ``None`` in this case, which will cause the
383interpreter to print no output. You can explicitly print the result of
384:meth:`match` to make this clear. ::
385
386 >>> p.match("")
Georg Brandl6911e3c2007-09-04 07:15:32 +0000387 >>> print(p.match(""))
Georg Brandl116aa622007-08-15 14:28:22 +0000388 None
389
390Now, let's try it on a string that it should match, such as ``tempo``. In this
391case, :meth:`match` will return a :class:`MatchObject`, so you should store the
392result in a variable for later use. ::
393
394 >>> m = p.match('tempo')
Georg Brandl6911e3c2007-09-04 07:15:32 +0000395 >>> m
Georg Brandl116aa622007-08-15 14:28:22 +0000396 <_sre.SRE_Match object at 80c4f68>
397
398Now you can query the :class:`MatchObject` for information about the matching
399string. :class:`MatchObject` instances also have several methods and
400attributes; the most important ones are:
401
402+------------------+--------------------------------------------+
403| Method/Attribute | Purpose |
404+==================+============================================+
405| ``group()`` | Return the string matched by the RE |
406+------------------+--------------------------------------------+
407| ``start()`` | Return the starting position of the match |
408+------------------+--------------------------------------------+
409| ``end()`` | Return the ending position of the match |
410+------------------+--------------------------------------------+
411| ``span()`` | Return a tuple containing the (start, end) |
412| | positions of the match |
413+------------------+--------------------------------------------+
414
415Trying these methods will soon clarify their meaning::
416
417 >>> m.group()
418 'tempo'
419 >>> m.start(), m.end()
420 (0, 5)
421 >>> m.span()
422 (0, 5)
423
424:meth:`group` returns the substring that was matched by the RE. :meth:`start`
425and :meth:`end` return the starting and ending index of the match. :meth:`span`
426returns both start and end indexes in a single tuple. Since the :meth:`match`
427method only checks if the RE matches at the start of a string, :meth:`start`
428will always be zero. However, the :meth:`search` method of :class:`RegexObject`
429instances scans through the string, so the match may not start at zero in that
430case. ::
431
Georg Brandl6911e3c2007-09-04 07:15:32 +0000432 >>> print(p.match('::: message'))
Georg Brandl116aa622007-08-15 14:28:22 +0000433 None
Georg Brandl6911e3c2007-09-04 07:15:32 +0000434 >>> m = p.search('::: message') ; print(m)
Georg Brandl116aa622007-08-15 14:28:22 +0000435 <re.MatchObject instance at 80c9650>
436 >>> m.group()
437 'message'
438 >>> m.span()
439 (4, 11)
440
441In actual programs, the most common style is to store the :class:`MatchObject`
442in a variable, and then check if it was ``None``. This usually looks like::
443
444 p = re.compile( ... )
445 m = p.match( 'string goes here' )
446 if m:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000447 print('Match found: ', m.group())
Georg Brandl116aa622007-08-15 14:28:22 +0000448 else:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000449 print('No match')
Georg Brandl116aa622007-08-15 14:28:22 +0000450
451Two :class:`RegexObject` methods return all of the matches for a pattern.
452:meth:`findall` returns a list of matching strings::
453
454 >>> p = re.compile('\d+')
455 >>> p.findall('12 drummers drumming, 11 pipers piping, 10 lords a-leaping')
456 ['12', '11', '10']
457
458:meth:`findall` has to create the entire list before it can be returned as the
459result. The :meth:`finditer` method returns a sequence of :class:`MatchObject`
Georg Brandl9afde1c2007-11-01 20:32:30 +0000460instances as an :term:`iterator`. [#]_ ::
Georg Brandl116aa622007-08-15 14:28:22 +0000461
462 >>> iterator = p.finditer('12 drummers drumming, 11 ... 10 ...')
463 >>> iterator
464 <callable-iterator object at 0x401833ac>
465 >>> for match in iterator:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000466 ... print(match.span())
Georg Brandl116aa622007-08-15 14:28:22 +0000467 ...
468 (0, 2)
469 (22, 24)
470 (29, 31)
471
472
473Module-Level Functions
474----------------------
475
476You don't have to create a :class:`RegexObject` and call its methods; the
477:mod:`re` module also provides top-level functions called :func:`match`,
478:func:`search`, :func:`findall`, :func:`sub`, and so forth. These functions
479take the same arguments as the corresponding :class:`RegexObject` method, with
480the RE string added as the first argument, and still return either ``None`` or a
481:class:`MatchObject` instance. ::
482
Georg Brandl6911e3c2007-09-04 07:15:32 +0000483 >>> print(re.match(r'From\s+', 'Fromage amk'))
Georg Brandl116aa622007-08-15 14:28:22 +0000484 None
485 >>> re.match(r'From\s+', 'From amk Thu May 14 19:12:10 1998')
486 <re.MatchObject instance at 80c5978>
487
488Under the hood, these functions simply produce a :class:`RegexObject` for you
489and call the appropriate method on it. They also store the compiled object in a
490cache, so future calls using the same RE are faster.
491
492Should you use these module-level functions, or should you get the
493:class:`RegexObject` and call its methods yourself? That choice depends on how
494frequently the RE will be used, and on your personal coding style. If the RE is
495being used at only one point in the code, then the module functions are probably
496more convenient. If a program contains a lot of regular expressions, or re-uses
497the same ones in several locations, then it might be worthwhile to collect all
498the definitions in one place, in a section of code that compiles all the REs
499ahead of time. To take an example from the standard library, here's an extract
500from :file:`xmllib.py`::
501
502 ref = re.compile( ... )
503 entityref = re.compile( ... )
504 charref = re.compile( ... )
505 starttagopen = re.compile( ... )
506
507I generally prefer to work with the compiled object, even for one-time uses, but
508few people will be as much of a purist about this as I am.
509
510
511Compilation Flags
512-----------------
513
514Compilation flags let you modify some aspects of how regular expressions work.
515Flags are available in the :mod:`re` module under two names, a long name such as
516:const:`IGNORECASE` and a short, one-letter form such as :const:`I`. (If you're
517familiar with Perl's pattern modifiers, the one-letter forms use the same
518letters; the short form of :const:`re.VERBOSE` is :const:`re.X`, for example.)
519Multiple flags can be specified by bitwise OR-ing them; ``re.I | re.M`` sets
520both the :const:`I` and :const:`M` flags, for example.
521
522Here's a table of the available flags, followed by a more detailed explanation
523of each one.
524
525+---------------------------------+--------------------------------------------+
526| Flag | Meaning |
527+=================================+============================================+
528| :const:`DOTALL`, :const:`S` | Make ``.`` match any character, including |
529| | newlines |
530+---------------------------------+--------------------------------------------+
531| :const:`IGNORECASE`, :const:`I` | Do case-insensitive matches |
532+---------------------------------+--------------------------------------------+
533| :const:`LOCALE`, :const:`L` | Do a locale-aware match |
534+---------------------------------+--------------------------------------------+
535| :const:`MULTILINE`, :const:`M` | Multi-line matching, affecting ``^`` and |
536| | ``$`` |
537+---------------------------------+--------------------------------------------+
538| :const:`VERBOSE`, :const:`X` | Enable verbose REs, which can be organized |
539| | more cleanly and understandably. |
540+---------------------------------+--------------------------------------------+
541
542
543.. data:: I
544 IGNORECASE
545 :noindex:
546
547 Perform case-insensitive matching; character class and literal strings will
548 match letters by ignoring case. For example, ``[A-Z]`` will match lowercase
549 letters, too, and ``Spam`` will match ``Spam``, ``spam``, or ``spAM``. This
550 lowercasing doesn't take the current locale into account; it will if you also
551 set the :const:`LOCALE` flag.
552
553
554.. data:: L
555 LOCALE
556 :noindex:
557
558 Make ``\w``, ``\W``, ``\b``, and ``\B``, dependent on the current locale.
559
560 Locales are a feature of the C library intended to help in writing programs that
561 take account of language differences. For example, if you're processing French
562 text, you'd want to be able to write ``\w+`` to match words, but ``\w`` only
563 matches the character class ``[A-Za-z]``; it won't match ``'é'`` or ``'ç'``. If
564 your system is configured properly and a French locale is selected, certain C
565 functions will tell the program that ``'é'`` should also be considered a letter.
566 Setting the :const:`LOCALE` flag when compiling a regular expression will cause
567 the resulting compiled object to use these C functions for ``\w``; this is
568 slower, but also enables ``\w+`` to match French words as you'd expect.
569
570
571.. data:: M
572 MULTILINE
573 :noindex:
574
575 (``^`` and ``$`` haven't been explained yet; they'll be introduced in section
576 :ref:`more-metacharacters`.)
577
578 Usually ``^`` matches only at the beginning of the string, and ``$`` matches
579 only at the end of the string and immediately before the newline (if any) at the
580 end of the string. When this flag is specified, ``^`` matches at the beginning
581 of the string and at the beginning of each line within the string, immediately
582 following each newline. Similarly, the ``$`` metacharacter matches either at
583 the end of the string and at the end of each line (immediately preceding each
584 newline).
585
586
587.. data:: S
588 DOTALL
589 :noindex:
590
591 Makes the ``'.'`` special character match any character at all, including a
592 newline; without this flag, ``'.'`` will match anything *except* a newline.
593
594
595.. data:: X
596 VERBOSE
597 :noindex:
598
599 This flag allows you to write regular expressions that are more readable by
600 granting you more flexibility in how you can format them. When this flag has
601 been specified, whitespace within the RE string is ignored, except when the
602 whitespace is in a character class or preceded by an unescaped backslash; this
603 lets you organize and indent the RE more clearly. This flag also lets you put
604 comments within a RE that will be ignored by the engine; comments are marked by
605 a ``'#'`` that's neither in a character class or preceded by an unescaped
606 backslash.
607
608 For example, here's a RE that uses :const:`re.VERBOSE`; see how much easier it
609 is to read? ::
610
611 charref = re.compile(r"""
612 &[#] # Start of a numeric entity reference
613 (
614 0[0-7]+ # Octal form
615 | [0-9]+ # Decimal form
616 | x[0-9a-fA-F]+ # Hexadecimal form
617 )
618 ; # Trailing semicolon
619 """, re.VERBOSE)
620
621 Without the verbose setting, the RE would look like this::
622
623 charref = re.compile("&#(0[0-7]+"
624 "|[0-9]+"
625 "|x[0-9a-fA-F]+);")
626
627 In the above example, Python's automatic concatenation of string literals has
628 been used to break up the RE into smaller pieces, but it's still more difficult
629 to understand than the version using :const:`re.VERBOSE`.
630
631
632More Pattern Power
633==================
634
635So far we've only covered a part of the features of regular expressions. In
636this section, we'll cover some new metacharacters, and how to use groups to
637retrieve portions of the text that was matched.
638
639
640.. _more-metacharacters:
641
642More Metacharacters
643-------------------
644
645There are some metacharacters that we haven't covered yet. Most of them will be
646covered in this section.
647
648Some of the remaining metacharacters to be discussed are :dfn:`zero-width
649assertions`. They don't cause the engine to advance through the string;
650instead, they consume no characters at all, and simply succeed or fail. For
651example, ``\b`` is an assertion that the current position is located at a word
652boundary; the position isn't changed by the ``\b`` at all. This means that
653zero-width assertions should never be repeated, because if they match once at a
654given location, they can obviously be matched an infinite number of times.
655
656``|``
657 Alternation, or the "or" operator. If A and B are regular expressions,
658 ``A|B`` will match any string that matches either ``A`` or ``B``. ``|`` has very
659 low precedence in order to make it work reasonably when you're alternating
660 multi-character strings. ``Crow|Servo`` will match either ``Crow`` or ``Servo``,
661 not ``Cro``, a ``'w'`` or an ``'S'``, and ``ervo``.
662
663 To match a literal ``'|'``, use ``\|``, or enclose it inside a character class,
664 as in ``[|]``.
665
666``^``
667 Matches at the beginning of lines. Unless the :const:`MULTILINE` flag has been
668 set, this will only match at the beginning of the string. In :const:`MULTILINE`
669 mode, this also matches immediately after each newline within the string.
670
671 For example, if you wish to match the word ``From`` only at the beginning of a
672 line, the RE to use is ``^From``. ::
673
Georg Brandl6911e3c2007-09-04 07:15:32 +0000674 >>> print(re.search('^From', 'From Here to Eternity'))
Georg Brandl116aa622007-08-15 14:28:22 +0000675 <re.MatchObject instance at 80c1520>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000676 >>> print(re.search('^From', 'Reciting From Memory'))
Georg Brandl116aa622007-08-15 14:28:22 +0000677 None
678
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000679 .. To match a literal \character{\^}, use \regexp{\e\^} or enclose it
680 .. inside a character class, as in \regexp{[{\e}\^]}.
Georg Brandl116aa622007-08-15 14:28:22 +0000681
682``$``
683 Matches at the end of a line, which is defined as either the end of the string,
684 or any location followed by a newline character. ::
685
Georg Brandl6911e3c2007-09-04 07:15:32 +0000686 >>> print(re.search('}$', '{block}'))
Georg Brandl116aa622007-08-15 14:28:22 +0000687 <re.MatchObject instance at 80adfa8>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000688 >>> print(re.search('}$', '{block} '))
Georg Brandl116aa622007-08-15 14:28:22 +0000689 None
Georg Brandl6911e3c2007-09-04 07:15:32 +0000690 >>> print(re.search('}$', '{block}\n'))
Georg Brandl116aa622007-08-15 14:28:22 +0000691 <re.MatchObject instance at 80adfa8>
692
693 To match a literal ``'$'``, use ``\$`` or enclose it inside a character class,
694 as in ``[$]``.
695
Georg Brandl116aa622007-08-15 14:28:22 +0000696``\A``
697 Matches only at the start of the string. When not in :const:`MULTILINE` mode,
698 ``\A`` and ``^`` are effectively the same. In :const:`MULTILINE` mode, they're
699 different: ``\A`` still matches only at the beginning of the string, but ``^``
700 may match at any location inside the string that follows a newline character.
701
702``\Z``
703 Matches only at the end of the string.
704
705``\b``
706 Word boundary. This is a zero-width assertion that matches only at the
707 beginning or end of a word. A word is defined as a sequence of alphanumeric
708 characters, so the end of a word is indicated by whitespace or a
709 non-alphanumeric character.
710
711 The following example matches ``class`` only when it's a complete word; it won't
712 match when it's contained inside another word. ::
713
714 >>> p = re.compile(r'\bclass\b')
Georg Brandl6911e3c2007-09-04 07:15:32 +0000715 >>> print(p.search('no class at all'))
Georg Brandl116aa622007-08-15 14:28:22 +0000716 <re.MatchObject instance at 80c8f28>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000717 >>> print(p.search('the declassified algorithm'))
Georg Brandl116aa622007-08-15 14:28:22 +0000718 None
Georg Brandl6911e3c2007-09-04 07:15:32 +0000719 >>> print(p.search('one subclass is'))
Georg Brandl116aa622007-08-15 14:28:22 +0000720 None
721
722 There are two subtleties you should remember when using this special sequence.
723 First, this is the worst collision between Python's string literals and regular
724 expression sequences. In Python's string literals, ``\b`` is the backspace
725 character, ASCII value 8. If you're not using raw strings, then Python will
726 convert the ``\b`` to a backspace, and your RE won't match as you expect it to.
727 The following example looks the same as our previous RE, but omits the ``'r'``
728 in front of the RE string. ::
729
730 >>> p = re.compile('\bclass\b')
Georg Brandl6911e3c2007-09-04 07:15:32 +0000731 >>> print(p.search('no class at all'))
Georg Brandl116aa622007-08-15 14:28:22 +0000732 None
Georg Brandl6911e3c2007-09-04 07:15:32 +0000733 >>> print(p.search('\b' + 'class' + '\b') )
Georg Brandl116aa622007-08-15 14:28:22 +0000734 <re.MatchObject instance at 80c3ee0>
735
736 Second, inside a character class, where there's no use for this assertion,
737 ``\b`` represents the backspace character, for compatibility with Python's
738 string literals.
739
740``\B``
741 Another zero-width assertion, this is the opposite of ``\b``, only matching when
742 the current position is not at a word boundary.
743
744
745Grouping
746--------
747
748Frequently you need to obtain more information than just whether the RE matched
749or not. Regular expressions are often used to dissect strings by writing a RE
750divided into several subgroups which match different components of interest.
751For example, an RFC-822 header line is divided into a header name and a value,
752separated by a ``':'``, like this::
753
754 From: author@example.com
755 User-Agent: Thunderbird 1.5.0.9 (X11/20061227)
756 MIME-Version: 1.0
757 To: editor@example.com
758
759This can be handled by writing a regular expression which matches an entire
760header line, and has one group which matches the header name, and another group
761which matches the header's value.
762
763Groups are marked by the ``'('``, ``')'`` metacharacters. ``'('`` and ``')'``
764have much the same meaning as they do in mathematical expressions; they group
765together the expressions contained inside them, and you can repeat the contents
766of a group with a repeating qualifier, such as ``*``, ``+``, ``?``, or
767``{m,n}``. For example, ``(ab)*`` will match zero or more repetitions of
768``ab``. ::
769
770 >>> p = re.compile('(ab)*')
Georg Brandl6911e3c2007-09-04 07:15:32 +0000771 >>> print(p.match('ababababab').span())
Georg Brandl116aa622007-08-15 14:28:22 +0000772 (0, 10)
773
774Groups indicated with ``'('``, ``')'`` also capture the starting and ending
775index of the text that they match; this can be retrieved by passing an argument
776to :meth:`group`, :meth:`start`, :meth:`end`, and :meth:`span`. Groups are
777numbered starting with 0. Group 0 is always present; it's the whole RE, so
778:class:`MatchObject` methods all have group 0 as their default argument. Later
779we'll see how to express groups that don't capture the span of text that they
780match. ::
781
782 >>> p = re.compile('(a)b')
783 >>> m = p.match('ab')
784 >>> m.group()
785 'ab'
786 >>> m.group(0)
787 'ab'
788
789Subgroups are numbered from left to right, from 1 upward. Groups can be nested;
790to determine the number, just count the opening parenthesis characters, going
791from left to right. ::
792
793 >>> p = re.compile('(a(b)c)d')
794 >>> m = p.match('abcd')
795 >>> m.group(0)
796 'abcd'
797 >>> m.group(1)
798 'abc'
799 >>> m.group(2)
800 'b'
801
802:meth:`group` can be passed multiple group numbers at a time, in which case it
803will return a tuple containing the corresponding values for those groups. ::
804
805 >>> m.group(2,1,2)
806 ('b', 'abc', 'b')
807
808The :meth:`groups` method returns a tuple containing the strings for all the
809subgroups, from 1 up to however many there are. ::
810
811 >>> m.groups()
812 ('abc', 'b')
813
814Backreferences in a pattern allow you to specify that the contents of an earlier
815capturing group must also be found at the current location in the string. For
816example, ``\1`` will succeed if the exact contents of group 1 can be found at
817the current position, and fails otherwise. Remember that Python's string
818literals also use a backslash followed by numbers to allow including arbitrary
819characters in a string, so be sure to use a raw string when incorporating
820backreferences in a RE.
821
822For example, the following RE detects doubled words in a string. ::
823
824 >>> p = re.compile(r'(\b\w+)\s+\1')
825 >>> p.search('Paris in the the spring').group()
826 'the the'
827
828Backreferences like this aren't often useful for just searching through a string
829--- there are few text formats which repeat data in this way --- but you'll soon
830find out that they're *very* useful when performing string substitutions.
831
832
833Non-capturing and Named Groups
834------------------------------
835
836Elaborate REs may use many groups, both to capture substrings of interest, and
837to group and structure the RE itself. In complex REs, it becomes difficult to
838keep track of the group numbers. There are two features which help with this
839problem. Both of them use a common syntax for regular expression extensions, so
840we'll look at that first.
841
842Perl 5 added several additional features to standard regular expressions, and
843the Python :mod:`re` module supports most of them. It would have been
844difficult to choose new single-keystroke metacharacters or new special sequences
845beginning with ``\`` to represent the new features without making Perl's regular
846expressions confusingly different from standard REs. If you chose ``&`` as a
847new metacharacter, for example, old expressions would be assuming that ``&`` was
848a regular character and wouldn't have escaped it by writing ``\&`` or ``[&]``.
849
850The solution chosen by the Perl developers was to use ``(?...)`` as the
851extension syntax. ``?`` immediately after a parenthesis was a syntax error
852because the ``?`` would have nothing to repeat, so this didn't introduce any
853compatibility problems. The characters immediately after the ``?`` indicate
854what extension is being used, so ``(?=foo)`` is one thing (a positive lookahead
855assertion) and ``(?:foo)`` is something else (a non-capturing group containing
856the subexpression ``foo``).
857
858Python adds an extension syntax to Perl's extension syntax. If the first
859character after the question mark is a ``P``, you know that it's an extension
860that's specific to Python. Currently there are two such extensions:
861``(?P<name>...)`` defines a named group, and ``(?P=name)`` is a backreference to
862a named group. If future versions of Perl 5 add similar features using a
863different syntax, the :mod:`re` module will be changed to support the new
864syntax, while preserving the Python-specific syntax for compatibility's sake.
865
866Now that we've looked at the general extension syntax, we can return to the
867features that simplify working with groups in complex REs. Since groups are
868numbered from left to right and a complex expression may use many groups, it can
869become difficult to keep track of the correct numbering. Modifying such a
870complex RE is annoying, too: insert a new group near the beginning and you
871change the numbers of everything that follows it.
872
873Sometimes you'll want to use a group to collect a part of a regular expression,
874but aren't interested in retrieving the group's contents. You can make this fact
875explicit by using a non-capturing group: ``(?:...)``, where you can replace the
876``...`` with any other regular expression. ::
877
878 >>> m = re.match("([abc])+", "abc")
879 >>> m.groups()
880 ('c',)
881 >>> m = re.match("(?:[abc])+", "abc")
882 >>> m.groups()
883 ()
884
885Except for the fact that you can't retrieve the contents of what the group
886matched, a non-capturing group behaves exactly the same as a capturing group;
887you can put anything inside it, repeat it with a repetition metacharacter such
888as ``*``, and nest it within other groups (capturing or non-capturing).
889``(?:...)`` is particularly useful when modifying an existing pattern, since you
890can add new groups without changing how all the other groups are numbered. It
891should be mentioned that there's no performance difference in searching between
892capturing and non-capturing groups; neither form is any faster than the other.
893
894A more significant feature is named groups: instead of referring to them by
895numbers, groups can be referenced by a name.
896
897The syntax for a named group is one of the Python-specific extensions:
898``(?P<name>...)``. *name* is, obviously, the name of the group. Named groups
899also behave exactly like capturing groups, and additionally associate a name
900with a group. The :class:`MatchObject` methods that deal with capturing groups
901all accept either integers that refer to the group by number or strings that
902contain the desired group's name. Named groups are still given numbers, so you
903can retrieve information about a group in two ways::
904
905 >>> p = re.compile(r'(?P<word>\b\w+\b)')
906 >>> m = p.search( '(((( Lots of punctuation )))' )
907 >>> m.group('word')
908 'Lots'
909 >>> m.group(1)
910 'Lots'
911
912Named groups are handy because they let you use easily-remembered names, instead
913of having to remember numbers. Here's an example RE from the :mod:`imaplib`
914module::
915
916 InternalDate = re.compile(r'INTERNALDATE "'
917 r'(?P<day>[ 123][0-9])-(?P<mon>[A-Z][a-z][a-z])-'
918 r'(?P<year>[0-9][0-9][0-9][0-9])'
919 r' (?P<hour>[0-9][0-9]):(?P<min>[0-9][0-9]):(?P<sec>[0-9][0-9])'
920 r' (?P<zonen>[-+])(?P<zoneh>[0-9][0-9])(?P<zonem>[0-9][0-9])'
921 r'"')
922
923It's obviously much easier to retrieve ``m.group('zonem')``, instead of having
924to remember to retrieve group 9.
925
926The syntax for backreferences in an expression such as ``(...)\1`` refers to the
927number of the group. There's naturally a variant that uses the group name
928instead of the number. This is another Python extension: ``(?P=name)`` indicates
929that the contents of the group called *name* should again be matched at the
930current point. The regular expression for finding doubled words,
931``(\b\w+)\s+\1`` can also be written as ``(?P<word>\b\w+)\s+(?P=word)``::
932
933 >>> p = re.compile(r'(?P<word>\b\w+)\s+(?P=word)')
934 >>> p.search('Paris in the the spring').group()
935 'the the'
936
937
938Lookahead Assertions
939--------------------
940
941Another zero-width assertion is the lookahead assertion. Lookahead assertions
942are available in both positive and negative form, and look like this:
943
944``(?=...)``
945 Positive lookahead assertion. This succeeds if the contained regular
946 expression, represented here by ``...``, successfully matches at the current
947 location, and fails otherwise. But, once the contained expression has been
948 tried, the matching engine doesn't advance at all; the rest of the pattern is
949 tried right where the assertion started.
950
951``(?!...)``
952 Negative lookahead assertion. This is the opposite of the positive assertion;
953 it succeeds if the contained expression *doesn't* match at the current position
954 in the string.
955
956To make this concrete, let's look at a case where a lookahead is useful.
957Consider a simple pattern to match a filename and split it apart into a base
958name and an extension, separated by a ``.``. For example, in ``news.rc``,
959``news`` is the base name, and ``rc`` is the filename's extension.
960
961The pattern to match this is quite simple:
962
963``.*[.].*$``
964
965Notice that the ``.`` needs to be treated specially because it's a
966metacharacter; I've put it inside a character class. Also notice the trailing
967``$``; this is added to ensure that all the rest of the string must be included
968in the extension. This regular expression matches ``foo.bar`` and
969``autoexec.bat`` and ``sendmail.cf`` and ``printers.conf``.
970
971Now, consider complicating the problem a bit; what if you want to match
972filenames where the extension is not ``bat``? Some incorrect attempts:
973
974``.*[.][^b].*$`` The first attempt above tries to exclude ``bat`` by requiring
975that the first character of the extension is not a ``b``. This is wrong,
976because the pattern also doesn't match ``foo.bar``.
977
Georg Brandl116aa622007-08-15 14:28:22 +0000978``.*[.]([^b]..|.[^a].|..[^t])$``
979
Georg Brandl116aa622007-08-15 14:28:22 +0000980The expression gets messier when you try to patch up the first solution by
981requiring one of the following cases to match: the first character of the
982extension isn't ``b``; the second character isn't ``a``; or the third character
983isn't ``t``. This accepts ``foo.bar`` and rejects ``autoexec.bat``, but it
984requires a three-letter extension and won't accept a filename with a two-letter
985extension such as ``sendmail.cf``. We'll complicate the pattern again in an
986effort to fix it.
987
988``.*[.]([^b].?.?|.[^a]?.?|..?[^t]?)$``
989
990In the third attempt, the second and third letters are all made optional in
991order to allow matching extensions shorter than three characters, such as
992``sendmail.cf``.
993
994The pattern's getting really complicated now, which makes it hard to read and
995understand. Worse, if the problem changes and you want to exclude both ``bat``
996and ``exe`` as extensions, the pattern would get even more complicated and
997confusing.
998
999A negative lookahead cuts through all this confusion:
1000
1001``.*[.](?!bat$).*$`` The negative lookahead means: if the expression ``bat``
1002doesn't match at this point, try the rest of the pattern; if ``bat$`` does
1003match, the whole pattern will fail. The trailing ``$`` is required to ensure
1004that something like ``sample.batch``, where the extension only starts with
1005``bat``, will be allowed.
1006
Georg Brandl116aa622007-08-15 14:28:22 +00001007Excluding another filename extension is now easy; simply add it as an
1008alternative inside the assertion. The following pattern excludes filenames that
1009end in either ``bat`` or ``exe``:
1010
1011``.*[.](?!bat$|exe$).*$``
1012
Georg Brandl116aa622007-08-15 14:28:22 +00001013
1014Modifying Strings
1015=================
1016
1017Up to this point, we've simply performed searches against a static string.
1018Regular expressions are also commonly used to modify strings in various ways,
1019using the following :class:`RegexObject` methods:
1020
1021+------------------+-----------------------------------------------+
1022| Method/Attribute | Purpose |
1023+==================+===============================================+
1024| ``split()`` | Split the string into a list, splitting it |
1025| | wherever the RE matches |
1026+------------------+-----------------------------------------------+
1027| ``sub()`` | Find all substrings where the RE matches, and |
1028| | replace them with a different string |
1029+------------------+-----------------------------------------------+
1030| ``subn()`` | Does the same thing as :meth:`sub`, but |
1031| | returns the new string and the number of |
1032| | replacements |
1033+------------------+-----------------------------------------------+
1034
1035
1036Splitting Strings
1037-----------------
1038
1039The :meth:`split` method of a :class:`RegexObject` splits a string apart
1040wherever the RE matches, returning a list of the pieces. It's similar to the
1041:meth:`split` method of strings but provides much more generality in the
1042delimiters that you can split by; :meth:`split` only supports splitting by
1043whitespace or by a fixed string. As you'd expect, there's a module-level
1044:func:`re.split` function, too.
1045
1046
1047.. method:: .split(string [, maxsplit=0])
1048 :noindex:
1049
1050 Split *string* by the matches of the regular expression. If capturing
1051 parentheses are used in the RE, then their contents will also be returned as
1052 part of the resulting list. If *maxsplit* is nonzero, at most *maxsplit* splits
1053 are performed.
1054
1055You can limit the number of splits made, by passing a value for *maxsplit*.
1056When *maxsplit* is nonzero, at most *maxsplit* splits will be made, and the
1057remainder of the string is returned as the final element of the list. In the
1058following example, the delimiter is any sequence of non-alphanumeric characters.
1059::
1060
1061 >>> p = re.compile(r'\W+')
1062 >>> p.split('This is a test, short and sweet, of split().')
1063 ['This', 'is', 'a', 'test', 'short', 'and', 'sweet', 'of', 'split', '']
1064 >>> p.split('This is a test, short and sweet, of split().', 3)
1065 ['This', 'is', 'a', 'test, short and sweet, of split().']
1066
1067Sometimes you're not only interested in what the text between delimiters is, but
1068also need to know what the delimiter was. If capturing parentheses are used in
1069the RE, then their values are also returned as part of the list. Compare the
1070following calls::
1071
1072 >>> p = re.compile(r'\W+')
1073 >>> p2 = re.compile(r'(\W+)')
1074 >>> p.split('This... is a test.')
1075 ['This', 'is', 'a', 'test', '']
1076 >>> p2.split('This... is a test.')
1077 ['This', '... ', 'is', ' ', 'a', ' ', 'test', '.', '']
1078
1079The module-level function :func:`re.split` adds the RE to be used as the first
1080argument, but is otherwise the same. ::
1081
1082 >>> re.split('[\W]+', 'Words, words, words.')
1083 ['Words', 'words', 'words', '']
1084 >>> re.split('([\W]+)', 'Words, words, words.')
1085 ['Words', ', ', 'words', ', ', 'words', '.', '']
1086 >>> re.split('[\W]+', 'Words, words, words.', 1)
1087 ['Words', 'words, words.']
1088
1089
1090Search and Replace
1091------------------
1092
1093Another common task is to find all the matches for a pattern, and replace them
1094with a different string. The :meth:`sub` method takes a replacement value,
1095which can be either a string or a function, and the string to be processed.
1096
1097
1098.. method:: .sub(replacement, string[, count=0])
1099 :noindex:
1100
1101 Returns the string obtained by replacing the leftmost non-overlapping
1102 occurrences of the RE in *string* by the replacement *replacement*. If the
1103 pattern isn't found, *string* is returned unchanged.
1104
1105 The optional argument *count* is the maximum number of pattern occurrences to be
1106 replaced; *count* must be a non-negative integer. The default value of 0 means
1107 to replace all occurrences.
1108
1109Here's a simple example of using the :meth:`sub` method. It replaces colour
1110names with the word ``colour``::
1111
1112 >>> p = re.compile( '(blue|white|red)')
1113 >>> p.sub( 'colour', 'blue socks and red shoes')
1114 'colour socks and colour shoes'
1115 >>> p.sub( 'colour', 'blue socks and red shoes', count=1)
1116 'colour socks and red shoes'
1117
1118The :meth:`subn` method does the same work, but returns a 2-tuple containing the
1119new string value and the number of replacements that were performed::
1120
1121 >>> p = re.compile( '(blue|white|red)')
1122 >>> p.subn( 'colour', 'blue socks and red shoes')
1123 ('colour socks and colour shoes', 2)
1124 >>> p.subn( 'colour', 'no colours at all')
1125 ('no colours at all', 0)
1126
1127Empty matches are replaced only when they're not adjacent to a previous match.
1128::
1129
1130 >>> p = re.compile('x*')
1131 >>> p.sub('-', 'abxd')
1132 '-a-b-d-'
1133
1134If *replacement* is a string, any backslash escapes in it are processed. That
1135is, ``\n`` is converted to a single newline character, ``\r`` is converted to a
1136carriage return, and so forth. Unknown escapes such as ``\j`` are left alone.
1137Backreferences, such as ``\6``, are replaced with the substring matched by the
1138corresponding group in the RE. This lets you incorporate portions of the
1139original text in the resulting replacement string.
1140
1141This example matches the word ``section`` followed by a string enclosed in
1142``{``, ``}``, and changes ``section`` to ``subsection``::
1143
1144 >>> p = re.compile('section{ ( [^}]* ) }', re.VERBOSE)
1145 >>> p.sub(r'subsection{\1}','section{First} section{second}')
1146 'subsection{First} subsection{second}'
1147
1148There's also a syntax for referring to named groups as defined by the
1149``(?P<name>...)`` syntax. ``\g<name>`` will use the substring matched by the
1150group named ``name``, and ``\g<number>`` uses the corresponding group number.
1151``\g<2>`` is therefore equivalent to ``\2``, but isn't ambiguous in a
1152replacement string such as ``\g<2>0``. (``\20`` would be interpreted as a
1153reference to group 20, not a reference to group 2 followed by the literal
1154character ``'0'``.) The following substitutions are all equivalent, but use all
1155three variations of the replacement string. ::
1156
1157 >>> p = re.compile('section{ (?P<name> [^}]* ) }', re.VERBOSE)
1158 >>> p.sub(r'subsection{\1}','section{First}')
1159 'subsection{First}'
1160 >>> p.sub(r'subsection{\g<1>}','section{First}')
1161 'subsection{First}'
1162 >>> p.sub(r'subsection{\g<name>}','section{First}')
1163 'subsection{First}'
1164
1165*replacement* can also be a function, which gives you even more control. If
1166*replacement* is a function, the function is called for every non-overlapping
1167occurrence of *pattern*. On each call, the function is passed a
1168:class:`MatchObject` argument for the match and can use this information to
1169compute the desired replacement string and return it.
1170
1171In the following example, the replacement function translates decimals into
1172hexadecimal::
1173
1174 >>> def hexrepl( match ):
1175 ... "Return the hex string for a decimal number"
1176 ... value = int( match.group() )
1177 ... return hex(value)
1178 ...
1179 >>> p = re.compile(r'\d+')
1180 >>> p.sub(hexrepl, 'Call 65490 for printing, 49152 for user code.')
1181 'Call 0xffd2 for printing, 0xc000 for user code.'
1182
1183When using the module-level :func:`re.sub` function, the pattern is passed as
1184the first argument. The pattern may be a string or a :class:`RegexObject`; if
1185you need to specify regular expression flags, you must either use a
1186:class:`RegexObject` as the first parameter, or use embedded modifiers in the
1187pattern, e.g. ``sub("(?i)b+", "x", "bbbb BBBB")`` returns ``'x x'``.
1188
1189
1190Common Problems
1191===============
1192
1193Regular expressions are a powerful tool for some applications, but in some ways
1194their behaviour isn't intuitive and at times they don't behave the way you may
1195expect them to. This section will point out some of the most common pitfalls.
1196
1197
1198Use String Methods
1199------------------
1200
1201Sometimes using the :mod:`re` module is a mistake. If you're matching a fixed
1202string, or a single character class, and you're not using any :mod:`re` features
1203such as the :const:`IGNORECASE` flag, then the full power of regular expressions
1204may not be required. Strings have several methods for performing operations with
1205fixed strings and they're usually much faster, because the implementation is a
1206single small C loop that's been optimized for the purpose, instead of the large,
1207more generalized regular expression engine.
1208
1209One example might be replacing a single fixed string with another one; for
1210example, you might replace ``word`` with ``deed``. ``re.sub()`` seems like the
1211function to use for this, but consider the :meth:`replace` method. Note that
1212:func:`replace` will also replace ``word`` inside words, turning ``swordfish``
1213into ``sdeedfish``, but the naive RE ``word`` would have done that, too. (To
1214avoid performing the substitution on parts of words, the pattern would have to
1215be ``\bword\b``, in order to require that ``word`` have a word boundary on
1216either side. This takes the job beyond :meth:`replace`'s abilities.)
1217
1218Another common task is deleting every occurrence of a single character from a
1219string or replacing it with another single character. You might do this with
1220something like ``re.sub('\n', ' ', S)``, but :meth:`translate` is capable of
1221doing both tasks and will be faster than any regular expression operation can
1222be.
1223
1224In short, before turning to the :mod:`re` module, consider whether your problem
1225can be solved with a faster and simpler string method.
1226
1227
1228match() versus search()
1229-----------------------
1230
1231The :func:`match` function only checks if the RE matches at the beginning of the
1232string while :func:`search` will scan forward through the string for a match.
1233It's important to keep this distinction in mind. Remember, :func:`match` will
1234only report a successful match which will start at 0; if the match wouldn't
1235start at zero, :func:`match` will *not* report it. ::
1236
Georg Brandl6911e3c2007-09-04 07:15:32 +00001237 >>> print(re.match('super', 'superstition').span())
Georg Brandl116aa622007-08-15 14:28:22 +00001238 (0, 5)
Georg Brandl6911e3c2007-09-04 07:15:32 +00001239 >>> print(re.match('super', 'insuperable'))
Georg Brandl116aa622007-08-15 14:28:22 +00001240 None
1241
1242On the other hand, :func:`search` will scan forward through the string,
1243reporting the first match it finds. ::
1244
Georg Brandl6911e3c2007-09-04 07:15:32 +00001245 >>> print(re.search('super', 'superstition').span())
Georg Brandl116aa622007-08-15 14:28:22 +00001246 (0, 5)
Georg Brandl6911e3c2007-09-04 07:15:32 +00001247 >>> print(re.search('super', 'insuperable').span())
Georg Brandl116aa622007-08-15 14:28:22 +00001248 (2, 7)
1249
1250Sometimes you'll be tempted to keep using :func:`re.match`, and just add ``.*``
1251to the front of your RE. Resist this temptation and use :func:`re.search`
1252instead. The regular expression compiler does some analysis of REs in order to
1253speed up the process of looking for a match. One such analysis figures out what
1254the first character of a match must be; for example, a pattern starting with
1255``Crow`` must match starting with a ``'C'``. The analysis lets the engine
1256quickly scan through the string looking for the starting character, only trying
1257the full match if a ``'C'`` is found.
1258
1259Adding ``.*`` defeats this optimization, requiring scanning to the end of the
1260string and then backtracking to find a match for the rest of the RE. Use
1261:func:`re.search` instead.
1262
1263
1264Greedy versus Non-Greedy
1265------------------------
1266
1267When repeating a regular expression, as in ``a*``, the resulting action is to
1268consume as much of the pattern as possible. This fact often bites you when
1269you're trying to match a pair of balanced delimiters, such as the angle brackets
1270surrounding an HTML tag. The naive pattern for matching a single HTML tag
1271doesn't work because of the greedy nature of ``.*``. ::
1272
1273 >>> s = '<html><head><title>Title</title>'
1274 >>> len(s)
1275 32
Georg Brandl6911e3c2007-09-04 07:15:32 +00001276 >>> print(re.match('<.*>', s).span())
Georg Brandl116aa622007-08-15 14:28:22 +00001277 (0, 32)
Georg Brandl6911e3c2007-09-04 07:15:32 +00001278 >>> print(re.match('<.*>', s).group())
Georg Brandl116aa622007-08-15 14:28:22 +00001279 <html><head><title>Title</title>
1280
1281The RE matches the ``'<'`` in ``<html>``, and the ``.*`` consumes the rest of
1282the string. There's still more left in the RE, though, and the ``>`` can't
1283match at the end of the string, so the regular expression engine has to
1284backtrack character by character until it finds a match for the ``>``. The
1285final match extends from the ``'<'`` in ``<html>`` to the ``'>'`` in
1286``</title>``, which isn't what you want.
1287
1288In this case, the solution is to use the non-greedy qualifiers ``*?``, ``+?``,
1289``??``, or ``{m,n}?``, which match as *little* text as possible. In the above
1290example, the ``'>'`` is tried immediately after the first ``'<'`` matches, and
1291when it fails, the engine advances a character at a time, retrying the ``'>'``
1292at every step. This produces just the right result::
1293
Georg Brandl6911e3c2007-09-04 07:15:32 +00001294 >>> print(re.match('<.*?>', s).group())
Georg Brandl116aa622007-08-15 14:28:22 +00001295 <html>
1296
1297(Note that parsing HTML or XML with regular expressions is painful.
1298Quick-and-dirty patterns will handle common cases, but HTML and XML have special
1299cases that will break the obvious regular expression; by the time you've written
1300a regular expression that handles all of the possible cases, the patterns will
1301be *very* complicated. Use an HTML or XML parser module for such tasks.)
1302
1303
1304Not Using re.VERBOSE
1305--------------------
1306
1307By now you've probably noticed that regular expressions are a very compact
1308notation, but they're not terribly readable. REs of moderate complexity can
1309become lengthy collections of backslashes, parentheses, and metacharacters,
1310making them difficult to read and understand.
1311
1312For such REs, specifying the ``re.VERBOSE`` flag when compiling the regular
1313expression can be helpful, because it allows you to format the regular
1314expression more clearly.
1315
1316The ``re.VERBOSE`` flag has several effects. Whitespace in the regular
1317expression that *isn't* inside a character class is ignored. This means that an
1318expression such as ``dog | cat`` is equivalent to the less readable ``dog|cat``,
1319but ``[a b]`` will still match the characters ``'a'``, ``'b'``, or a space. In
1320addition, you can also put comments inside a RE; comments extend from a ``#``
1321character to the next newline. When used with triple-quoted strings, this
1322enables REs to be formatted more neatly::
1323
1324 pat = re.compile(r"""
1325 \s* # Skip leading whitespace
1326 (?P<header>[^:]+) # Header name
1327 \s* : # Whitespace, and a colon
1328 (?P<value>.*?) # The header's value -- *? used to
1329 # lose the following trailing whitespace
1330 \s*$ # Trailing whitespace to end-of-line
1331 """, re.VERBOSE)
1332
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001333This is far more readable than::
Georg Brandl116aa622007-08-15 14:28:22 +00001334
1335 pat = re.compile(r"\s*(?P<header>[^:]+)\s*:(?P<value>.*?)\s*$")
1336
Georg Brandl116aa622007-08-15 14:28:22 +00001337
1338Feedback
1339========
1340
1341Regular expressions are a complicated topic. Did this document help you
1342understand them? Were there parts that were unclear, or Problems you
1343encountered that weren't covered here? If so, please send suggestions for
1344improvements to the author.
1345
1346The most complete book on regular expressions is almost certainly Jeffrey
1347Friedl's Mastering Regular Expressions, published by O'Reilly. Unfortunately,
1348it exclusively concentrates on Perl and Java's flavours of regular expressions,
1349and doesn't contain any Python material at all, so it won't be useful as a
1350reference for programming in Python. (The first edition covered Python's
1351now-removed :mod:`regex` module, which won't help you much.) Consider checking
1352it out from your library.
1353
1354
1355.. rubric:: Footnotes
1356
1357.. [#] Introduced in Python 2.2.2.
1358