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