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