blob: 87a6b1aba59f9f2e4d9fc99f7b7915f8dde01239 [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
Martin Panter1050d2d2016-07-26 11:18:21 +020077in the rest of this HOWTO.
78
79.. code-block:: none
Georg Brandl116aa622007-08-15 14:28:22 +000080
Georg Brandla2388be2011-03-06 11:07:11 +010081 . ^ $ * + ? { } [ ] \ | ( )
Georg Brandl116aa622007-08-15 14:28:22 +000082
83The first metacharacters we'll look at are ``[`` and ``]``. They're used for
84specifying a character class, which is a set of characters that you wish to
85match. Characters can be listed individually, or a range of characters can be
86indicated by giving two characters and separating them by a ``'-'``. For
87example, ``[abc]`` will match any of the characters ``a``, ``b``, or ``c``; this
88is the same as ``[a-c]``, which uses a range to express the same set of
89characters. If you wanted to match only lowercase letters, your RE would be
90``[a-z]``.
91
Georg Brandl116aa622007-08-15 14:28:22 +000092Metacharacters are not active inside classes. For example, ``[akm$]`` will
93match any of the characters ``'a'``, ``'k'``, ``'m'``, or ``'$'``; ``'$'`` is
94usually a metacharacter, but inside a character class it's stripped of its
95special nature.
96
97You can match the characters not listed within the class by :dfn:`complementing`
98the set. This is indicated by including a ``'^'`` as the first character of the
99class; ``'^'`` outside a character class will simply match the ``'^'``
100character. For example, ``[^5]`` will match any character except ``'5'``.
101
102Perhaps the most important metacharacter is the backslash, ``\``. As in Python
103string literals, the backslash can be followed by various characters to signal
104various special sequences. It's also used to escape all the metacharacters so
105you can still match them in patterns; for example, if you need to match a ``[``
106or ``\``, you can precede them with a backslash to remove their special
107meaning: ``\[`` or ``\\``.
108
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400109Some of the special sequences beginning with ``'\'`` represent
110predefined sets of characters that are often useful, such as the set
111of digits, the set of letters, or the set of anything that isn't
112whitespace.
113
114Let's take an example: ``\w`` matches any alphanumeric character. If
115the regex pattern is expressed in bytes, this is equivalent to the
116class ``[a-zA-Z0-9_]``. If the regex pattern is a string, ``\w`` will
117match all the characters marked as letters in the Unicode database
118provided by the :mod:`unicodedata` module. You can use the more
119restricted definition of ``\w`` in a string pattern by supplying the
120:const:`re.ASCII` flag when compiling the regular expression.
121
122The following list of special sequences isn't complete. For a complete
123list of sequences and expanded class definitions for Unicode string
124patterns, see the last part of :ref:`Regular Expression Syntax
125<re-syntax>` in the Standard Library reference. In general, the
126Unicode versions match any character that's in the appropriate
127category in the Unicode database.
Georg Brandl116aa622007-08-15 14:28:22 +0000128
129``\d``
130 Matches any decimal digit; this is equivalent to the class ``[0-9]``.
131
132``\D``
133 Matches any non-digit character; this is equivalent to the class ``[^0-9]``.
134
135``\s``
136 Matches any whitespace character; this is equivalent to the class ``[
137 \t\n\r\f\v]``.
138
139``\S``
140 Matches any non-whitespace character; this is equivalent to the class ``[^
141 \t\n\r\f\v]``.
142
143``\w``
144 Matches any alphanumeric character; this is equivalent to the class
145 ``[a-zA-Z0-9_]``.
146
147``\W``
148 Matches any non-alphanumeric character; this is equivalent to the class
149 ``[^a-zA-Z0-9_]``.
150
151These sequences can be included inside a character class. For example,
152``[\s,.]`` is a character class that will match any whitespace character, or
153``','`` or ``'.'``.
154
155The final metacharacter in this section is ``.``. It matches anything except a
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300156newline character, and there's an alternate mode (:const:`re.DOTALL`) where it will
157match even a newline. ``.`` is often used where you want to match "any
Georg Brandl116aa622007-08-15 14:28:22 +0000158character".
159
160
161Repeating Things
162----------------
163
164Being able to match varying sets of characters is the first thing regular
165expressions can do that isn't already possible with the methods available on
166strings. However, if that was the only additional capability of regexes, they
167wouldn't be much of an advance. Another capability is that you can specify that
168portions of the RE must be repeated a certain number of times.
169
170The first metacharacter for repeating things that we'll look at is ``*``. ``*``
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300171doesn't match the literal character ``'*'``; instead, it specifies that the
Georg Brandl116aa622007-08-15 14:28:22 +0000172previous character can be matched zero or more times, instead of exactly once.
173
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300174For example, ``ca*t`` will match ``'ct'`` (0 ``'a'`` characters), ``'cat'`` (1 ``'a'``),
175``'caaat'`` (3 ``'a'`` characters), and so forth.
Georg Brandl116aa622007-08-15 14:28:22 +0000176
177Repetitions such as ``*`` are :dfn:`greedy`; when repeating a RE, the matching
178engine will try to repeat it as many times as possible. If later portions of the
179pattern don't match, the matching engine will then back up and try again with
Benjamin Peterson8f0432f2016-02-17 23:42:46 -0800180fewer repetitions.
Georg Brandl116aa622007-08-15 14:28:22 +0000181
182A step-by-step example will make this more obvious. Let's consider the
183expression ``a[bcd]*b``. This matches the letter ``'a'``, zero or more letters
184from the class ``[bcd]``, and finally ends with a ``'b'``. Now imagine matching
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300185this RE against the string ``'abcbd'``.
Georg Brandl116aa622007-08-15 14:28:22 +0000186
187+------+-----------+---------------------------------+
188| Step | Matched | Explanation |
189+======+===========+=================================+
190| 1 | ``a`` | The ``a`` in the RE matches. |
191+------+-----------+---------------------------------+
192| 2 | ``abcbd`` | The engine matches ``[bcd]*``, |
193| | | going as far as it can, which |
194| | | is to the end of the string. |
195+------+-----------+---------------------------------+
196| 3 | *Failure* | The engine tries to match |
197| | | ``b``, but the current position |
198| | | is at the end of the string, so |
199| | | it fails. |
200+------+-----------+---------------------------------+
201| 4 | ``abcb`` | Back up, so that ``[bcd]*`` |
202| | | matches one less character. |
203+------+-----------+---------------------------------+
204| 5 | *Failure* | Try ``b`` again, but the |
205| | | current position is at the last |
206| | | character, which is a ``'d'``. |
207+------+-----------+---------------------------------+
208| 6 | ``abc`` | Back up again, so that |
209| | | ``[bcd]*`` is only matching |
210| | | ``bc``. |
211+------+-----------+---------------------------------+
212| 6 | ``abcb`` | Try ``b`` again. This time |
Christian Heimesa612dc02008-02-24 13:08:18 +0000213| | | the character at the |
Georg Brandl116aa622007-08-15 14:28:22 +0000214| | | current position is ``'b'``, so |
215| | | it succeeds. |
216+------+-----------+---------------------------------+
217
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300218The end of the RE has now been reached, and it has matched ``'abcb'``. This
Georg Brandl116aa622007-08-15 14:28:22 +0000219demonstrates how the matching engine goes as far as it can at first, and if no
220match is found it will then progressively back up and retry the rest of the RE
221again and again. It will back up until it has tried zero matches for
222``[bcd]*``, and if that subsequently fails, the engine will conclude that the
223string doesn't match the RE at all.
224
225Another repeating metacharacter is ``+``, which matches one or more times. Pay
226careful attention to the difference between ``*`` and ``+``; ``*`` matches
227*zero* or more times, so whatever's being repeated may not be present at all,
228while ``+`` requires at least *one* occurrence. To use a similar example,
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300229``ca+t`` will match ``'cat'`` (1 ``'a'``), ``'caaat'`` (3 ``'a'``\ s), but won't
230match ``'ct'``.
Georg Brandl116aa622007-08-15 14:28:22 +0000231
232There are two more repeating qualifiers. The question mark character, ``?``,
233matches either once or zero times; you can think of it as marking something as
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300234being optional. For example, ``home-?brew`` matches either ``'homebrew'`` or
235``'home-brew'``.
Georg Brandl116aa622007-08-15 14:28:22 +0000236
237The most complicated repeated qualifier is ``{m,n}``, where *m* and *n* are
238decimal integers. This qualifier means there must be at least *m* repetitions,
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300239and at most *n*. For example, ``a/{1,3}b`` will match ``'a/b'``, ``'a//b'``, and
240``'a///b'``. It won't match ``'ab'``, which has no slashes, or ``'a////b'``, which
Georg Brandl116aa622007-08-15 14:28:22 +0000241has four.
242
243You can omit either *m* or *n*; in that case, a reasonable value is assumed for
244the missing value. Omitting *m* is interpreted as a lower limit of 0, while
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300245omitting *n* results in an upper bound of infinity.
Georg Brandl116aa622007-08-15 14:28:22 +0000246
247Readers of a reductionist bent may notice that the three other qualifiers can
248all be expressed using this notation. ``{0,}`` is the same as ``*``, ``{1,}``
249is equivalent to ``+``, and ``{0,1}`` is the same as ``?``. It's better to use
250``*``, ``+``, or ``?`` when you can, simply because they're shorter and easier
251to read.
252
253
254Using Regular Expressions
255=========================
256
257Now that we've looked at some simple regular expressions, how do we actually use
258them in Python? The :mod:`re` module provides an interface to the regular
259expression engine, allowing you to compile REs into objects and then perform
260matches with them.
261
262
263Compiling Regular Expressions
264-----------------------------
265
Benjamin Peterson8cc7d882009-06-01 23:14:51 +0000266Regular expressions are compiled into pattern objects, which have
Georg Brandl116aa622007-08-15 14:28:22 +0000267methods for various operations such as searching for pattern matches or
268performing string substitutions. ::
269
270 >>> import re
271 >>> p = re.compile('ab*')
Ezio Melotti613a97e2013-11-25 22:47:01 +0200272 >>> p
273 re.compile('ab*')
Georg Brandl116aa622007-08-15 14:28:22 +0000274
275:func:`re.compile` also accepts an optional *flags* argument, used to enable
276various special features and syntax variations. We'll go over the available
277settings later, but for now a single example will do::
278
279 >>> p = re.compile('ab*', re.IGNORECASE)
280
281The RE is passed to :func:`re.compile` as a string. REs are handled as strings
282because regular expressions aren't part of the core Python language, and no
283special syntax was created for expressing them. (There are applications that
284don't need REs at all, so there's no need to bloat the language specification by
285including them.) Instead, the :mod:`re` module is simply a C extension module
286included with Python, just like the :mod:`socket` or :mod:`zlib` modules.
287
288Putting REs in strings keeps the Python language simpler, but has one
289disadvantage which is the topic of the next section.
290
291
292The Backslash Plague
293--------------------
294
295As stated earlier, regular expressions use the backslash character (``'\'``) to
296indicate special forms or to allow special characters to be used without
297invoking their special meaning. This conflicts with Python's usage of the same
298character for the same purpose in string literals.
299
300Let's say you want to write a RE that matches the string ``\section``, which
301might be found in a LaTeX file. To figure out what to write in the program
302code, start with the desired string to be matched. Next, you must escape any
303backslashes and other metacharacters by preceding them with a backslash,
304resulting in the string ``\\section``. The resulting string that must be passed
305to :func:`re.compile` must be ``\\section``. However, to express this as a
306Python string literal, both backslashes must be escaped *again*.
307
308+-------------------+------------------------------------------+
309| Characters | Stage |
310+===================+==========================================+
311| ``\section`` | Text string to be matched |
312+-------------------+------------------------------------------+
313| ``\\section`` | Escaped backslash for :func:`re.compile` |
314+-------------------+------------------------------------------+
315| ``"\\\\section"`` | Escaped backslashes for a string literal |
316+-------------------+------------------------------------------+
317
318In short, to match a literal backslash, one has to write ``'\\\\'`` as the RE
319string, because the regular expression must be ``\\``, and each backslash must
320be expressed as ``\\`` inside a regular Python string literal. In REs that
321feature backslashes repeatedly, this leads to lots of repeated backslashes and
322makes the resulting strings difficult to understand.
323
324The solution is to use Python's raw string notation for regular expressions;
325backslashes are not handled in any special way in a string literal prefixed with
326``'r'``, so ``r"\n"`` is a two-character string containing ``'\'`` and ``'n'``,
327while ``"\n"`` is a one-character string containing a newline. Regular
328expressions will often be written in Python code using this raw string notation.
329
330+-------------------+------------------+
331| Regular String | Raw string |
332+===================+==================+
333| ``"ab*"`` | ``r"ab*"`` |
334+-------------------+------------------+
335| ``"\\\\section"`` | ``r"\\section"`` |
336+-------------------+------------------+
337| ``"\\w+\\s+\\1"`` | ``r"\w+\s+\1"`` |
338+-------------------+------------------+
339
340
341Performing Matches
342------------------
343
344Once you have an object representing a compiled regular expression, what do you
Benjamin Peterson8cc7d882009-06-01 23:14:51 +0000345do with it? Pattern objects have several methods and attributes.
Georg Brandl86def6c2008-01-21 20:36:10 +0000346Only the most significant ones will be covered here; consult the :mod:`re` docs
347for a complete listing.
Georg Brandl116aa622007-08-15 14:28:22 +0000348
349+------------------+-----------------------------------------------+
350| Method/Attribute | Purpose |
351+==================+===============================================+
352| ``match()`` | Determine if the RE matches at the beginning |
353| | of the string. |
354+------------------+-----------------------------------------------+
355| ``search()`` | Scan through a string, looking for any |
356| | location where this RE matches. |
357+------------------+-----------------------------------------------+
358| ``findall()`` | Find all substrings where the RE matches, and |
359| | returns them as a list. |
360+------------------+-----------------------------------------------+
361| ``finditer()`` | Find all substrings where the RE matches, and |
Georg Brandl9afde1c2007-11-01 20:32:30 +0000362| | returns them as an :term:`iterator`. |
Georg Brandl116aa622007-08-15 14:28:22 +0000363+------------------+-----------------------------------------------+
364
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300365:meth:`~re.Pattern.match` and :meth:`~re.Pattern.search` return ``None`` if no match can be found. If
Ezio Melotti090f7be2012-12-25 18:10:49 +0200366they're successful, a :ref:`match object <match-objects>` instance is returned,
367containing information about the match: where it starts and ends, the substring
368it matched, and more.
Georg Brandl116aa622007-08-15 14:28:22 +0000369
370You can learn about this by interactively experimenting with the :mod:`re`
Terry Reedy8663e342011-01-10 21:49:11 +0000371module. If you have :mod:`tkinter` available, you may also want to look at
Éric Araujofdfaf0a2012-03-05 15:50:37 +0100372:source:`Tools/demo/redemo.py`, a demonstration program included with the
Georg Brandl116aa622007-08-15 14:28:22 +0000373Python distribution. It allows you to enter REs and strings, and displays
374whether the RE matches or fails. :file:`redemo.py` can be quite useful when
Berker Peksag79af27e2016-06-24 08:54:43 +0300375trying to debug a complicated RE.
Georg Brandl116aa622007-08-15 14:28:22 +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
Georg Brandl116aa622007-08-15 14:28:22 +0000380 >>> import re
381 >>> p = re.compile('[a-z]+')
Ezio Melotti613a97e2013-11-25 22:47:01 +0200382 >>> p
383 re.compile('[a-z]+')
Georg Brandl116aa622007-08-15 14:28:22 +0000384
385Now, you can try matching various strings against the RE ``[a-z]+``. An empty
386string shouldn't match at all, since ``+`` means 'one or more repetitions'.
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300387:meth:`~re.Pattern.match` should return ``None`` in this case, which will cause the
Georg Brandl116aa622007-08-15 14:28:22 +0000388interpreter to print no output. You can explicitly print the result of
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300389:meth:`!match` to make this clear. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000390
391 >>> p.match("")
Georg Brandl6911e3c2007-09-04 07:15:32 +0000392 >>> print(p.match(""))
Georg Brandl116aa622007-08-15 14:28:22 +0000393 None
394
395Now, let's try it on a string that it should match, such as ``tempo``. In this
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300396case, :meth:`~re.Pattern.match` will return a :ref:`match object <match-objects>`, so you
Ezio Melotti090f7be2012-12-25 18:10:49 +0200397should store the result in a variable for later use. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000398
399 >>> m = p.match('tempo')
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300400 >>> m
Serhiy Storchaka0b5e61d2017-10-04 20:09:49 +0300401 <re.Match object; span=(0, 5), match='tempo'>
Georg Brandl116aa622007-08-15 14:28:22 +0000402
Ezio Melotti090f7be2012-12-25 18:10:49 +0200403Now you can query the :ref:`match object <match-objects>` for information
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300404about the matching string. Match object instances
Ezio Melotti090f7be2012-12-25 18:10:49 +0200405also have several methods and attributes; the most important ones are:
Georg Brandl116aa622007-08-15 14:28:22 +0000406
407+------------------+--------------------------------------------+
408| Method/Attribute | Purpose |
409+==================+============================================+
410| ``group()`` | Return the string matched by the RE |
411+------------------+--------------------------------------------+
412| ``start()`` | Return the starting position of the match |
413+------------------+--------------------------------------------+
414| ``end()`` | Return the ending position of the match |
415+------------------+--------------------------------------------+
416| ``span()`` | Return a tuple containing the (start, end) |
417| | positions of the match |
418+------------------+--------------------------------------------+
419
420Trying these methods will soon clarify their meaning::
421
422 >>> m.group()
423 'tempo'
424 >>> m.start(), m.end()
425 (0, 5)
426 >>> m.span()
427 (0, 5)
428
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300429:meth:`~re.Match.group` returns the substring that was matched by the RE. :meth:`~re.Match.start`
430and :meth:`~re.Match.end` return the starting and ending index of the match. :meth:`~re.Match.span`
431returns both start and end indexes in a single tuple. Since the :meth:`~re.Pattern.match`
432method only checks if the RE matches at the start of a string, :meth:`!start`
433will always be zero. However, the :meth:`~re.Pattern.search` method of patterns
Benjamin Peterson8cc7d882009-06-01 23:14:51 +0000434scans through the string, so the match may not start at zero in that
Georg Brandl116aa622007-08-15 14:28:22 +0000435case. ::
436
Georg Brandl6911e3c2007-09-04 07:15:32 +0000437 >>> print(p.match('::: message'))
Georg Brandl116aa622007-08-15 14:28:22 +0000438 None
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300439 >>> m = p.search('::: message'); print(m)
Serhiy Storchaka0b5e61d2017-10-04 20:09:49 +0300440 <re.Match object; span=(4, 11), match='message'>
Georg Brandl116aa622007-08-15 14:28:22 +0000441 >>> m.group()
442 'message'
443 >>> m.span()
444 (4, 11)
445
Ezio Melotti090f7be2012-12-25 18:10:49 +0200446In actual programs, the most common style is to store the
447:ref:`match object <match-objects>` in a variable, and then check if it was
448``None``. This usually looks like::
Georg Brandl116aa622007-08-15 14:28:22 +0000449
450 p = re.compile( ... )
451 m = p.match( 'string goes here' )
452 if m:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000453 print('Match found: ', m.group())
Georg Brandl116aa622007-08-15 14:28:22 +0000454 else:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000455 print('No match')
Georg Brandl116aa622007-08-15 14:28:22 +0000456
Benjamin Peterson8cc7d882009-06-01 23:14:51 +0000457Two pattern methods return all of the matches for a pattern.
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300458:meth:`~re.Pattern.findall` returns a list of matching strings::
Georg Brandl116aa622007-08-15 14:28:22 +0000459
460 >>> p = re.compile('\d+')
461 >>> p.findall('12 drummers drumming, 11 pipers piping, 10 lords a-leaping')
462 ['12', '11', '10']
463
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300464:meth:`~re.Pattern.findall` has to create the entire list before it can be returned as the
465result. The :meth:`~re.Pattern.finditer` method returns a sequence of
Ezio Melotti090f7be2012-12-25 18:10:49 +0200466:ref:`match object <match-objects>` instances as an :term:`iterator`::
Georg Brandl116aa622007-08-15 14:28:22 +0000467
468 >>> iterator = p.finditer('12 drummers drumming, 11 ... 10 ...')
Ezio Melotti13bec9b2012-09-17 05:29:47 +0300469 >>> iterator #doctest: +ELLIPSIS
Terry Reedy8663e342011-01-10 21:49:11 +0000470 <callable_iterator object at 0x...>
Georg Brandl116aa622007-08-15 14:28:22 +0000471 >>> for match in iterator:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000472 ... print(match.span())
Georg Brandl116aa622007-08-15 14:28:22 +0000473 ...
474 (0, 2)
475 (22, 24)
476 (29, 31)
477
478
479Module-Level Functions
480----------------------
481
Benjamin Peterson8cc7d882009-06-01 23:14:51 +0000482You don't have to create a pattern object and call its methods; the
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400483:mod:`re` module also provides top-level functions called :func:`~re.match`,
484:func:`~re.search`, :func:`~re.findall`, :func:`~re.sub`, and so forth. These functions
485take the same arguments as the corresponding pattern method with
Georg Brandl116aa622007-08-15 14:28:22 +0000486the RE string added as the first argument, and still return either ``None`` or a
Ezio Melotti090f7be2012-12-25 18:10:49 +0200487:ref:`match object <match-objects>` instance. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000488
Georg Brandl6911e3c2007-09-04 07:15:32 +0000489 >>> print(re.match(r'From\s+', 'Fromage amk'))
Georg Brandl116aa622007-08-15 14:28:22 +0000490 None
Ezio Melotti13bec9b2012-09-17 05:29:47 +0300491 >>> re.match(r'From\s+', 'From amk Thu May 14 19:12:10 1998') #doctest: +ELLIPSIS
Serhiy Storchaka0b5e61d2017-10-04 20:09:49 +0300492 <re.Match object; span=(0, 5), match='From '>
Georg Brandl116aa622007-08-15 14:28:22 +0000493
Benjamin Peterson8cc7d882009-06-01 23:14:51 +0000494Under the hood, these functions simply create a pattern object for you
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400495and call the appropriate method on it. They also store the compiled
496object in a cache, so future calls using the same RE won't need to
497parse the pattern again and again.
Georg Brandl116aa622007-08-15 14:28:22 +0000498
499Should you use these module-level functions, or should you get the
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400500pattern and call its methods yourself? If you're accessing a regex
501within a loop, pre-compiling it will save a few function calls.
502Outside of loops, there's not much difference thanks to the internal
503cache.
Georg Brandl116aa622007-08-15 14:28:22 +0000504
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+=================================+============================================+
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400523| :const:`ASCII`, :const:`A` | Makes several escapes like ``\w``, ``\b``, |
524| | ``\s`` and ``\d`` match only on ASCII |
525| | characters with the respective property. |
526+---------------------------------+--------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000527| :const:`DOTALL`, :const:`S` | Make ``.`` match any character, including |
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300528| | newlines. |
Georg Brandl116aa622007-08-15 14:28:22 +0000529+---------------------------------+--------------------------------------------+
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300530| :const:`IGNORECASE`, :const:`I` | Do case-insensitive matches. |
Georg Brandl116aa622007-08-15 14:28:22 +0000531+---------------------------------+--------------------------------------------+
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300532| :const:`LOCALE`, :const:`L` | Do a locale-aware match. |
Georg Brandl116aa622007-08-15 14:28:22 +0000533+---------------------------------+--------------------------------------------+
534| :const:`MULTILINE`, :const:`M` | Multi-line matching, affecting ``^`` and |
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300535| | ``$``. |
Georg Brandl116aa622007-08-15 14:28:22 +0000536+---------------------------------+--------------------------------------------+
537| :const:`VERBOSE`, :const:`X` | Enable verbose REs, which can be organized |
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400538| (for 'extended') | more cleanly and understandably. |
Georg Brandlce9fbd32009-03-31 18:41:03 +0000539+---------------------------------+--------------------------------------------+
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
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300548 letters, too. Full Unicode matching also works unless the :const:`ASCII`
549 flag is used to disable non-ASCII matches. When the Unicode patterns
550 ``[a-z]`` or ``[A-Z]`` are used in combination with the :const:`IGNORECASE`
551 flag, they will match the 52 ASCII letters and 4 additional non-ASCII
552 letters: 'İ' (U+0130, Latin capital letter I with dot above), 'ı' (U+0131,
553 Latin small letter dotless i), 'Å¿' (U+017F, Latin small letter long s) and
554 'K' (U+212A, Kelvin sign). ``Spam`` will match ``'Spam'``, ``'spam'``,
555 ``'spAM'``, or ``'ſpam'`` (the latter is matched only in Unicode mode).
556 This lowercasing doesn't take the current locale into account;
557 it will if you also set the :const:`LOCALE` flag.
Georg Brandl116aa622007-08-15 14:28:22 +0000558
559
560.. data:: L
561 LOCALE
562 :noindex:
563
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300564 Make ``\w``, ``\W``, ``\b``, ``\B`` and case-insensitive matching dependent
565 on the current locale instead of the Unicode database.
Georg Brandl116aa622007-08-15 14:28:22 +0000566
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300567 Locales are a feature of the C library intended to help in writing programs
568 that take account of language differences. For example, if you're
569 processing encoded French text, you'd want to be able to write ``\w+`` to
570 match words, but ``\w`` only matches the character class ``[A-Za-z]`` in
571 bytes patterns; it won't match bytes corresponding to ``é`` or ``ç``.
572 If your system is configured properly and a French locale is selected,
573 certain C functions will tell the program that the byte corresponding to
574 ``é`` should also be considered a letter.
Georg Brandl116aa622007-08-15 14:28:22 +0000575 Setting the :const:`LOCALE` flag when compiling a regular expression will cause
576 the resulting compiled object to use these C functions for ``\w``; this is
577 slower, but also enables ``\w+`` to match French words as you'd expect.
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300578 The use of this flag is discouraged in Python 3 as the locale mechanism
579 is very unreliable, it only handles one "culture" at a time, and it only
580 works with 8-bit locales. Unicode matching is already enabled by default
581 in Python 3 for Unicode (str) patterns, and it is able to handle different
582 locales/languages.
Georg Brandl116aa622007-08-15 14:28:22 +0000583
584
585.. data:: M
586 MULTILINE
587 :noindex:
588
589 (``^`` and ``$`` haven't been explained yet; they'll be introduced in section
590 :ref:`more-metacharacters`.)
591
592 Usually ``^`` matches only at the beginning of the string, and ``$`` matches
593 only at the end of the string and immediately before the newline (if any) at the
594 end of the string. When this flag is specified, ``^`` matches at the beginning
595 of the string and at the beginning of each line within the string, immediately
596 following each newline. Similarly, the ``$`` metacharacter matches either at
597 the end of the string and at the end of each line (immediately preceding each
598 newline).
599
600
601.. data:: S
602 DOTALL
603 :noindex:
604
605 Makes the ``'.'`` special character match any character at all, including a
606 newline; without this flag, ``'.'`` will match anything *except* a newline.
607
608
Georg Brandlce9fbd32009-03-31 18:41:03 +0000609.. data:: A
610 ASCII
611 :noindex:
612
613 Make ``\w``, ``\W``, ``\b``, ``\B``, ``\s`` and ``\S`` perform ASCII-only
614 matching instead of full Unicode matching. This is only meaningful for
615 Unicode patterns, and is ignored for byte patterns.
616
617
Georg Brandl116aa622007-08-15 14:28:22 +0000618.. data:: X
619 VERBOSE
620 :noindex:
621
622 This flag allows you to write regular expressions that are more readable by
623 granting you more flexibility in how you can format them. When this flag has
624 been specified, whitespace within the RE string is ignored, except when the
625 whitespace is in a character class or preceded by an unescaped backslash; this
626 lets you organize and indent the RE more clearly. This flag also lets you put
627 comments within a RE that will be ignored by the engine; comments are marked by
628 a ``'#'`` that's neither in a character class or preceded by an unescaped
629 backslash.
630
631 For example, here's a RE that uses :const:`re.VERBOSE`; see how much easier it
632 is to read? ::
633
634 charref = re.compile(r"""
Georg Brandl06788c92009-01-03 21:31:47 +0000635 &[#] # Start of a numeric entity reference
Georg Brandl116aa622007-08-15 14:28:22 +0000636 (
637 0[0-7]+ # Octal form
638 | [0-9]+ # Decimal form
639 | x[0-9a-fA-F]+ # Hexadecimal form
640 )
641 ; # Trailing semicolon
642 """, re.VERBOSE)
643
644 Without the verbose setting, the RE would look like this::
645
646 charref = re.compile("&#(0[0-7]+"
647 "|[0-9]+"
648 "|x[0-9a-fA-F]+);")
649
650 In the above example, Python's automatic concatenation of string literals has
651 been used to break up the RE into smaller pieces, but it's still more difficult
652 to understand than the version using :const:`re.VERBOSE`.
653
654
655More Pattern Power
656==================
657
658So far we've only covered a part of the features of regular expressions. In
659this section, we'll cover some new metacharacters, and how to use groups to
660retrieve portions of the text that was matched.
661
662
663.. _more-metacharacters:
664
665More Metacharacters
666-------------------
667
668There are some metacharacters that we haven't covered yet. Most of them will be
669covered in this section.
670
671Some of the remaining metacharacters to be discussed are :dfn:`zero-width
672assertions`. They don't cause the engine to advance through the string;
673instead, they consume no characters at all, and simply succeed or fail. For
674example, ``\b`` is an assertion that the current position is located at a word
675boundary; the position isn't changed by the ``\b`` at all. This means that
676zero-width assertions should never be repeated, because if they match once at a
677given location, they can obviously be matched an infinite number of times.
678
679``|``
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300680 Alternation, or the "or" operator. If *A* and *B* are regular expressions,
681 ``A|B`` will match any string that matches either *A* or *B*. ``|`` has very
Georg Brandl116aa622007-08-15 14:28:22 +0000682 low precedence in order to make it work reasonably when you're alternating
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300683 multi-character strings. ``Crow|Servo`` will match either ``'Crow'`` or ``'Servo'``,
684 not ``'Cro'``, a ``'w'`` or an ``'S'``, and ``'ervo'``.
Georg Brandl116aa622007-08-15 14:28:22 +0000685
686 To match a literal ``'|'``, use ``\|``, or enclose it inside a character class,
687 as in ``[|]``.
688
689``^``
690 Matches at the beginning of lines. Unless the :const:`MULTILINE` flag has been
691 set, this will only match at the beginning of the string. In :const:`MULTILINE`
692 mode, this also matches immediately after each newline within the string.
693
694 For example, if you wish to match the word ``From`` only at the beginning of a
695 line, the RE to use is ``^From``. ::
696
Ezio Melotti13bec9b2012-09-17 05:29:47 +0300697 >>> print(re.search('^From', 'From Here to Eternity')) #doctest: +ELLIPSIS
Serhiy Storchaka0b5e61d2017-10-04 20:09:49 +0300698 <re.Match object; span=(0, 4), match='From'>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000699 >>> print(re.search('^From', 'Reciting From Memory'))
Georg Brandl116aa622007-08-15 14:28:22 +0000700 None
701
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300702 To match a literal ``'^'``, use ``\^``.
Georg Brandl116aa622007-08-15 14:28:22 +0000703
704``$``
705 Matches at the end of a line, which is defined as either the end of the string,
706 or any location followed by a newline character. ::
707
Ezio Melotti13bec9b2012-09-17 05:29:47 +0300708 >>> print(re.search('}$', '{block}')) #doctest: +ELLIPSIS
Serhiy Storchaka0b5e61d2017-10-04 20:09:49 +0300709 <re.Match object; span=(6, 7), match='}'>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000710 >>> print(re.search('}$', '{block} '))
Georg Brandl116aa622007-08-15 14:28:22 +0000711 None
Ezio Melotti13bec9b2012-09-17 05:29:47 +0300712 >>> print(re.search('}$', '{block}\n')) #doctest: +ELLIPSIS
Serhiy Storchaka0b5e61d2017-10-04 20:09:49 +0300713 <re.Match object; span=(6, 7), match='}'>
Georg Brandl116aa622007-08-15 14:28:22 +0000714
715 To match a literal ``'$'``, use ``\$`` or enclose it inside a character class,
716 as in ``[$]``.
717
Georg Brandl116aa622007-08-15 14:28:22 +0000718``\A``
719 Matches only at the start of the string. When not in :const:`MULTILINE` mode,
720 ``\A`` and ``^`` are effectively the same. In :const:`MULTILINE` mode, they're
721 different: ``\A`` still matches only at the beginning of the string, but ``^``
722 may match at any location inside the string that follows a newline character.
723
724``\Z``
725 Matches only at the end of the string.
726
727``\b``
728 Word boundary. This is a zero-width assertion that matches only at the
729 beginning or end of a word. A word is defined as a sequence of alphanumeric
730 characters, so the end of a word is indicated by whitespace or a
731 non-alphanumeric character.
732
733 The following example matches ``class`` only when it's a complete word; it won't
734 match when it's contained inside another word. ::
735
736 >>> p = re.compile(r'\bclass\b')
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300737 >>> print(p.search('no class at all'))
Serhiy Storchaka0b5e61d2017-10-04 20:09:49 +0300738 <re.Match object; span=(3, 8), match='class'>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000739 >>> print(p.search('the declassified algorithm'))
Georg Brandl116aa622007-08-15 14:28:22 +0000740 None
Georg Brandl6911e3c2007-09-04 07:15:32 +0000741 >>> print(p.search('one subclass is'))
Georg Brandl116aa622007-08-15 14:28:22 +0000742 None
743
744 There are two subtleties you should remember when using this special sequence.
745 First, this is the worst collision between Python's string literals and regular
746 expression sequences. In Python's string literals, ``\b`` is the backspace
747 character, ASCII value 8. If you're not using raw strings, then Python will
748 convert the ``\b`` to a backspace, and your RE won't match as you expect it to.
749 The following example looks the same as our previous RE, but omits the ``'r'``
750 in front of the RE string. ::
751
752 >>> p = re.compile('\bclass\b')
Georg Brandl6911e3c2007-09-04 07:15:32 +0000753 >>> print(p.search('no class at all'))
Georg Brandl116aa622007-08-15 14:28:22 +0000754 None
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300755 >>> print(p.search('\b' + 'class' + '\b'))
Serhiy Storchaka0b5e61d2017-10-04 20:09:49 +0300756 <re.Match object; span=(0, 7), match='\x08class\x08'>
Georg Brandl116aa622007-08-15 14:28:22 +0000757
758 Second, inside a character class, where there's no use for this assertion,
759 ``\b`` represents the backspace character, for compatibility with Python's
760 string literals.
761
762``\B``
763 Another zero-width assertion, this is the opposite of ``\b``, only matching when
764 the current position is not at a word boundary.
765
766
767Grouping
768--------
769
770Frequently you need to obtain more information than just whether the RE matched
771or not. Regular expressions are often used to dissect strings by writing a RE
772divided into several subgroups which match different components of interest.
773For example, an RFC-822 header line is divided into a header name and a value,
774separated by a ``':'``, like this::
775
776 From: author@example.com
777 User-Agent: Thunderbird 1.5.0.9 (X11/20061227)
778 MIME-Version: 1.0
779 To: editor@example.com
780
781This can be handled by writing a regular expression which matches an entire
782header line, and has one group which matches the header name, and another group
783which matches the header's value.
784
785Groups are marked by the ``'('``, ``')'`` metacharacters. ``'('`` and ``')'``
786have much the same meaning as they do in mathematical expressions; they group
787together the expressions contained inside them, and you can repeat the contents
788of a group with a repeating qualifier, such as ``*``, ``+``, ``?``, or
789``{m,n}``. For example, ``(ab)*`` will match zero or more repetitions of
790``ab``. ::
791
792 >>> p = re.compile('(ab)*')
Georg Brandl6911e3c2007-09-04 07:15:32 +0000793 >>> print(p.match('ababababab').span())
Georg Brandl116aa622007-08-15 14:28:22 +0000794 (0, 10)
795
796Groups indicated with ``'('``, ``')'`` also capture the starting and ending
797index of the text that they match; this can be retrieved by passing an argument
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300798to :meth:`~re.Match.group`, :meth:`~re.Match.start`, :meth:`~re.Match.end`, and
799:meth:`~re.Match.span`. Groups are
Georg Brandl116aa622007-08-15 14:28:22 +0000800numbered starting with 0. Group 0 is always present; it's the whole RE, so
Ezio Melotti090f7be2012-12-25 18:10:49 +0200801:ref:`match object <match-objects>` methods all have group 0 as their default
802argument. Later we'll see how to express groups that don't capture the span
803of text that they match. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000804
805 >>> p = re.compile('(a)b')
806 >>> m = p.match('ab')
807 >>> m.group()
808 'ab'
809 >>> m.group(0)
810 'ab'
811
812Subgroups are numbered from left to right, from 1 upward. Groups can be nested;
813to determine the number, just count the opening parenthesis characters, going
814from left to right. ::
815
816 >>> p = re.compile('(a(b)c)d')
817 >>> m = p.match('abcd')
818 >>> m.group(0)
819 'abcd'
820 >>> m.group(1)
821 'abc'
822 >>> m.group(2)
823 'b'
824
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300825:meth:`~re.Match.group` can be passed multiple group numbers at a time, in which case it
Georg Brandl116aa622007-08-15 14:28:22 +0000826will return a tuple containing the corresponding values for those groups. ::
827
828 >>> m.group(2,1,2)
829 ('b', 'abc', 'b')
830
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300831The :meth:`~re.Match.groups` method returns a tuple containing the strings for all the
Georg Brandl116aa622007-08-15 14:28:22 +0000832subgroups, from 1 up to however many there are. ::
833
834 >>> m.groups()
835 ('abc', 'b')
836
837Backreferences in a pattern allow you to specify that the contents of an earlier
838capturing group must also be found at the current location in the string. For
839example, ``\1`` will succeed if the exact contents of group 1 can be found at
840the current position, and fails otherwise. Remember that Python's string
841literals also use a backslash followed by numbers to allow including arbitrary
842characters in a string, so be sure to use a raw string when incorporating
843backreferences in a RE.
844
845For example, the following RE detects doubled words in a string. ::
846
Mandeep Bhutani610e5af2017-11-24 22:56:00 -0600847 >>> p = re.compile(r'\b(\w+)\s+\1\b')
Georg Brandl116aa622007-08-15 14:28:22 +0000848 >>> p.search('Paris in the the spring').group()
849 'the the'
850
851Backreferences like this aren't often useful for just searching through a string
852--- there are few text formats which repeat data in this way --- but you'll soon
853find out that they're *very* useful when performing string substitutions.
854
855
856Non-capturing and Named Groups
857------------------------------
858
859Elaborate REs may use many groups, both to capture substrings of interest, and
860to group and structure the RE itself. In complex REs, it becomes difficult to
861keep track of the group numbers. There are two features which help with this
862problem. Both of them use a common syntax for regular expression extensions, so
863we'll look at that first.
864
Donald Stufft8b852f12014-05-20 12:58:38 -0400865Perl 5 is well known for its powerful additions to standard regular expressions.
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400866For these new features the Perl developers couldn't choose new single-keystroke metacharacters
867or new special sequences beginning with ``\`` without making Perl's regular
868expressions confusingly different from standard REs. If they chose ``&`` as a
Georg Brandl116aa622007-08-15 14:28:22 +0000869new metacharacter, for example, old expressions would be assuming that ``&`` was
870a regular character and wouldn't have escaped it by writing ``\&`` or ``[&]``.
871
872The solution chosen by the Perl developers was to use ``(?...)`` as the
873extension syntax. ``?`` immediately after a parenthesis was a syntax error
874because the ``?`` would have nothing to repeat, so this didn't introduce any
875compatibility problems. The characters immediately after the ``?`` indicate
876what extension is being used, so ``(?=foo)`` is one thing (a positive lookahead
877assertion) and ``(?:foo)`` is something else (a non-capturing group containing
878the subexpression ``foo``).
879
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400880Python supports several of Perl's extensions and adds an extension
881syntax to Perl's extension syntax. If the first character after the
882question mark is a ``P``, you know that it's an extension that's
883specific to Python.
Georg Brandl116aa622007-08-15 14:28:22 +0000884
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400885Now that we've looked at the general extension syntax, we can return
886to the features that simplify working with groups in complex REs.
Georg Brandl116aa622007-08-15 14:28:22 +0000887
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400888Sometimes you'll want to use a group to denote a part of a regular expression,
Georg Brandl116aa622007-08-15 14:28:22 +0000889but aren't interested in retrieving the group's contents. You can make this fact
890explicit by using a non-capturing group: ``(?:...)``, where you can replace the
891``...`` with any other regular expression. ::
892
893 >>> m = re.match("([abc])+", "abc")
894 >>> m.groups()
895 ('c',)
896 >>> m = re.match("(?:[abc])+", "abc")
897 >>> m.groups()
898 ()
899
900Except for the fact that you can't retrieve the contents of what the group
901matched, a non-capturing group behaves exactly the same as a capturing group;
902you can put anything inside it, repeat it with a repetition metacharacter such
903as ``*``, and nest it within other groups (capturing or non-capturing).
904``(?:...)`` is particularly useful when modifying an existing pattern, since you
905can add new groups without changing how all the other groups are numbered. It
906should be mentioned that there's no performance difference in searching between
907capturing and non-capturing groups; neither form is any faster than the other.
908
909A more significant feature is named groups: instead of referring to them by
910numbers, groups can be referenced by a name.
911
912The syntax for a named group is one of the Python-specific extensions:
913``(?P<name>...)``. *name* is, obviously, the name of the group. Named groups
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400914behave exactly like capturing groups, and additionally associate a name
Ezio Melotti090f7be2012-12-25 18:10:49 +0200915with a group. The :ref:`match object <match-objects>` methods that deal with
916capturing groups all accept either integers that refer to the group by number
917or strings that contain the desired group's name. Named groups are still
918given numbers, so you can retrieve information about a group in two ways::
Georg Brandl116aa622007-08-15 14:28:22 +0000919
920 >>> p = re.compile(r'(?P<word>\b\w+\b)')
921 >>> m = p.search( '(((( Lots of punctuation )))' )
922 >>> m.group('word')
923 'Lots'
924 >>> m.group(1)
925 'Lots'
926
927Named groups are handy because they let you use easily-remembered names, instead
928of having to remember numbers. Here's an example RE from the :mod:`imaplib`
929module::
930
931 InternalDate = re.compile(r'INTERNALDATE "'
932 r'(?P<day>[ 123][0-9])-(?P<mon>[A-Z][a-z][a-z])-'
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000933 r'(?P<year>[0-9][0-9][0-9][0-9])'
Georg Brandl116aa622007-08-15 14:28:22 +0000934 r' (?P<hour>[0-9][0-9]):(?P<min>[0-9][0-9]):(?P<sec>[0-9][0-9])'
935 r' (?P<zonen>[-+])(?P<zoneh>[0-9][0-9])(?P<zonem>[0-9][0-9])'
936 r'"')
937
938It's obviously much easier to retrieve ``m.group('zonem')``, instead of having
939to remember to retrieve group 9.
940
941The syntax for backreferences in an expression such as ``(...)\1`` refers to the
942number of the group. There's naturally a variant that uses the group name
943instead of the number. This is another Python extension: ``(?P=name)`` indicates
944that the contents of the group called *name* should again be matched at the
945current point. The regular expression for finding doubled words,
Mandeep Bhutani610e5af2017-11-24 22:56:00 -0600946``\b(\w+)\s+\1\b`` can also be written as ``\b(?P<word>\w+)\s+(?P=word)\b``::
Georg Brandl116aa622007-08-15 14:28:22 +0000947
Mandeep Bhutani610e5af2017-11-24 22:56:00 -0600948 >>> p = re.compile(r'\b(?P<word>\w+)\s+(?P=word)\b')
Georg Brandl116aa622007-08-15 14:28:22 +0000949 >>> p.search('Paris in the the spring').group()
950 'the the'
951
952
953Lookahead Assertions
954--------------------
955
956Another zero-width assertion is the lookahead assertion. Lookahead assertions
957are available in both positive and negative form, and look like this:
958
959``(?=...)``
960 Positive lookahead assertion. This succeeds if the contained regular
961 expression, represented here by ``...``, successfully matches at the current
962 location, and fails otherwise. But, once the contained expression has been
963 tried, the matching engine doesn't advance at all; the rest of the pattern is
964 tried right where the assertion started.
965
966``(?!...)``
967 Negative lookahead assertion. This is the opposite of the positive assertion;
968 it succeeds if the contained expression *doesn't* match at the current position
969 in the string.
970
971To make this concrete, let's look at a case where a lookahead is useful.
972Consider a simple pattern to match a filename and split it apart into a base
973name and an extension, separated by a ``.``. For example, in ``news.rc``,
974``news`` is the base name, and ``rc`` is the filename's extension.
975
976The pattern to match this is quite simple:
977
978``.*[.].*$``
979
980Notice that the ``.`` needs to be treated specially because it's a
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400981metacharacter, so it's inside a character class to only match that
982specific character. Also notice the trailing ``$``; this is added to
983ensure that all the rest of the string must be included in the
984extension. This regular expression matches ``foo.bar`` and
Georg Brandl116aa622007-08-15 14:28:22 +0000985``autoexec.bat`` and ``sendmail.cf`` and ``printers.conf``.
986
987Now, consider complicating the problem a bit; what if you want to match
988filenames where the extension is not ``bat``? Some incorrect attempts:
989
990``.*[.][^b].*$`` The first attempt above tries to exclude ``bat`` by requiring
991that the first character of the extension is not a ``b``. This is wrong,
992because the pattern also doesn't match ``foo.bar``.
993
Georg Brandl116aa622007-08-15 14:28:22 +0000994``.*[.]([^b]..|.[^a].|..[^t])$``
995
Georg Brandl116aa622007-08-15 14:28:22 +0000996The expression gets messier when you try to patch up the first solution by
997requiring one of the following cases to match: the first character of the
998extension isn't ``b``; the second character isn't ``a``; or the third character
999isn't ``t``. This accepts ``foo.bar`` and rejects ``autoexec.bat``, but it
1000requires a three-letter extension and won't accept a filename with a two-letter
1001extension such as ``sendmail.cf``. We'll complicate the pattern again in an
1002effort to fix it.
1003
1004``.*[.]([^b].?.?|.[^a]?.?|..?[^t]?)$``
1005
1006In the third attempt, the second and third letters are all made optional in
1007order to allow matching extensions shorter than three characters, such as
1008``sendmail.cf``.
1009
1010The pattern's getting really complicated now, which makes it hard to read and
1011understand. Worse, if the problem changes and you want to exclude both ``bat``
1012and ``exe`` as extensions, the pattern would get even more complicated and
1013confusing.
1014
1015A negative lookahead cuts through all this confusion:
1016
Ezio Melotti84c63e82016-01-12 00:09:13 +02001017``.*[.](?!bat$)[^.]*$`` The negative lookahead means: if the expression ``bat``
Georg Brandl116aa622007-08-15 14:28:22 +00001018doesn't match at this point, try the rest of the pattern; if ``bat$`` does
1019match, the whole pattern will fail. The trailing ``$`` is required to ensure
1020that something like ``sample.batch``, where the extension only starts with
Ezio Melotti84c63e82016-01-12 00:09:13 +02001021``bat``, will be allowed. The ``[^.]*`` makes sure that the pattern works
1022when there are multiple dots in the filename.
Georg Brandl116aa622007-08-15 14:28:22 +00001023
Georg Brandl116aa622007-08-15 14:28:22 +00001024Excluding another filename extension is now easy; simply add it as an
1025alternative inside the assertion. The following pattern excludes filenames that
1026end in either ``bat`` or ``exe``:
1027
Ezio Melotti84c63e82016-01-12 00:09:13 +02001028``.*[.](?!bat$|exe$)[^.]*$``
Georg Brandl116aa622007-08-15 14:28:22 +00001029
Georg Brandl116aa622007-08-15 14:28:22 +00001030
1031Modifying Strings
1032=================
1033
1034Up to this point, we've simply performed searches against a static string.
1035Regular expressions are also commonly used to modify strings in various ways,
Benjamin Peterson8cc7d882009-06-01 23:14:51 +00001036using the following pattern methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001037
1038+------------------+-----------------------------------------------+
1039| Method/Attribute | Purpose |
1040+==================+===============================================+
1041| ``split()`` | Split the string into a list, splitting it |
1042| | wherever the RE matches |
1043+------------------+-----------------------------------------------+
1044| ``sub()`` | Find all substrings where the RE matches, and |
1045| | replace them with a different string |
1046+------------------+-----------------------------------------------+
Serhiy Storchakacd195e22017-10-14 11:14:26 +03001047| ``subn()`` | Does the same thing as :meth:`!sub`, but |
Georg Brandl116aa622007-08-15 14:28:22 +00001048| | returns the new string and the number of |
1049| | replacements |
1050+------------------+-----------------------------------------------+
1051
1052
1053Splitting Strings
1054-----------------
1055
Serhiy Storchakacd195e22017-10-14 11:14:26 +03001056The :meth:`~re.Pattern.split` method of a pattern splits a string apart
Georg Brandl116aa622007-08-15 14:28:22 +00001057wherever the RE matches, returning a list of the pieces. It's similar to the
Serhiy Storchakacd195e22017-10-14 11:14:26 +03001058:meth:`~str.split` method of strings but provides much more generality in the
1059delimiters that you can split by; string :meth:`!split` only supports splitting by
Georg Brandl116aa622007-08-15 14:28:22 +00001060whitespace or by a fixed string. As you'd expect, there's a module-level
1061:func:`re.split` function, too.
1062
1063
1064.. method:: .split(string [, maxsplit=0])
1065 :noindex:
1066
1067 Split *string* by the matches of the regular expression. If capturing
1068 parentheses are used in the RE, then their contents will also be returned as
1069 part of the resulting list. If *maxsplit* is nonzero, at most *maxsplit* splits
1070 are performed.
1071
1072You can limit the number of splits made, by passing a value for *maxsplit*.
1073When *maxsplit* is nonzero, at most *maxsplit* splits will be made, and the
1074remainder of the string is returned as the final element of the list. In the
1075following example, the delimiter is any sequence of non-alphanumeric characters.
1076::
1077
1078 >>> p = re.compile(r'\W+')
1079 >>> p.split('This is a test, short and sweet, of split().')
1080 ['This', 'is', 'a', 'test', 'short', 'and', 'sweet', 'of', 'split', '']
1081 >>> p.split('This is a test, short and sweet, of split().', 3)
1082 ['This', 'is', 'a', 'test, short and sweet, of split().']
1083
1084Sometimes you're not only interested in what the text between delimiters is, but
1085also need to know what the delimiter was. If capturing parentheses are used in
1086the RE, then their values are also returned as part of the list. Compare the
1087following calls::
1088
1089 >>> p = re.compile(r'\W+')
1090 >>> p2 = re.compile(r'(\W+)')
1091 >>> p.split('This... is a test.')
1092 ['This', 'is', 'a', 'test', '']
1093 >>> p2.split('This... is a test.')
1094 ['This', '... ', 'is', ' ', 'a', ' ', 'test', '.', '']
1095
1096The module-level function :func:`re.split` adds the RE to be used as the first
1097argument, but is otherwise the same. ::
1098
1099 >>> re.split('[\W]+', 'Words, words, words.')
1100 ['Words', 'words', 'words', '']
1101 >>> re.split('([\W]+)', 'Words, words, words.')
1102 ['Words', ', ', 'words', ', ', 'words', '.', '']
1103 >>> re.split('[\W]+', 'Words, words, words.', 1)
1104 ['Words', 'words, words.']
1105
1106
1107Search and Replace
1108------------------
1109
1110Another common task is to find all the matches for a pattern, and replace them
Serhiy Storchakacd195e22017-10-14 11:14:26 +03001111with a different string. The :meth:`~re.Pattern.sub` method takes a replacement value,
Georg Brandl116aa622007-08-15 14:28:22 +00001112which can be either a string or a function, and the string to be processed.
1113
Georg Brandl116aa622007-08-15 14:28:22 +00001114.. method:: .sub(replacement, string[, count=0])
1115 :noindex:
1116
1117 Returns the string obtained by replacing the leftmost non-overlapping
1118 occurrences of the RE in *string* by the replacement *replacement*. If the
1119 pattern isn't found, *string* is returned unchanged.
1120
1121 The optional argument *count* is the maximum number of pattern occurrences to be
1122 replaced; *count* must be a non-negative integer. The default value of 0 means
1123 to replace all occurrences.
1124
Serhiy Storchakacd195e22017-10-14 11:14:26 +03001125Here's a simple example of using the :meth:`~re.Pattern.sub` method. It replaces colour
Georg Brandl116aa622007-08-15 14:28:22 +00001126names with the word ``colour``::
1127
Serhiy Storchakadba90392016-05-10 12:01:23 +03001128 >>> p = re.compile('(blue|white|red)')
1129 >>> p.sub('colour', 'blue socks and red shoes')
Georg Brandl116aa622007-08-15 14:28:22 +00001130 'colour socks and colour shoes'
Serhiy Storchakadba90392016-05-10 12:01:23 +03001131 >>> p.sub('colour', 'blue socks and red shoes', count=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001132 'colour socks and red shoes'
1133
Serhiy Storchakacd195e22017-10-14 11:14:26 +03001134The :meth:`~re.Pattern.subn` method does the same work, but returns a 2-tuple containing the
Georg Brandl116aa622007-08-15 14:28:22 +00001135new string value and the number of replacements that were performed::
1136
Serhiy Storchakadba90392016-05-10 12:01:23 +03001137 >>> p = re.compile('(blue|white|red)')
1138 >>> p.subn('colour', 'blue socks and red shoes')
Georg Brandl116aa622007-08-15 14:28:22 +00001139 ('colour socks and colour shoes', 2)
Serhiy Storchakadba90392016-05-10 12:01:23 +03001140 >>> p.subn('colour', 'no colours at all')
Georg Brandl116aa622007-08-15 14:28:22 +00001141 ('no colours at all', 0)
1142
Serhiy Storchakafbb490f2018-01-04 11:06:13 +02001143Empty matches are replaced only when they're not adjacent to a previous empty match.
Georg Brandl116aa622007-08-15 14:28:22 +00001144::
1145
1146 >>> p = re.compile('x*')
1147 >>> p.sub('-', 'abxd')
Serhiy Storchakafbb490f2018-01-04 11:06:13 +02001148 '-a-b--d-'
Georg Brandl116aa622007-08-15 14:28:22 +00001149
1150If *replacement* is a string, any backslash escapes in it are processed. That
1151is, ``\n`` is converted to a single newline character, ``\r`` is converted to a
Serhiy Storchakaa54aae02015-03-24 22:58:14 +02001152carriage return, and so forth. Unknown escapes such as ``\&`` are left alone.
Georg Brandl116aa622007-08-15 14:28:22 +00001153Backreferences, such as ``\6``, are replaced with the substring matched by the
1154corresponding group in the RE. This lets you incorporate portions of the
1155original text in the resulting replacement string.
1156
1157This example matches the word ``section`` followed by a string enclosed in
1158``{``, ``}``, and changes ``section`` to ``subsection``::
1159
1160 >>> p = re.compile('section{ ( [^}]* ) }', re.VERBOSE)
1161 >>> p.sub(r'subsection{\1}','section{First} section{second}')
1162 'subsection{First} subsection{second}'
1163
1164There's also a syntax for referring to named groups as defined by the
1165``(?P<name>...)`` syntax. ``\g<name>`` will use the substring matched by the
1166group named ``name``, and ``\g<number>`` uses the corresponding group number.
1167``\g<2>`` is therefore equivalent to ``\2``, but isn't ambiguous in a
1168replacement string such as ``\g<2>0``. (``\20`` would be interpreted as a
1169reference to group 20, not a reference to group 2 followed by the literal
1170character ``'0'``.) The following substitutions are all equivalent, but use all
1171three variations of the replacement string. ::
1172
1173 >>> p = re.compile('section{ (?P<name> [^}]* ) }', re.VERBOSE)
1174 >>> p.sub(r'subsection{\1}','section{First}')
1175 'subsection{First}'
1176 >>> p.sub(r'subsection{\g<1>}','section{First}')
1177 'subsection{First}'
1178 >>> p.sub(r'subsection{\g<name>}','section{First}')
1179 'subsection{First}'
1180
1181*replacement* can also be a function, which gives you even more control. If
1182*replacement* is a function, the function is called for every non-overlapping
Ezio Melotti090f7be2012-12-25 18:10:49 +02001183occurrence of *pattern*. On each call, the function is passed a
1184:ref:`match object <match-objects>` argument for the match and can use this
1185information to compute the desired replacement string and return it.
Georg Brandl116aa622007-08-15 14:28:22 +00001186
Ezio Melotti090f7be2012-12-25 18:10:49 +02001187In the following example, the replacement function translates decimals into
Georg Brandl116aa622007-08-15 14:28:22 +00001188hexadecimal::
1189
Ezio Melotti13bec9b2012-09-17 05:29:47 +03001190 >>> def hexrepl(match):
Georg Brandl116aa622007-08-15 14:28:22 +00001191 ... "Return the hex string for a decimal number"
Ezio Melotti13bec9b2012-09-17 05:29:47 +03001192 ... value = int(match.group())
Georg Brandl116aa622007-08-15 14:28:22 +00001193 ... return hex(value)
1194 ...
1195 >>> p = re.compile(r'\d+')
1196 >>> p.sub(hexrepl, 'Call 65490 for printing, 49152 for user code.')
1197 'Call 0xffd2 for printing, 0xc000 for user code.'
1198
1199When using the module-level :func:`re.sub` function, the pattern is passed as
Benjamin Peterson8cc7d882009-06-01 23:14:51 +00001200the first argument. The pattern may be provided as an object or as a string; if
Georg Brandl116aa622007-08-15 14:28:22 +00001201you need to specify regular expression flags, you must either use a
Benjamin Peterson8cc7d882009-06-01 23:14:51 +00001202pattern object as the first parameter, or use embedded modifiers in the
1203pattern string, e.g. ``sub("(?i)b+", "x", "bbbb BBBB")`` returns ``'x x'``.
Georg Brandl116aa622007-08-15 14:28:22 +00001204
1205
1206Common Problems
1207===============
1208
1209Regular expressions are a powerful tool for some applications, but in some ways
1210their behaviour isn't intuitive and at times they don't behave the way you may
1211expect them to. This section will point out some of the most common pitfalls.
1212
1213
1214Use String Methods
1215------------------
1216
1217Sometimes using the :mod:`re` module is a mistake. If you're matching a fixed
1218string, or a single character class, and you're not using any :mod:`re` features
Serhiy Storchakacd195e22017-10-14 11:14:26 +03001219such as the :const:`~re.IGNORECASE` flag, then the full power of regular expressions
Georg Brandl116aa622007-08-15 14:28:22 +00001220may not be required. Strings have several methods for performing operations with
1221fixed strings and they're usually much faster, because the implementation is a
1222single small C loop that's been optimized for the purpose, instead of the large,
1223more generalized regular expression engine.
1224
1225One example might be replacing a single fixed string with another one; for
Serhiy Storchakacd195e22017-10-14 11:14:26 +03001226example, you might replace ``word`` with ``deed``. :func:`re.sub` seems like the
1227function to use for this, but consider the :meth:`~str.replace` method. Note that
1228:meth:`!replace` will also replace ``word`` inside words, turning ``swordfish``
Georg Brandl116aa622007-08-15 14:28:22 +00001229into ``sdeedfish``, but the naive RE ``word`` would have done that, too. (To
1230avoid performing the substitution on parts of words, the pattern would have to
1231be ``\bword\b``, in order to require that ``word`` have a word boundary on
Serhiy Storchakacd195e22017-10-14 11:14:26 +03001232either side. This takes the job beyond :meth:`!replace`'s abilities.)
Georg Brandl116aa622007-08-15 14:28:22 +00001233
1234Another common task is deleting every occurrence of a single character from a
1235string or replacing it with another single character. You might do this with
Serhiy Storchakacd195e22017-10-14 11:14:26 +03001236something like ``re.sub('\n', ' ', S)``, but :meth:`~str.translate` is capable of
Georg Brandl116aa622007-08-15 14:28:22 +00001237doing both tasks and will be faster than any regular expression operation can
1238be.
1239
1240In short, before turning to the :mod:`re` module, consider whether your problem
1241can be solved with a faster and simpler string method.
1242
1243
1244match() versus search()
1245-----------------------
1246
Serhiy Storchakacd195e22017-10-14 11:14:26 +03001247The :func:`~re.match` function only checks if the RE matches at the beginning of the
1248string while :func:`~re.search` will scan forward through the string for a match.
1249It's important to keep this distinction in mind. Remember, :func:`!match` will
Georg Brandl116aa622007-08-15 14:28:22 +00001250only report a successful match which will start at 0; if the match wouldn't
Serhiy Storchakacd195e22017-10-14 11:14:26 +03001251start at zero, :func:`!match` will *not* report it. ::
Georg Brandl116aa622007-08-15 14:28:22 +00001252
Georg Brandl6911e3c2007-09-04 07:15:32 +00001253 >>> print(re.match('super', 'superstition').span())
Georg Brandl116aa622007-08-15 14:28:22 +00001254 (0, 5)
Georg Brandl6911e3c2007-09-04 07:15:32 +00001255 >>> print(re.match('super', 'insuperable'))
Georg Brandl116aa622007-08-15 14:28:22 +00001256 None
1257
Serhiy Storchakacd195e22017-10-14 11:14:26 +03001258On the other hand, :func:`~re.search` will scan forward through the string,
Georg Brandl116aa622007-08-15 14:28:22 +00001259reporting the first match it finds. ::
1260
Georg Brandl6911e3c2007-09-04 07:15:32 +00001261 >>> print(re.search('super', 'superstition').span())
Georg Brandl116aa622007-08-15 14:28:22 +00001262 (0, 5)
Georg Brandl6911e3c2007-09-04 07:15:32 +00001263 >>> print(re.search('super', 'insuperable').span())
Georg Brandl116aa622007-08-15 14:28:22 +00001264 (2, 7)
1265
1266Sometimes you'll be tempted to keep using :func:`re.match`, and just add ``.*``
1267to the front of your RE. Resist this temptation and use :func:`re.search`
1268instead. The regular expression compiler does some analysis of REs in order to
1269speed up the process of looking for a match. One such analysis figures out what
1270the first character of a match must be; for example, a pattern starting with
1271``Crow`` must match starting with a ``'C'``. The analysis lets the engine
1272quickly scan through the string looking for the starting character, only trying
1273the full match if a ``'C'`` is found.
1274
1275Adding ``.*`` defeats this optimization, requiring scanning to the end of the
1276string and then backtracking to find a match for the rest of the RE. Use
1277:func:`re.search` instead.
1278
1279
1280Greedy versus Non-Greedy
1281------------------------
1282
1283When repeating a regular expression, as in ``a*``, the resulting action is to
1284consume as much of the pattern as possible. This fact often bites you when
1285you're trying to match a pair of balanced delimiters, such as the angle brackets
1286surrounding an HTML tag. The naive pattern for matching a single HTML tag
1287doesn't work because of the greedy nature of ``.*``. ::
1288
1289 >>> s = '<html><head><title>Title</title>'
1290 >>> len(s)
1291 32
Georg Brandl6911e3c2007-09-04 07:15:32 +00001292 >>> print(re.match('<.*>', s).span())
Georg Brandl116aa622007-08-15 14:28:22 +00001293 (0, 32)
Georg Brandl6911e3c2007-09-04 07:15:32 +00001294 >>> print(re.match('<.*>', s).group())
Georg Brandl116aa622007-08-15 14:28:22 +00001295 <html><head><title>Title</title>
1296
Serhiy Storchakacd195e22017-10-14 11:14:26 +03001297The RE matches the ``'<'`` in ``'<html>'``, and the ``.*`` consumes the rest of
Georg Brandl116aa622007-08-15 14:28:22 +00001298the string. There's still more left in the RE, though, and the ``>`` can't
1299match at the end of the string, so the regular expression engine has to
1300backtrack character by character until it finds a match for the ``>``. The
Serhiy Storchakacd195e22017-10-14 11:14:26 +03001301final match extends from the ``'<'`` in ``'<html>'`` to the ``'>'`` in
1302``'</title>'``, which isn't what you want.
Georg Brandl116aa622007-08-15 14:28:22 +00001303
1304In this case, the solution is to use the non-greedy qualifiers ``*?``, ``+?``,
1305``??``, or ``{m,n}?``, which match as *little* text as possible. In the above
1306example, the ``'>'`` is tried immediately after the first ``'<'`` matches, and
1307when it fails, the engine advances a character at a time, retrying the ``'>'``
1308at every step. This produces just the right result::
1309
Georg Brandl6911e3c2007-09-04 07:15:32 +00001310 >>> print(re.match('<.*?>', s).group())
Georg Brandl116aa622007-08-15 14:28:22 +00001311 <html>
1312
1313(Note that parsing HTML or XML with regular expressions is painful.
1314Quick-and-dirty patterns will handle common cases, but HTML and XML have special
1315cases that will break the obvious regular expression; by the time you've written
1316a regular expression that handles all of the possible cases, the patterns will
1317be *very* complicated. Use an HTML or XML parser module for such tasks.)
1318
1319
Terry Reedy8663e342011-01-10 21:49:11 +00001320Using re.VERBOSE
1321----------------
Georg Brandl116aa622007-08-15 14:28:22 +00001322
1323By now you've probably noticed that regular expressions are a very compact
1324notation, but they're not terribly readable. REs of moderate complexity can
1325become lengthy collections of backslashes, parentheses, and metacharacters,
1326making them difficult to read and understand.
1327
Serhiy Storchakacd195e22017-10-14 11:14:26 +03001328For such REs, specifying the :const:`re.VERBOSE` flag when compiling the regular
Georg Brandl116aa622007-08-15 14:28:22 +00001329expression can be helpful, because it allows you to format the regular
1330expression more clearly.
1331
1332The ``re.VERBOSE`` flag has several effects. Whitespace in the regular
1333expression that *isn't* inside a character class is ignored. This means that an
1334expression such as ``dog | cat`` is equivalent to the less readable ``dog|cat``,
1335but ``[a b]`` will still match the characters ``'a'``, ``'b'``, or a space. In
1336addition, you can also put comments inside a RE; comments extend from a ``#``
1337character to the next newline. When used with triple-quoted strings, this
1338enables REs to be formatted more neatly::
1339
1340 pat = re.compile(r"""
1341 \s* # Skip leading whitespace
1342 (?P<header>[^:]+) # Header name
1343 \s* : # Whitespace, and a colon
1344 (?P<value>.*?) # The header's value -- *? used to
1345 # lose the following trailing whitespace
1346 \s*$ # Trailing whitespace to end-of-line
1347 """, re.VERBOSE)
1348
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001349This is far more readable than::
Georg Brandl116aa622007-08-15 14:28:22 +00001350
1351 pat = re.compile(r"\s*(?P<header>[^:]+)\s*:(?P<value>.*?)\s*$")
1352
Georg Brandl116aa622007-08-15 14:28:22 +00001353
1354Feedback
1355========
1356
1357Regular expressions are a complicated topic. Did this document help you
1358understand them? Were there parts that were unclear, or Problems you
1359encountered that weren't covered here? If so, please send suggestions for
1360improvements to the author.
1361
1362The most complete book on regular expressions is almost certainly Jeffrey
1363Friedl's Mastering Regular Expressions, published by O'Reilly. Unfortunately,
1364it exclusively concentrates on Perl and Java's flavours of regular expressions,
1365and doesn't contain any Python material at all, so it won't be useful as a
1366reference for programming in Python. (The first edition covered Python's
Serhiy Storchakacd195e22017-10-14 11:14:26 +03001367now-removed :mod:`!regex` module, which won't help you much.) Consider checking
Georg Brandl116aa622007-08-15 14:28:22 +00001368it out from your library.