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