blob: d385d991344b2898340ef5ffa9bf7662d7365357 [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
Raymond Hettinger3bacf612019-02-19 11:32:18 -080099class. For example, ``[^5]`` will match any character except ``'5'``. If the
100caret appears elsewhere in a character class, it does not have special meaning.
101For example: ``[5^]`` will match either a ``'5'`` or a ``'^'``.
Georg Brandl116aa622007-08-15 14:28:22 +0000102
103Perhaps the most important metacharacter is the backslash, ``\``. As in Python
104string literals, the backslash can be followed by various characters to signal
105various special sequences. It's also used to escape all the metacharacters so
106you can still match them in patterns; for example, if you need to match a ``[``
107or ``\``, you can precede them with a backslash to remove their special
108meaning: ``\[`` or ``\\``.
109
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400110Some of the special sequences beginning with ``'\'`` represent
111predefined sets of characters that are often useful, such as the set
112of digits, the set of letters, or the set of anything that isn't
113whitespace.
114
115Let's take an example: ``\w`` matches any alphanumeric character. If
116the regex pattern is expressed in bytes, this is equivalent to the
117class ``[a-zA-Z0-9_]``. If the regex pattern is a string, ``\w`` will
118match all the characters marked as letters in the Unicode database
119provided by the :mod:`unicodedata` module. You can use the more
120restricted definition of ``\w`` in a string pattern by supplying the
121:const:`re.ASCII` flag when compiling the regular expression.
122
123The following list of special sequences isn't complete. For a complete
124list of sequences and expanded class definitions for Unicode string
125patterns, see the last part of :ref:`Regular Expression Syntax
126<re-syntax>` in the Standard Library reference. In general, the
127Unicode versions match any character that's in the appropriate
128category in the Unicode database.
Georg Brandl116aa622007-08-15 14:28:22 +0000129
130``\d``
131 Matches any decimal digit; this is equivalent to the class ``[0-9]``.
132
133``\D``
134 Matches any non-digit character; this is equivalent to the class ``[^0-9]``.
135
136``\s``
137 Matches any whitespace character; this is equivalent to the class ``[
138 \t\n\r\f\v]``.
139
140``\S``
141 Matches any non-whitespace character; this is equivalent to the class ``[^
142 \t\n\r\f\v]``.
143
144``\w``
145 Matches any alphanumeric character; this is equivalent to the class
146 ``[a-zA-Z0-9_]``.
147
148``\W``
149 Matches any non-alphanumeric character; this is equivalent to the class
150 ``[^a-zA-Z0-9_]``.
151
152These sequences can be included inside a character class. For example,
153``[\s,.]`` is a character class that will match any whitespace character, or
154``','`` or ``'.'``.
155
156The final metacharacter in this section is ``.``. It matches anything except a
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300157newline character, and there's an alternate mode (:const:`re.DOTALL`) where it will
158match even a newline. ``.`` is often used where you want to match "any
Georg Brandl116aa622007-08-15 14:28:22 +0000159character".
160
161
162Repeating Things
163----------------
164
165Being able to match varying sets of characters is the first thing regular
166expressions can do that isn't already possible with the methods available on
167strings. However, if that was the only additional capability of regexes, they
168wouldn't be much of an advance. Another capability is that you can specify that
169portions of the RE must be repeated a certain number of times.
170
171The first metacharacter for repeating things that we'll look at is ``*``. ``*``
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300172doesn't match the literal character ``'*'``; instead, it specifies that the
Georg Brandl116aa622007-08-15 14:28:22 +0000173previous character can be matched zero or more times, instead of exactly once.
174
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300175For example, ``ca*t`` will match ``'ct'`` (0 ``'a'`` characters), ``'cat'`` (1 ``'a'``),
176``'caaat'`` (3 ``'a'`` characters), and so forth.
Georg Brandl116aa622007-08-15 14:28:22 +0000177
178Repetitions such as ``*`` are :dfn:`greedy`; when repeating a RE, the matching
179engine will try to repeat it as many times as possible. If later portions of the
180pattern don't match, the matching engine will then back up and try again with
Benjamin Peterson8f0432f2016-02-17 23:42:46 -0800181fewer repetitions.
Georg Brandl116aa622007-08-15 14:28:22 +0000182
183A step-by-step example will make this more obvious. Let's consider the
184expression ``a[bcd]*b``. This matches the letter ``'a'``, zero or more letters
185from the class ``[bcd]``, and finally ends with a ``'b'``. Now imagine matching
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300186this RE against the string ``'abcbd'``.
Georg Brandl116aa622007-08-15 14:28:22 +0000187
188+------+-----------+---------------------------------+
189| Step | Matched | Explanation |
190+======+===========+=================================+
191| 1 | ``a`` | The ``a`` in the RE matches. |
192+------+-----------+---------------------------------+
193| 2 | ``abcbd`` | The engine matches ``[bcd]*``, |
194| | | going as far as it can, which |
195| | | is to the end of the string. |
196+------+-----------+---------------------------------+
197| 3 | *Failure* | The engine tries to match |
198| | | ``b``, but the current position |
199| | | is at the end of the string, so |
200| | | it fails. |
201+------+-----------+---------------------------------+
202| 4 | ``abcb`` | Back up, so that ``[bcd]*`` |
203| | | matches one less character. |
204+------+-----------+---------------------------------+
205| 5 | *Failure* | Try ``b`` again, but the |
206| | | current position is at the last |
207| | | character, which is a ``'d'``. |
208+------+-----------+---------------------------------+
209| 6 | ``abc`` | Back up again, so that |
210| | | ``[bcd]*`` is only matching |
211| | | ``bc``. |
212+------+-----------+---------------------------------+
213| 6 | ``abcb`` | Try ``b`` again. This time |
Christian Heimesa612dc02008-02-24 13:08:18 +0000214| | | the character at the |
Georg Brandl116aa622007-08-15 14:28:22 +0000215| | | current position is ``'b'``, so |
216| | | it succeeds. |
217+------+-----------+---------------------------------+
218
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300219The end of the RE has now been reached, and it has matched ``'abcb'``. This
Georg Brandl116aa622007-08-15 14:28:22 +0000220demonstrates how the matching engine goes as far as it can at first, and if no
221match is found it will then progressively back up and retry the rest of the RE
222again and again. It will back up until it has tried zero matches for
223``[bcd]*``, and if that subsequently fails, the engine will conclude that the
224string doesn't match the RE at all.
225
226Another repeating metacharacter is ``+``, which matches one or more times. Pay
227careful attention to the difference between ``*`` and ``+``; ``*`` matches
228*zero* or more times, so whatever's being repeated may not be present at all,
229while ``+`` requires at least *one* occurrence. To use a similar example,
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300230``ca+t`` will match ``'cat'`` (1 ``'a'``), ``'caaat'`` (3 ``'a'``\ s), but won't
231match ``'ct'``.
Georg Brandl116aa622007-08-15 14:28:22 +0000232
233There are two more repeating qualifiers. The question mark character, ``?``,
234matches either once or zero times; you can think of it as marking something as
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300235being optional. For example, ``home-?brew`` matches either ``'homebrew'`` or
236``'home-brew'``.
Georg Brandl116aa622007-08-15 14:28:22 +0000237
238The most complicated repeated qualifier is ``{m,n}``, where *m* and *n* are
239decimal integers. This qualifier means there must be at least *m* repetitions,
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300240and at most *n*. For example, ``a/{1,3}b`` will match ``'a/b'``, ``'a//b'``, and
241``'a///b'``. It won't match ``'ab'``, which has no slashes, or ``'a////b'``, which
Georg Brandl116aa622007-08-15 14:28:22 +0000242has four.
243
244You can omit either *m* or *n*; in that case, a reasonable value is assumed for
245the missing value. Omitting *m* is interpreted as a lower limit of 0, while
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300246omitting *n* results in an upper bound of infinity.
Georg Brandl116aa622007-08-15 14:28:22 +0000247
248Readers of a reductionist bent may notice that the three other qualifiers can
249all be expressed using this notation. ``{0,}`` is the same as ``*``, ``{1,}``
250is equivalent to ``+``, and ``{0,1}`` is the same as ``?``. It's better to use
251``*``, ``+``, or ``?`` when you can, simply because they're shorter and easier
252to read.
253
254
255Using Regular Expressions
256=========================
257
258Now that we've looked at some simple regular expressions, how do we actually use
259them in Python? The :mod:`re` module provides an interface to the regular
260expression engine, allowing you to compile REs into objects and then perform
261matches with them.
262
263
264Compiling Regular Expressions
265-----------------------------
266
Benjamin Peterson8cc7d882009-06-01 23:14:51 +0000267Regular expressions are compiled into pattern objects, which have
Georg Brandl116aa622007-08-15 14:28:22 +0000268methods for various operations such as searching for pattern matches or
269performing string substitutions. ::
270
271 >>> import re
272 >>> p = re.compile('ab*')
Ezio Melotti613a97e2013-11-25 22:47:01 +0200273 >>> p
274 re.compile('ab*')
Georg Brandl116aa622007-08-15 14:28:22 +0000275
276:func:`re.compile` also accepts an optional *flags* argument, used to enable
277various special features and syntax variations. We'll go over the available
278settings later, but for now a single example will do::
279
280 >>> p = re.compile('ab*', re.IGNORECASE)
281
282The RE is passed to :func:`re.compile` as a string. REs are handled as strings
283because regular expressions aren't part of the core Python language, and no
284special syntax was created for expressing them. (There are applications that
285don't need REs at all, so there's no need to bloat the language specification by
286including them.) Instead, the :mod:`re` module is simply a C extension module
287included with Python, just like the :mod:`socket` or :mod:`zlib` modules.
288
289Putting REs in strings keeps the Python language simpler, but has one
290disadvantage which is the topic of the next section.
291
292
Cheryl Sabella66771422018-02-02 16:16:27 -0500293.. _the-backslash-plague:
294
Georg Brandl116aa622007-08-15 14:28:22 +0000295The Backslash Plague
296--------------------
297
298As stated earlier, regular expressions use the backslash character (``'\'``) to
299indicate special forms or to allow special characters to be used without
300invoking their special meaning. This conflicts with Python's usage of the same
301character for the same purpose in string literals.
302
303Let's say you want to write a RE that matches the string ``\section``, which
304might be found in a LaTeX file. To figure out what to write in the program
305code, start with the desired string to be matched. Next, you must escape any
306backslashes and other metacharacters by preceding them with a backslash,
307resulting in the string ``\\section``. The resulting string that must be passed
308to :func:`re.compile` must be ``\\section``. However, to express this as a
309Python string literal, both backslashes must be escaped *again*.
310
311+-------------------+------------------------------------------+
312| Characters | Stage |
313+===================+==========================================+
314| ``\section`` | Text string to be matched |
315+-------------------+------------------------------------------+
316| ``\\section`` | Escaped backslash for :func:`re.compile` |
317+-------------------+------------------------------------------+
318| ``"\\\\section"`` | Escaped backslashes for a string literal |
319+-------------------+------------------------------------------+
320
321In short, to match a literal backslash, one has to write ``'\\\\'`` as the RE
322string, because the regular expression must be ``\\``, and each backslash must
323be expressed as ``\\`` inside a regular Python string literal. In REs that
324feature backslashes repeatedly, this leads to lots of repeated backslashes and
325makes the resulting strings difficult to understand.
326
327The solution is to use Python's raw string notation for regular expressions;
328backslashes are not handled in any special way in a string literal prefixed with
329``'r'``, so ``r"\n"`` is a two-character string containing ``'\'`` and ``'n'``,
330while ``"\n"`` is a one-character string containing a newline. Regular
331expressions will often be written in Python code using this raw string notation.
332
Cheryl Sabella66771422018-02-02 16:16:27 -0500333In addition, special escape sequences that are valid in regular expressions,
334but not valid as Python string literals, now result in a
335:exc:`DeprecationWarning` and will eventually become a :exc:`SyntaxError`,
336which means the sequences will be invalid if raw string notation or escaping
337the backslashes isn't used.
338
339
Georg Brandl116aa622007-08-15 14:28:22 +0000340+-------------------+------------------+
341| Regular String | Raw string |
342+===================+==================+
343| ``"ab*"`` | ``r"ab*"`` |
344+-------------------+------------------+
345| ``"\\\\section"`` | ``r"\\section"`` |
346+-------------------+------------------+
347| ``"\\w+\\s+\\1"`` | ``r"\w+\s+\1"`` |
348+-------------------+------------------+
349
350
351Performing Matches
352------------------
353
354Once you have an object representing a compiled regular expression, what do you
Benjamin Peterson8cc7d882009-06-01 23:14:51 +0000355do with it? Pattern objects have several methods and attributes.
Georg Brandl86def6c2008-01-21 20:36:10 +0000356Only the most significant ones will be covered here; consult the :mod:`re` docs
357for a complete listing.
Georg Brandl116aa622007-08-15 14:28:22 +0000358
359+------------------+-----------------------------------------------+
360| Method/Attribute | Purpose |
361+==================+===============================================+
362| ``match()`` | Determine if the RE matches at the beginning |
363| | of the string. |
364+------------------+-----------------------------------------------+
365| ``search()`` | Scan through a string, looking for any |
366| | location where this RE matches. |
367+------------------+-----------------------------------------------+
368| ``findall()`` | Find all substrings where the RE matches, and |
369| | returns them as a list. |
370+------------------+-----------------------------------------------+
371| ``finditer()`` | Find all substrings where the RE matches, and |
Georg Brandl9afde1c2007-11-01 20:32:30 +0000372| | returns them as an :term:`iterator`. |
Georg Brandl116aa622007-08-15 14:28:22 +0000373+------------------+-----------------------------------------------+
374
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300375: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 +0200376they're successful, a :ref:`match object <match-objects>` instance is returned,
377containing information about the match: where it starts and ends, the substring
378it matched, and more.
Georg Brandl116aa622007-08-15 14:28:22 +0000379
380You can learn about this by interactively experimenting with the :mod:`re`
Terry Reedy8663e342011-01-10 21:49:11 +0000381module. If you have :mod:`tkinter` available, you may also want to look at
Éric Araujofdfaf0a2012-03-05 15:50:37 +0100382:source:`Tools/demo/redemo.py`, a demonstration program included with the
Georg Brandl116aa622007-08-15 14:28:22 +0000383Python distribution. It allows you to enter REs and strings, and displays
384whether the RE matches or fails. :file:`redemo.py` can be quite useful when
Berker Peksag79af27e2016-06-24 08:54:43 +0300385trying to debug a complicated RE.
Georg Brandl116aa622007-08-15 14:28:22 +0000386
387This HOWTO uses the standard Python interpreter for its examples. First, run the
388Python interpreter, import the :mod:`re` module, and compile a RE::
389
Georg Brandl116aa622007-08-15 14:28:22 +0000390 >>> import re
391 >>> p = re.compile('[a-z]+')
Ezio Melotti613a97e2013-11-25 22:47:01 +0200392 >>> p
393 re.compile('[a-z]+')
Georg Brandl116aa622007-08-15 14:28:22 +0000394
395Now, you can try matching various strings against the RE ``[a-z]+``. An empty
396string shouldn't match at all, since ``+`` means 'one or more repetitions'.
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300397:meth:`~re.Pattern.match` should return ``None`` in this case, which will cause the
Georg Brandl116aa622007-08-15 14:28:22 +0000398interpreter to print no output. You can explicitly print the result of
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300399:meth:`!match` to make this clear. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000400
401 >>> p.match("")
Georg Brandl6911e3c2007-09-04 07:15:32 +0000402 >>> print(p.match(""))
Georg Brandl116aa622007-08-15 14:28:22 +0000403 None
404
405Now, let's try it on a string that it should match, such as ``tempo``. In this
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300406case, :meth:`~re.Pattern.match` will return a :ref:`match object <match-objects>`, so you
Ezio Melotti090f7be2012-12-25 18:10:49 +0200407should store the result in a variable for later use. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000408
409 >>> m = p.match('tempo')
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300410 >>> m
Serhiy Storchaka0b5e61d2017-10-04 20:09:49 +0300411 <re.Match object; span=(0, 5), match='tempo'>
Georg Brandl116aa622007-08-15 14:28:22 +0000412
Ezio Melotti090f7be2012-12-25 18:10:49 +0200413Now you can query the :ref:`match object <match-objects>` for information
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300414about the matching string. Match object instances
Ezio Melotti090f7be2012-12-25 18:10:49 +0200415also have several methods and attributes; the most important ones are:
Georg Brandl116aa622007-08-15 14:28:22 +0000416
417+------------------+--------------------------------------------+
418| Method/Attribute | Purpose |
419+==================+============================================+
420| ``group()`` | Return the string matched by the RE |
421+------------------+--------------------------------------------+
422| ``start()`` | Return the starting position of the match |
423+------------------+--------------------------------------------+
424| ``end()`` | Return the ending position of the match |
425+------------------+--------------------------------------------+
426| ``span()`` | Return a tuple containing the (start, end) |
427| | positions of the match |
428+------------------+--------------------------------------------+
429
430Trying these methods will soon clarify their meaning::
431
432 >>> m.group()
433 'tempo'
434 >>> m.start(), m.end()
435 (0, 5)
436 >>> m.span()
437 (0, 5)
438
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300439:meth:`~re.Match.group` returns the substring that was matched by the RE. :meth:`~re.Match.start`
440and :meth:`~re.Match.end` return the starting and ending index of the match. :meth:`~re.Match.span`
441returns both start and end indexes in a single tuple. Since the :meth:`~re.Pattern.match`
442method only checks if the RE matches at the start of a string, :meth:`!start`
443will always be zero. However, the :meth:`~re.Pattern.search` method of patterns
Benjamin Peterson8cc7d882009-06-01 23:14:51 +0000444scans through the string, so the match may not start at zero in that
Georg Brandl116aa622007-08-15 14:28:22 +0000445case. ::
446
Georg Brandl6911e3c2007-09-04 07:15:32 +0000447 >>> print(p.match('::: message'))
Georg Brandl116aa622007-08-15 14:28:22 +0000448 None
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300449 >>> m = p.search('::: message'); print(m)
Serhiy Storchaka0b5e61d2017-10-04 20:09:49 +0300450 <re.Match object; span=(4, 11), match='message'>
Georg Brandl116aa622007-08-15 14:28:22 +0000451 >>> m.group()
452 'message'
453 >>> m.span()
454 (4, 11)
455
Ezio Melotti090f7be2012-12-25 18:10:49 +0200456In actual programs, the most common style is to store the
457:ref:`match object <match-objects>` in a variable, and then check if it was
458``None``. This usually looks like::
Georg Brandl116aa622007-08-15 14:28:22 +0000459
460 p = re.compile( ... )
461 m = p.match( 'string goes here' )
462 if m:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000463 print('Match found: ', m.group())
Georg Brandl116aa622007-08-15 14:28:22 +0000464 else:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000465 print('No match')
Georg Brandl116aa622007-08-15 14:28:22 +0000466
Benjamin Peterson8cc7d882009-06-01 23:14:51 +0000467Two pattern methods return all of the matches for a pattern.
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300468:meth:`~re.Pattern.findall` returns a list of matching strings::
Georg Brandl116aa622007-08-15 14:28:22 +0000469
Cheryl Sabella66771422018-02-02 16:16:27 -0500470 >>> p = re.compile(r'\d+')
Georg Brandl116aa622007-08-15 14:28:22 +0000471 >>> p.findall('12 drummers drumming, 11 pipers piping, 10 lords a-leaping')
472 ['12', '11', '10']
473
Cheryl Sabella66771422018-02-02 16:16:27 -0500474The ``r`` prefix, making the literal a raw string literal, is needed in this
475example because escape sequences in a normal "cooked" string literal that are
476not recognized by Python, as opposed to regular expressions, now result in a
477:exc:`DeprecationWarning` and will eventually become a :exc:`SyntaxError`. See
478:ref:`the-backslash-plague`.
479
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300480:meth:`~re.Pattern.findall` has to create the entire list before it can be returned as the
481result. The :meth:`~re.Pattern.finditer` method returns a sequence of
Ezio Melotti090f7be2012-12-25 18:10:49 +0200482:ref:`match object <match-objects>` instances as an :term:`iterator`::
Georg Brandl116aa622007-08-15 14:28:22 +0000483
484 >>> iterator = p.finditer('12 drummers drumming, 11 ... 10 ...')
Ezio Melotti13bec9b2012-09-17 05:29:47 +0300485 >>> iterator #doctest: +ELLIPSIS
Terry Reedy8663e342011-01-10 21:49:11 +0000486 <callable_iterator object at 0x...>
Georg Brandl116aa622007-08-15 14:28:22 +0000487 >>> for match in iterator:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000488 ... print(match.span())
Georg Brandl116aa622007-08-15 14:28:22 +0000489 ...
490 (0, 2)
491 (22, 24)
492 (29, 31)
493
494
495Module-Level Functions
496----------------------
497
Benjamin Peterson8cc7d882009-06-01 23:14:51 +0000498You don't have to create a pattern object and call its methods; the
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400499:mod:`re` module also provides top-level functions called :func:`~re.match`,
500:func:`~re.search`, :func:`~re.findall`, :func:`~re.sub`, and so forth. These functions
501take the same arguments as the corresponding pattern method with
Georg Brandl116aa622007-08-15 14:28:22 +0000502the RE string added as the first argument, and still return either ``None`` or a
Ezio Melotti090f7be2012-12-25 18:10:49 +0200503:ref:`match object <match-objects>` instance. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000504
Georg Brandl6911e3c2007-09-04 07:15:32 +0000505 >>> print(re.match(r'From\s+', 'Fromage amk'))
Georg Brandl116aa622007-08-15 14:28:22 +0000506 None
Ezio Melotti13bec9b2012-09-17 05:29:47 +0300507 >>> re.match(r'From\s+', 'From amk Thu May 14 19:12:10 1998') #doctest: +ELLIPSIS
Serhiy Storchaka0b5e61d2017-10-04 20:09:49 +0300508 <re.Match object; span=(0, 5), match='From '>
Georg Brandl116aa622007-08-15 14:28:22 +0000509
Benjamin Peterson8cc7d882009-06-01 23:14:51 +0000510Under the hood, these functions simply create a pattern object for you
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400511and call the appropriate method on it. They also store the compiled
512object in a cache, so future calls using the same RE won't need to
513parse the pattern again and again.
Georg Brandl116aa622007-08-15 14:28:22 +0000514
515Should you use these module-level functions, or should you get the
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400516pattern and call its methods yourself? If you're accessing a regex
517within a loop, pre-compiling it will save a few function calls.
518Outside of loops, there's not much difference thanks to the internal
519cache.
Georg Brandl116aa622007-08-15 14:28:22 +0000520
521
522Compilation Flags
523-----------------
524
525Compilation flags let you modify some aspects of how regular expressions work.
526Flags are available in the :mod:`re` module under two names, a long name such as
527:const:`IGNORECASE` and a short, one-letter form such as :const:`I`. (If you're
528familiar with Perl's pattern modifiers, the one-letter forms use the same
529letters; the short form of :const:`re.VERBOSE` is :const:`re.X`, for example.)
530Multiple flags can be specified by bitwise OR-ing them; ``re.I | re.M`` sets
531both the :const:`I` and :const:`M` flags, for example.
532
533Here's a table of the available flags, followed by a more detailed explanation
534of each one.
535
536+---------------------------------+--------------------------------------------+
537| Flag | Meaning |
538+=================================+============================================+
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400539| :const:`ASCII`, :const:`A` | Makes several escapes like ``\w``, ``\b``, |
540| | ``\s`` and ``\d`` match only on ASCII |
541| | characters with the respective property. |
542+---------------------------------+--------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000543| :const:`DOTALL`, :const:`S` | Make ``.`` match any character, including |
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300544| | newlines. |
Georg Brandl116aa622007-08-15 14:28:22 +0000545+---------------------------------+--------------------------------------------+
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300546| :const:`IGNORECASE`, :const:`I` | Do case-insensitive matches. |
Georg Brandl116aa622007-08-15 14:28:22 +0000547+---------------------------------+--------------------------------------------+
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300548| :const:`LOCALE`, :const:`L` | Do a locale-aware match. |
Georg Brandl116aa622007-08-15 14:28:22 +0000549+---------------------------------+--------------------------------------------+
550| :const:`MULTILINE`, :const:`M` | Multi-line matching, affecting ``^`` and |
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300551| | ``$``. |
Georg Brandl116aa622007-08-15 14:28:22 +0000552+---------------------------------+--------------------------------------------+
553| :const:`VERBOSE`, :const:`X` | Enable verbose REs, which can be organized |
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400554| (for 'extended') | more cleanly and understandably. |
Georg Brandlce9fbd32009-03-31 18:41:03 +0000555+---------------------------------+--------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000556
557
558.. data:: I
559 IGNORECASE
560 :noindex:
561
562 Perform case-insensitive matching; character class and literal strings will
563 match letters by ignoring case. For example, ``[A-Z]`` will match lowercase
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300564 letters, too. Full Unicode matching also works unless the :const:`ASCII`
565 flag is used to disable non-ASCII matches. When the Unicode patterns
566 ``[a-z]`` or ``[A-Z]`` are used in combination with the :const:`IGNORECASE`
567 flag, they will match the 52 ASCII letters and 4 additional non-ASCII
568 letters: 'İ' (U+0130, Latin capital letter I with dot above), 'ı' (U+0131,
569 Latin small letter dotless i), 'Å¿' (U+017F, Latin small letter long s) and
570 'K' (U+212A, Kelvin sign). ``Spam`` will match ``'Spam'``, ``'spam'``,
571 ``'spAM'``, or ``'ſpam'`` (the latter is matched only in Unicode mode).
572 This lowercasing doesn't take the current locale into account;
573 it will if you also set the :const:`LOCALE` flag.
Georg Brandl116aa622007-08-15 14:28:22 +0000574
575
576.. data:: L
577 LOCALE
578 :noindex:
579
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300580 Make ``\w``, ``\W``, ``\b``, ``\B`` and case-insensitive matching dependent
581 on the current locale instead of the Unicode database.
Georg Brandl116aa622007-08-15 14:28:22 +0000582
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300583 Locales are a feature of the C library intended to help in writing programs
584 that take account of language differences. For example, if you're
585 processing encoded French text, you'd want to be able to write ``\w+`` to
586 match words, but ``\w`` only matches the character class ``[A-Za-z]`` in
587 bytes patterns; it won't match bytes corresponding to ``é`` or ``ç``.
588 If your system is configured properly and a French locale is selected,
589 certain C functions will tell the program that the byte corresponding to
590 ``é`` should also be considered a letter.
Georg Brandl116aa622007-08-15 14:28:22 +0000591 Setting the :const:`LOCALE` flag when compiling a regular expression will cause
592 the resulting compiled object to use these C functions for ``\w``; this is
593 slower, but also enables ``\w+`` to match French words as you'd expect.
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300594 The use of this flag is discouraged in Python 3 as the locale mechanism
595 is very unreliable, it only handles one "culture" at a time, and it only
596 works with 8-bit locales. Unicode matching is already enabled by default
597 in Python 3 for Unicode (str) patterns, and it is able to handle different
598 locales/languages.
Georg Brandl116aa622007-08-15 14:28:22 +0000599
600
601.. data:: M
602 MULTILINE
603 :noindex:
604
605 (``^`` and ``$`` haven't been explained yet; they'll be introduced in section
606 :ref:`more-metacharacters`.)
607
608 Usually ``^`` matches only at the beginning of the string, and ``$`` matches
609 only at the end of the string and immediately before the newline (if any) at the
610 end of the string. When this flag is specified, ``^`` matches at the beginning
611 of the string and at the beginning of each line within the string, immediately
612 following each newline. Similarly, the ``$`` metacharacter matches either at
613 the end of the string and at the end of each line (immediately preceding each
614 newline).
615
616
617.. data:: S
618 DOTALL
619 :noindex:
620
621 Makes the ``'.'`` special character match any character at all, including a
622 newline; without this flag, ``'.'`` will match anything *except* a newline.
623
624
Georg Brandlce9fbd32009-03-31 18:41:03 +0000625.. data:: A
626 ASCII
627 :noindex:
628
629 Make ``\w``, ``\W``, ``\b``, ``\B``, ``\s`` and ``\S`` perform ASCII-only
630 matching instead of full Unicode matching. This is only meaningful for
631 Unicode patterns, and is ignored for byte patterns.
632
633
Georg Brandl116aa622007-08-15 14:28:22 +0000634.. data:: X
635 VERBOSE
636 :noindex:
637
638 This flag allows you to write regular expressions that are more readable by
639 granting you more flexibility in how you can format them. When this flag has
640 been specified, whitespace within the RE string is ignored, except when the
641 whitespace is in a character class or preceded by an unescaped backslash; this
642 lets you organize and indent the RE more clearly. This flag also lets you put
643 comments within a RE that will be ignored by the engine; comments are marked by
644 a ``'#'`` that's neither in a character class or preceded by an unescaped
645 backslash.
646
647 For example, here's a RE that uses :const:`re.VERBOSE`; see how much easier it
648 is to read? ::
649
650 charref = re.compile(r"""
Georg Brandl06788c92009-01-03 21:31:47 +0000651 &[#] # Start of a numeric entity reference
Georg Brandl116aa622007-08-15 14:28:22 +0000652 (
653 0[0-7]+ # Octal form
654 | [0-9]+ # Decimal form
655 | x[0-9a-fA-F]+ # Hexadecimal form
656 )
657 ; # Trailing semicolon
658 """, re.VERBOSE)
659
660 Without the verbose setting, the RE would look like this::
661
662 charref = re.compile("&#(0[0-7]+"
663 "|[0-9]+"
664 "|x[0-9a-fA-F]+);")
665
666 In the above example, Python's automatic concatenation of string literals has
667 been used to break up the RE into smaller pieces, but it's still more difficult
668 to understand than the version using :const:`re.VERBOSE`.
669
670
671More Pattern Power
672==================
673
674So far we've only covered a part of the features of regular expressions. In
675this section, we'll cover some new metacharacters, and how to use groups to
676retrieve portions of the text that was matched.
677
678
679.. _more-metacharacters:
680
681More Metacharacters
682-------------------
683
684There are some metacharacters that we haven't covered yet. Most of them will be
685covered in this section.
686
687Some of the remaining metacharacters to be discussed are :dfn:`zero-width
688assertions`. They don't cause the engine to advance through the string;
689instead, they consume no characters at all, and simply succeed or fail. For
690example, ``\b`` is an assertion that the current position is located at a word
691boundary; the position isn't changed by the ``\b`` at all. This means that
692zero-width assertions should never be repeated, because if they match once at a
693given location, they can obviously be matched an infinite number of times.
694
695``|``
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300696 Alternation, or the "or" operator. If *A* and *B* are regular expressions,
697 ``A|B`` will match any string that matches either *A* or *B*. ``|`` has very
Georg Brandl116aa622007-08-15 14:28:22 +0000698 low precedence in order to make it work reasonably when you're alternating
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300699 multi-character strings. ``Crow|Servo`` will match either ``'Crow'`` or ``'Servo'``,
700 not ``'Cro'``, a ``'w'`` or an ``'S'``, and ``'ervo'``.
Georg Brandl116aa622007-08-15 14:28:22 +0000701
702 To match a literal ``'|'``, use ``\|``, or enclose it inside a character class,
703 as in ``[|]``.
704
705``^``
706 Matches at the beginning of lines. Unless the :const:`MULTILINE` flag has been
707 set, this will only match at the beginning of the string. In :const:`MULTILINE`
708 mode, this also matches immediately after each newline within the string.
709
710 For example, if you wish to match the word ``From`` only at the beginning of a
711 line, the RE to use is ``^From``. ::
712
Ezio Melotti13bec9b2012-09-17 05:29:47 +0300713 >>> print(re.search('^From', 'From Here to Eternity')) #doctest: +ELLIPSIS
Serhiy Storchaka0b5e61d2017-10-04 20:09:49 +0300714 <re.Match object; span=(0, 4), match='From'>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000715 >>> print(re.search('^From', 'Reciting From Memory'))
Georg Brandl116aa622007-08-15 14:28:22 +0000716 None
717
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300718 To match a literal ``'^'``, use ``\^``.
Georg Brandl116aa622007-08-15 14:28:22 +0000719
720``$``
721 Matches at the end of a line, which is defined as either the end of the string,
722 or any location followed by a newline character. ::
723
Ezio Melotti13bec9b2012-09-17 05:29:47 +0300724 >>> print(re.search('}$', '{block}')) #doctest: +ELLIPSIS
Serhiy Storchaka0b5e61d2017-10-04 20:09:49 +0300725 <re.Match object; span=(6, 7), match='}'>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000726 >>> print(re.search('}$', '{block} '))
Georg Brandl116aa622007-08-15 14:28:22 +0000727 None
Ezio Melotti13bec9b2012-09-17 05:29:47 +0300728 >>> print(re.search('}$', '{block}\n')) #doctest: +ELLIPSIS
Serhiy Storchaka0b5e61d2017-10-04 20:09:49 +0300729 <re.Match object; span=(6, 7), match='}'>
Georg Brandl116aa622007-08-15 14:28:22 +0000730
731 To match a literal ``'$'``, use ``\$`` or enclose it inside a character class,
732 as in ``[$]``.
733
Georg Brandl116aa622007-08-15 14:28:22 +0000734``\A``
735 Matches only at the start of the string. When not in :const:`MULTILINE` mode,
736 ``\A`` and ``^`` are effectively the same. In :const:`MULTILINE` mode, they're
737 different: ``\A`` still matches only at the beginning of the string, but ``^``
738 may match at any location inside the string that follows a newline character.
739
740``\Z``
741 Matches only at the end of the string.
742
743``\b``
744 Word boundary. This is a zero-width assertion that matches only at the
745 beginning or end of a word. A word is defined as a sequence of alphanumeric
746 characters, so the end of a word is indicated by whitespace or a
747 non-alphanumeric character.
748
749 The following example matches ``class`` only when it's a complete word; it won't
750 match when it's contained inside another word. ::
751
752 >>> p = re.compile(r'\bclass\b')
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300753 >>> print(p.search('no class at all'))
Serhiy Storchaka0b5e61d2017-10-04 20:09:49 +0300754 <re.Match object; span=(3, 8), match='class'>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000755 >>> print(p.search('the declassified algorithm'))
Georg Brandl116aa622007-08-15 14:28:22 +0000756 None
Georg Brandl6911e3c2007-09-04 07:15:32 +0000757 >>> print(p.search('one subclass is'))
Georg Brandl116aa622007-08-15 14:28:22 +0000758 None
759
760 There are two subtleties you should remember when using this special sequence.
761 First, this is the worst collision between Python's string literals and regular
762 expression sequences. In Python's string literals, ``\b`` is the backspace
763 character, ASCII value 8. If you're not using raw strings, then Python will
764 convert the ``\b`` to a backspace, and your RE won't match as you expect it to.
765 The following example looks the same as our previous RE, but omits the ``'r'``
766 in front of the RE string. ::
767
768 >>> p = re.compile('\bclass\b')
Georg Brandl6911e3c2007-09-04 07:15:32 +0000769 >>> print(p.search('no class at all'))
Georg Brandl116aa622007-08-15 14:28:22 +0000770 None
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300771 >>> print(p.search('\b' + 'class' + '\b'))
Serhiy Storchaka0b5e61d2017-10-04 20:09:49 +0300772 <re.Match object; span=(0, 7), match='\x08class\x08'>
Georg Brandl116aa622007-08-15 14:28:22 +0000773
774 Second, inside a character class, where there's no use for this assertion,
775 ``\b`` represents the backspace character, for compatibility with Python's
776 string literals.
777
778``\B``
779 Another zero-width assertion, this is the opposite of ``\b``, only matching when
780 the current position is not at a word boundary.
781
782
783Grouping
784--------
785
786Frequently you need to obtain more information than just whether the RE matched
787or not. Regular expressions are often used to dissect strings by writing a RE
788divided into several subgroups which match different components of interest.
789For example, an RFC-822 header line is divided into a header name and a value,
Serhiy Storchaka46936d52018-04-08 19:18:04 +0300790separated by a ``':'``, like this:
791
792.. code-block:: none
Georg Brandl116aa622007-08-15 14:28:22 +0000793
794 From: author@example.com
795 User-Agent: Thunderbird 1.5.0.9 (X11/20061227)
796 MIME-Version: 1.0
797 To: editor@example.com
798
799This can be handled by writing a regular expression which matches an entire
800header line, and has one group which matches the header name, and another group
801which matches the header's value.
802
803Groups are marked by the ``'('``, ``')'`` metacharacters. ``'('`` and ``')'``
804have much the same meaning as they do in mathematical expressions; they group
805together the expressions contained inside them, and you can repeat the contents
806of a group with a repeating qualifier, such as ``*``, ``+``, ``?``, or
807``{m,n}``. For example, ``(ab)*`` will match zero or more repetitions of
808``ab``. ::
809
810 >>> p = re.compile('(ab)*')
Georg Brandl6911e3c2007-09-04 07:15:32 +0000811 >>> print(p.match('ababababab').span())
Georg Brandl116aa622007-08-15 14:28:22 +0000812 (0, 10)
813
814Groups indicated with ``'('``, ``')'`` also capture the starting and ending
815index of the text that they match; this can be retrieved by passing an argument
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300816to :meth:`~re.Match.group`, :meth:`~re.Match.start`, :meth:`~re.Match.end`, and
817:meth:`~re.Match.span`. Groups are
Georg Brandl116aa622007-08-15 14:28:22 +0000818numbered starting with 0. Group 0 is always present; it's the whole RE, so
Ezio Melotti090f7be2012-12-25 18:10:49 +0200819:ref:`match object <match-objects>` methods all have group 0 as their default
820argument. Later we'll see how to express groups that don't capture the span
821of text that they match. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000822
823 >>> p = re.compile('(a)b')
824 >>> m = p.match('ab')
825 >>> m.group()
826 'ab'
827 >>> m.group(0)
828 'ab'
829
830Subgroups are numbered from left to right, from 1 upward. Groups can be nested;
831to determine the number, just count the opening parenthesis characters, going
832from left to right. ::
833
834 >>> p = re.compile('(a(b)c)d')
835 >>> m = p.match('abcd')
836 >>> m.group(0)
837 'abcd'
838 >>> m.group(1)
839 'abc'
840 >>> m.group(2)
841 'b'
842
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300843:meth:`~re.Match.group` can be passed multiple group numbers at a time, in which case it
Georg Brandl116aa622007-08-15 14:28:22 +0000844will return a tuple containing the corresponding values for those groups. ::
845
846 >>> m.group(2,1,2)
847 ('b', 'abc', 'b')
848
Serhiy Storchakacd195e22017-10-14 11:14:26 +0300849The :meth:`~re.Match.groups` method returns a tuple containing the strings for all the
Georg Brandl116aa622007-08-15 14:28:22 +0000850subgroups, from 1 up to however many there are. ::
851
852 >>> m.groups()
853 ('abc', 'b')
854
855Backreferences in a pattern allow you to specify that the contents of an earlier
856capturing group must also be found at the current location in the string. For
857example, ``\1`` will succeed if the exact contents of group 1 can be found at
858the current position, and fails otherwise. Remember that Python's string
859literals also use a backslash followed by numbers to allow including arbitrary
860characters in a string, so be sure to use a raw string when incorporating
861backreferences in a RE.
862
863For example, the following RE detects doubled words in a string. ::
864
Mandeep Bhutani610e5af2017-11-24 22:56:00 -0600865 >>> p = re.compile(r'\b(\w+)\s+\1\b')
Georg Brandl116aa622007-08-15 14:28:22 +0000866 >>> p.search('Paris in the the spring').group()
867 'the the'
868
869Backreferences like this aren't often useful for just searching through a string
870--- there are few text formats which repeat data in this way --- but you'll soon
871find out that they're *very* useful when performing string substitutions.
872
873
874Non-capturing and Named Groups
875------------------------------
876
877Elaborate REs may use many groups, both to capture substrings of interest, and
878to group and structure the RE itself. In complex REs, it becomes difficult to
879keep track of the group numbers. There are two features which help with this
880problem. Both of them use a common syntax for regular expression extensions, so
881we'll look at that first.
882
Donald Stufft8b852f12014-05-20 12:58:38 -0400883Perl 5 is well known for its powerful additions to standard regular expressions.
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400884For these new features the Perl developers couldn't choose new single-keystroke metacharacters
885or new special sequences beginning with ``\`` without making Perl's regular
886expressions confusingly different from standard REs. If they chose ``&`` as a
Georg Brandl116aa622007-08-15 14:28:22 +0000887new metacharacter, for example, old expressions would be assuming that ``&`` was
888a regular character and wouldn't have escaped it by writing ``\&`` or ``[&]``.
889
890The solution chosen by the Perl developers was to use ``(?...)`` as the
891extension syntax. ``?`` immediately after a parenthesis was a syntax error
892because the ``?`` would have nothing to repeat, so this didn't introduce any
893compatibility problems. The characters immediately after the ``?`` indicate
894what extension is being used, so ``(?=foo)`` is one thing (a positive lookahead
895assertion) and ``(?:foo)`` is something else (a non-capturing group containing
896the subexpression ``foo``).
897
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400898Python supports several of Perl's extensions and adds an extension
899syntax to Perl's extension syntax. If the first character after the
900question mark is a ``P``, you know that it's an extension that's
901specific to Python.
Georg Brandl116aa622007-08-15 14:28:22 +0000902
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400903Now that we've looked at the general extension syntax, we can return
904to the features that simplify working with groups in complex REs.
Georg Brandl116aa622007-08-15 14:28:22 +0000905
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400906Sometimes you'll want to use a group to denote a part of a regular expression,
Georg Brandl116aa622007-08-15 14:28:22 +0000907but aren't interested in retrieving the group's contents. You can make this fact
908explicit by using a non-capturing group: ``(?:...)``, where you can replace the
909``...`` with any other regular expression. ::
910
911 >>> m = re.match("([abc])+", "abc")
912 >>> m.groups()
913 ('c',)
914 >>> m = re.match("(?:[abc])+", "abc")
915 >>> m.groups()
916 ()
917
918Except for the fact that you can't retrieve the contents of what the group
919matched, a non-capturing group behaves exactly the same as a capturing group;
920you can put anything inside it, repeat it with a repetition metacharacter such
921as ``*``, and nest it within other groups (capturing or non-capturing).
922``(?:...)`` is particularly useful when modifying an existing pattern, since you
923can add new groups without changing how all the other groups are numbered. It
924should be mentioned that there's no performance difference in searching between
925capturing and non-capturing groups; neither form is any faster than the other.
926
927A more significant feature is named groups: instead of referring to them by
928numbers, groups can be referenced by a name.
929
930The syntax for a named group is one of the Python-specific extensions:
931``(?P<name>...)``. *name* is, obviously, the name of the group. Named groups
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400932behave exactly like capturing groups, and additionally associate a name
Ezio Melotti090f7be2012-12-25 18:10:49 +0200933with a group. The :ref:`match object <match-objects>` methods that deal with
934capturing groups all accept either integers that refer to the group by number
935or strings that contain the desired group's name. Named groups are still
936given numbers, so you can retrieve information about a group in two ways::
Georg Brandl116aa622007-08-15 14:28:22 +0000937
938 >>> p = re.compile(r'(?P<word>\b\w+\b)')
939 >>> m = p.search( '(((( Lots of punctuation )))' )
940 >>> m.group('word')
941 'Lots'
942 >>> m.group(1)
943 'Lots'
944
945Named groups are handy because they let you use easily-remembered names, instead
946of having to remember numbers. Here's an example RE from the :mod:`imaplib`
947module::
948
949 InternalDate = re.compile(r'INTERNALDATE "'
950 r'(?P<day>[ 123][0-9])-(?P<mon>[A-Z][a-z][a-z])-'
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000951 r'(?P<year>[0-9][0-9][0-9][0-9])'
Georg Brandl116aa622007-08-15 14:28:22 +0000952 r' (?P<hour>[0-9][0-9]):(?P<min>[0-9][0-9]):(?P<sec>[0-9][0-9])'
953 r' (?P<zonen>[-+])(?P<zoneh>[0-9][0-9])(?P<zonem>[0-9][0-9])'
954 r'"')
955
956It's obviously much easier to retrieve ``m.group('zonem')``, instead of having
957to remember to retrieve group 9.
958
959The syntax for backreferences in an expression such as ``(...)\1`` refers to the
960number of the group. There's naturally a variant that uses the group name
961instead of the number. This is another Python extension: ``(?P=name)`` indicates
962that the contents of the group called *name* should again be matched at the
963current point. The regular expression for finding doubled words,
Mandeep Bhutani610e5af2017-11-24 22:56:00 -0600964``\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 +0000965
Mandeep Bhutani610e5af2017-11-24 22:56:00 -0600966 >>> p = re.compile(r'\b(?P<word>\w+)\s+(?P=word)\b')
Georg Brandl116aa622007-08-15 14:28:22 +0000967 >>> p.search('Paris in the the spring').group()
968 'the the'
969
970
971Lookahead Assertions
972--------------------
973
974Another zero-width assertion is the lookahead assertion. Lookahead assertions
975are available in both positive and negative form, and look like this:
976
977``(?=...)``
978 Positive lookahead assertion. This succeeds if the contained regular
979 expression, represented here by ``...``, successfully matches at the current
980 location, and fails otherwise. But, once the contained expression has been
981 tried, the matching engine doesn't advance at all; the rest of the pattern is
982 tried right where the assertion started.
983
984``(?!...)``
985 Negative lookahead assertion. This is the opposite of the positive assertion;
986 it succeeds if the contained expression *doesn't* match at the current position
987 in the string.
988
989To make this concrete, let's look at a case where a lookahead is useful.
990Consider a simple pattern to match a filename and split it apart into a base
991name and an extension, separated by a ``.``. For example, in ``news.rc``,
992``news`` is the base name, and ``rc`` is the filename's extension.
993
994The pattern to match this is quite simple:
995
996``.*[.].*$``
997
998Notice that the ``.`` needs to be treated specially because it's a
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400999metacharacter, so it's inside a character class to only match that
1000specific character. Also notice the trailing ``$``; this is added to
1001ensure that all the rest of the string must be included in the
1002extension. This regular expression matches ``foo.bar`` and
Georg Brandl116aa622007-08-15 14:28:22 +00001003``autoexec.bat`` and ``sendmail.cf`` and ``printers.conf``.
1004
1005Now, consider complicating the problem a bit; what if you want to match
1006filenames where the extension is not ``bat``? Some incorrect attempts:
1007
1008``.*[.][^b].*$`` The first attempt above tries to exclude ``bat`` by requiring
1009that the first character of the extension is not a ``b``. This is wrong,
1010because the pattern also doesn't match ``foo.bar``.
1011
Georg Brandl116aa622007-08-15 14:28:22 +00001012``.*[.]([^b]..|.[^a].|..[^t])$``
1013
Georg Brandl116aa622007-08-15 14:28:22 +00001014The expression gets messier when you try to patch up the first solution by
1015requiring one of the following cases to match: the first character of the
1016extension isn't ``b``; the second character isn't ``a``; or the third character
1017isn't ``t``. This accepts ``foo.bar`` and rejects ``autoexec.bat``, but it
1018requires a three-letter extension and won't accept a filename with a two-letter
1019extension such as ``sendmail.cf``. We'll complicate the pattern again in an
1020effort to fix it.
1021
1022``.*[.]([^b].?.?|.[^a]?.?|..?[^t]?)$``
1023
1024In the third attempt, the second and third letters are all made optional in
1025order to allow matching extensions shorter than three characters, such as
1026``sendmail.cf``.
1027
1028The pattern's getting really complicated now, which makes it hard to read and
1029understand. Worse, if the problem changes and you want to exclude both ``bat``
1030and ``exe`` as extensions, the pattern would get even more complicated and
1031confusing.
1032
1033A negative lookahead cuts through all this confusion:
1034
Ezio Melotti84c63e82016-01-12 00:09:13 +02001035``.*[.](?!bat$)[^.]*$`` The negative lookahead means: if the expression ``bat``
Georg Brandl116aa622007-08-15 14:28:22 +00001036doesn't match at this point, try the rest of the pattern; if ``bat$`` does
1037match, the whole pattern will fail. The trailing ``$`` is required to ensure
1038that something like ``sample.batch``, where the extension only starts with
Ezio Melotti84c63e82016-01-12 00:09:13 +02001039``bat``, will be allowed. The ``[^.]*`` makes sure that the pattern works
1040when there are multiple dots in the filename.
Georg Brandl116aa622007-08-15 14:28:22 +00001041
Georg Brandl116aa622007-08-15 14:28:22 +00001042Excluding another filename extension is now easy; simply add it as an
1043alternative inside the assertion. The following pattern excludes filenames that
1044end in either ``bat`` or ``exe``:
1045
Ezio Melotti84c63e82016-01-12 00:09:13 +02001046``.*[.](?!bat$|exe$)[^.]*$``
Georg Brandl116aa622007-08-15 14:28:22 +00001047
Georg Brandl116aa622007-08-15 14:28:22 +00001048
1049Modifying Strings
1050=================
1051
1052Up to this point, we've simply performed searches against a static string.
1053Regular expressions are also commonly used to modify strings in various ways,
Benjamin Peterson8cc7d882009-06-01 23:14:51 +00001054using the following pattern methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001055
1056+------------------+-----------------------------------------------+
1057| Method/Attribute | Purpose |
1058+==================+===============================================+
1059| ``split()`` | Split the string into a list, splitting it |
1060| | wherever the RE matches |
1061+------------------+-----------------------------------------------+
1062| ``sub()`` | Find all substrings where the RE matches, and |
1063| | replace them with a different string |
1064+------------------+-----------------------------------------------+
Serhiy Storchakacd195e22017-10-14 11:14:26 +03001065| ``subn()`` | Does the same thing as :meth:`!sub`, but |
Georg Brandl116aa622007-08-15 14:28:22 +00001066| | returns the new string and the number of |
1067| | replacements |
1068+------------------+-----------------------------------------------+
1069
1070
1071Splitting Strings
1072-----------------
1073
Serhiy Storchakacd195e22017-10-14 11:14:26 +03001074The :meth:`~re.Pattern.split` method of a pattern splits a string apart
Georg Brandl116aa622007-08-15 14:28:22 +00001075wherever the RE matches, returning a list of the pieces. It's similar to the
Serhiy Storchakacd195e22017-10-14 11:14:26 +03001076:meth:`~str.split` method of strings but provides much more generality in the
1077delimiters that you can split by; string :meth:`!split` only supports splitting by
Georg Brandl116aa622007-08-15 14:28:22 +00001078whitespace or by a fixed string. As you'd expect, there's a module-level
1079:func:`re.split` function, too.
1080
1081
1082.. method:: .split(string [, maxsplit=0])
1083 :noindex:
1084
1085 Split *string* by the matches of the regular expression. If capturing
1086 parentheses are used in the RE, then their contents will also be returned as
1087 part of the resulting list. If *maxsplit* is nonzero, at most *maxsplit* splits
1088 are performed.
1089
1090You can limit the number of splits made, by passing a value for *maxsplit*.
1091When *maxsplit* is nonzero, at most *maxsplit* splits will be made, and the
1092remainder of the string is returned as the final element of the list. In the
1093following example, the delimiter is any sequence of non-alphanumeric characters.
1094::
1095
1096 >>> p = re.compile(r'\W+')
1097 >>> p.split('This is a test, short and sweet, of split().')
1098 ['This', 'is', 'a', 'test', 'short', 'and', 'sweet', 'of', 'split', '']
1099 >>> p.split('This is a test, short and sweet, of split().', 3)
1100 ['This', 'is', 'a', 'test, short and sweet, of split().']
1101
1102Sometimes you're not only interested in what the text between delimiters is, but
1103also need to know what the delimiter was. If capturing parentheses are used in
1104the RE, then their values are also returned as part of the list. Compare the
1105following calls::
1106
1107 >>> p = re.compile(r'\W+')
1108 >>> p2 = re.compile(r'(\W+)')
1109 >>> p.split('This... is a test.')
1110 ['This', 'is', 'a', 'test', '']
1111 >>> p2.split('This... is a test.')
1112 ['This', '... ', 'is', ' ', 'a', ' ', 'test', '.', '']
1113
1114The module-level function :func:`re.split` adds the RE to be used as the first
1115argument, but is otherwise the same. ::
1116
Cheryl Sabella66771422018-02-02 16:16:27 -05001117 >>> re.split(r'[\W]+', 'Words, words, words.')
Georg Brandl116aa622007-08-15 14:28:22 +00001118 ['Words', 'words', 'words', '']
Cheryl Sabella66771422018-02-02 16:16:27 -05001119 >>> re.split(r'([\W]+)', 'Words, words, words.')
Georg Brandl116aa622007-08-15 14:28:22 +00001120 ['Words', ', ', 'words', ', ', 'words', '.', '']
Cheryl Sabella66771422018-02-02 16:16:27 -05001121 >>> re.split(r'[\W]+', 'Words, words, words.', 1)
Georg Brandl116aa622007-08-15 14:28:22 +00001122 ['Words', 'words, words.']
1123
1124
1125Search and Replace
1126------------------
1127
1128Another common task is to find all the matches for a pattern, and replace them
Serhiy Storchakacd195e22017-10-14 11:14:26 +03001129with a different string. The :meth:`~re.Pattern.sub` method takes a replacement value,
Georg Brandl116aa622007-08-15 14:28:22 +00001130which can be either a string or a function, and the string to be processed.
1131
Georg Brandl116aa622007-08-15 14:28:22 +00001132.. method:: .sub(replacement, string[, count=0])
1133 :noindex:
1134
1135 Returns the string obtained by replacing the leftmost non-overlapping
1136 occurrences of the RE in *string* by the replacement *replacement*. If the
1137 pattern isn't found, *string* is returned unchanged.
1138
1139 The optional argument *count* is the maximum number of pattern occurrences to be
1140 replaced; *count* must be a non-negative integer. The default value of 0 means
1141 to replace all occurrences.
1142
Serhiy Storchakacd195e22017-10-14 11:14:26 +03001143Here's a simple example of using the :meth:`~re.Pattern.sub` method. It replaces colour
Georg Brandl116aa622007-08-15 14:28:22 +00001144names with the word ``colour``::
1145
Serhiy Storchakadba90392016-05-10 12:01:23 +03001146 >>> p = re.compile('(blue|white|red)')
1147 >>> p.sub('colour', 'blue socks and red shoes')
Georg Brandl116aa622007-08-15 14:28:22 +00001148 'colour socks and colour shoes'
Serhiy Storchakadba90392016-05-10 12:01:23 +03001149 >>> p.sub('colour', 'blue socks and red shoes', count=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001150 'colour socks and red shoes'
1151
Serhiy Storchakacd195e22017-10-14 11:14:26 +03001152The :meth:`~re.Pattern.subn` method does the same work, but returns a 2-tuple containing the
Georg Brandl116aa622007-08-15 14:28:22 +00001153new string value and the number of replacements that were performed::
1154
Serhiy Storchakadba90392016-05-10 12:01:23 +03001155 >>> p = re.compile('(blue|white|red)')
1156 >>> p.subn('colour', 'blue socks and red shoes')
Georg Brandl116aa622007-08-15 14:28:22 +00001157 ('colour socks and colour shoes', 2)
Serhiy Storchakadba90392016-05-10 12:01:23 +03001158 >>> p.subn('colour', 'no colours at all')
Georg Brandl116aa622007-08-15 14:28:22 +00001159 ('no colours at all', 0)
1160
Serhiy Storchakafbb490f2018-01-04 11:06:13 +02001161Empty matches are replaced only when they're not adjacent to a previous empty match.
Georg Brandl116aa622007-08-15 14:28:22 +00001162::
1163
1164 >>> p = re.compile('x*')
1165 >>> p.sub('-', 'abxd')
Serhiy Storchakafbb490f2018-01-04 11:06:13 +02001166 '-a-b--d-'
Georg Brandl116aa622007-08-15 14:28:22 +00001167
1168If *replacement* is a string, any backslash escapes in it are processed. That
1169is, ``\n`` is converted to a single newline character, ``\r`` is converted to a
Serhiy Storchakaa54aae02015-03-24 22:58:14 +02001170carriage return, and so forth. Unknown escapes such as ``\&`` are left alone.
Georg Brandl116aa622007-08-15 14:28:22 +00001171Backreferences, such as ``\6``, are replaced with the substring matched by the
1172corresponding group in the RE. This lets you incorporate portions of the
1173original text in the resulting replacement string.
1174
1175This example matches the word ``section`` followed by a string enclosed in
1176``{``, ``}``, and changes ``section`` to ``subsection``::
1177
1178 >>> p = re.compile('section{ ( [^}]* ) }', re.VERBOSE)
1179 >>> p.sub(r'subsection{\1}','section{First} section{second}')
1180 'subsection{First} subsection{second}'
1181
1182There's also a syntax for referring to named groups as defined by the
1183``(?P<name>...)`` syntax. ``\g<name>`` will use the substring matched by the
1184group named ``name``, and ``\g<number>`` uses the corresponding group number.
1185``\g<2>`` is therefore equivalent to ``\2``, but isn't ambiguous in a
1186replacement string such as ``\g<2>0``. (``\20`` would be interpreted as a
1187reference to group 20, not a reference to group 2 followed by the literal
1188character ``'0'``.) The following substitutions are all equivalent, but use all
1189three variations of the replacement string. ::
1190
1191 >>> p = re.compile('section{ (?P<name> [^}]* ) }', re.VERBOSE)
1192 >>> p.sub(r'subsection{\1}','section{First}')
1193 'subsection{First}'
1194 >>> p.sub(r'subsection{\g<1>}','section{First}')
1195 'subsection{First}'
1196 >>> p.sub(r'subsection{\g<name>}','section{First}')
1197 'subsection{First}'
1198
1199*replacement* can also be a function, which gives you even more control. If
1200*replacement* is a function, the function is called for every non-overlapping
Ezio Melotti090f7be2012-12-25 18:10:49 +02001201occurrence of *pattern*. On each call, the function is passed a
1202:ref:`match object <match-objects>` argument for the match and can use this
1203information to compute the desired replacement string and return it.
Georg Brandl116aa622007-08-15 14:28:22 +00001204
Ezio Melotti090f7be2012-12-25 18:10:49 +02001205In the following example, the replacement function translates decimals into
Georg Brandl116aa622007-08-15 14:28:22 +00001206hexadecimal::
1207
Ezio Melotti13bec9b2012-09-17 05:29:47 +03001208 >>> def hexrepl(match):
Georg Brandl116aa622007-08-15 14:28:22 +00001209 ... "Return the hex string for a decimal number"
Ezio Melotti13bec9b2012-09-17 05:29:47 +03001210 ... value = int(match.group())
Georg Brandl116aa622007-08-15 14:28:22 +00001211 ... return hex(value)
1212 ...
1213 >>> p = re.compile(r'\d+')
1214 >>> p.sub(hexrepl, 'Call 65490 for printing, 49152 for user code.')
1215 'Call 0xffd2 for printing, 0xc000 for user code.'
1216
1217When using the module-level :func:`re.sub` function, the pattern is passed as
Benjamin Peterson8cc7d882009-06-01 23:14:51 +00001218the first argument. The pattern may be provided as an object or as a string; if
Georg Brandl116aa622007-08-15 14:28:22 +00001219you need to specify regular expression flags, you must either use a
Benjamin Peterson8cc7d882009-06-01 23:14:51 +00001220pattern object as the first parameter, or use embedded modifiers in the
1221pattern string, e.g. ``sub("(?i)b+", "x", "bbbb BBBB")`` returns ``'x x'``.
Georg Brandl116aa622007-08-15 14:28:22 +00001222
1223
1224Common Problems
1225===============
1226
1227Regular expressions are a powerful tool for some applications, but in some ways
1228their behaviour isn't intuitive and at times they don't behave the way you may
1229expect them to. This section will point out some of the most common pitfalls.
1230
1231
1232Use String Methods
1233------------------
1234
1235Sometimes using the :mod:`re` module is a mistake. If you're matching a fixed
1236string, or a single character class, and you're not using any :mod:`re` features
Serhiy Storchakacd195e22017-10-14 11:14:26 +03001237such as the :const:`~re.IGNORECASE` flag, then the full power of regular expressions
Georg Brandl116aa622007-08-15 14:28:22 +00001238may not be required. Strings have several methods for performing operations with
1239fixed strings and they're usually much faster, because the implementation is a
1240single small C loop that's been optimized for the purpose, instead of the large,
1241more generalized regular expression engine.
1242
1243One example might be replacing a single fixed string with another one; for
Serhiy Storchakacd195e22017-10-14 11:14:26 +03001244example, you might replace ``word`` with ``deed``. :func:`re.sub` seems like the
1245function to use for this, but consider the :meth:`~str.replace` method. Note that
1246:meth:`!replace` will also replace ``word`` inside words, turning ``swordfish``
Georg Brandl116aa622007-08-15 14:28:22 +00001247into ``sdeedfish``, but the naive RE ``word`` would have done that, too. (To
1248avoid performing the substitution on parts of words, the pattern would have to
1249be ``\bword\b``, in order to require that ``word`` have a word boundary on
Serhiy Storchakacd195e22017-10-14 11:14:26 +03001250either side. This takes the job beyond :meth:`!replace`'s abilities.)
Georg Brandl116aa622007-08-15 14:28:22 +00001251
1252Another common task is deleting every occurrence of a single character from a
1253string or replacing it with another single character. You might do this with
Serhiy Storchakacd195e22017-10-14 11:14:26 +03001254something like ``re.sub('\n', ' ', S)``, but :meth:`~str.translate` is capable of
Georg Brandl116aa622007-08-15 14:28:22 +00001255doing both tasks and will be faster than any regular expression operation can
1256be.
1257
1258In short, before turning to the :mod:`re` module, consider whether your problem
1259can be solved with a faster and simpler string method.
1260
1261
1262match() versus search()
1263-----------------------
1264
Serhiy Storchakacd195e22017-10-14 11:14:26 +03001265The :func:`~re.match` function only checks if the RE matches at the beginning of the
1266string while :func:`~re.search` will scan forward through the string for a match.
1267It's important to keep this distinction in mind. Remember, :func:`!match` will
Georg Brandl116aa622007-08-15 14:28:22 +00001268only report a successful match which will start at 0; if the match wouldn't
Serhiy Storchakacd195e22017-10-14 11:14:26 +03001269start at zero, :func:`!match` will *not* report it. ::
Georg Brandl116aa622007-08-15 14:28:22 +00001270
Georg Brandl6911e3c2007-09-04 07:15:32 +00001271 >>> print(re.match('super', 'superstition').span())
Georg Brandl116aa622007-08-15 14:28:22 +00001272 (0, 5)
Georg Brandl6911e3c2007-09-04 07:15:32 +00001273 >>> print(re.match('super', 'insuperable'))
Georg Brandl116aa622007-08-15 14:28:22 +00001274 None
1275
Serhiy Storchakacd195e22017-10-14 11:14:26 +03001276On the other hand, :func:`~re.search` will scan forward through the string,
Georg Brandl116aa622007-08-15 14:28:22 +00001277reporting the first match it finds. ::
1278
Georg Brandl6911e3c2007-09-04 07:15:32 +00001279 >>> print(re.search('super', 'superstition').span())
Georg Brandl116aa622007-08-15 14:28:22 +00001280 (0, 5)
Georg Brandl6911e3c2007-09-04 07:15:32 +00001281 >>> print(re.search('super', 'insuperable').span())
Georg Brandl116aa622007-08-15 14:28:22 +00001282 (2, 7)
1283
1284Sometimes you'll be tempted to keep using :func:`re.match`, and just add ``.*``
1285to the front of your RE. Resist this temptation and use :func:`re.search`
1286instead. The regular expression compiler does some analysis of REs in order to
1287speed up the process of looking for a match. One such analysis figures out what
1288the first character of a match must be; for example, a pattern starting with
1289``Crow`` must match starting with a ``'C'``. The analysis lets the engine
1290quickly scan through the string looking for the starting character, only trying
1291the full match if a ``'C'`` is found.
1292
1293Adding ``.*`` defeats this optimization, requiring scanning to the end of the
1294string and then backtracking to find a match for the rest of the RE. Use
1295:func:`re.search` instead.
1296
1297
1298Greedy versus Non-Greedy
1299------------------------
1300
1301When repeating a regular expression, as in ``a*``, the resulting action is to
1302consume as much of the pattern as possible. This fact often bites you when
1303you're trying to match a pair of balanced delimiters, such as the angle brackets
1304surrounding an HTML tag. The naive pattern for matching a single HTML tag
1305doesn't work because of the greedy nature of ``.*``. ::
1306
1307 >>> s = '<html><head><title>Title</title>'
1308 >>> len(s)
1309 32
Georg Brandl6911e3c2007-09-04 07:15:32 +00001310 >>> print(re.match('<.*>', s).span())
Georg Brandl116aa622007-08-15 14:28:22 +00001311 (0, 32)
Georg Brandl6911e3c2007-09-04 07:15:32 +00001312 >>> print(re.match('<.*>', s).group())
Georg Brandl116aa622007-08-15 14:28:22 +00001313 <html><head><title>Title</title>
1314
Serhiy Storchakacd195e22017-10-14 11:14:26 +03001315The RE matches the ``'<'`` in ``'<html>'``, and the ``.*`` consumes the rest of
Georg Brandl116aa622007-08-15 14:28:22 +00001316the string. There's still more left in the RE, though, and the ``>`` can't
1317match at the end of the string, so the regular expression engine has to
1318backtrack character by character until it finds a match for the ``>``. The
Serhiy Storchakacd195e22017-10-14 11:14:26 +03001319final match extends from the ``'<'`` in ``'<html>'`` to the ``'>'`` in
1320``'</title>'``, which isn't what you want.
Georg Brandl116aa622007-08-15 14:28:22 +00001321
1322In this case, the solution is to use the non-greedy qualifiers ``*?``, ``+?``,
1323``??``, or ``{m,n}?``, which match as *little* text as possible. In the above
1324example, the ``'>'`` is tried immediately after the first ``'<'`` matches, and
1325when it fails, the engine advances a character at a time, retrying the ``'>'``
1326at every step. This produces just the right result::
1327
Georg Brandl6911e3c2007-09-04 07:15:32 +00001328 >>> print(re.match('<.*?>', s).group())
Georg Brandl116aa622007-08-15 14:28:22 +00001329 <html>
1330
1331(Note that parsing HTML or XML with regular expressions is painful.
1332Quick-and-dirty patterns will handle common cases, but HTML and XML have special
1333cases that will break the obvious regular expression; by the time you've written
1334a regular expression that handles all of the possible cases, the patterns will
1335be *very* complicated. Use an HTML or XML parser module for such tasks.)
1336
1337
Terry Reedy8663e342011-01-10 21:49:11 +00001338Using re.VERBOSE
1339----------------
Georg Brandl116aa622007-08-15 14:28:22 +00001340
1341By now you've probably noticed that regular expressions are a very compact
1342notation, but they're not terribly readable. REs of moderate complexity can
1343become lengthy collections of backslashes, parentheses, and metacharacters,
1344making them difficult to read and understand.
1345
Serhiy Storchakacd195e22017-10-14 11:14:26 +03001346For such REs, specifying the :const:`re.VERBOSE` flag when compiling the regular
Georg Brandl116aa622007-08-15 14:28:22 +00001347expression can be helpful, because it allows you to format the regular
1348expression more clearly.
1349
1350The ``re.VERBOSE`` flag has several effects. Whitespace in the regular
1351expression that *isn't* inside a character class is ignored. This means that an
1352expression such as ``dog | cat`` is equivalent to the less readable ``dog|cat``,
1353but ``[a b]`` will still match the characters ``'a'``, ``'b'``, or a space. In
1354addition, you can also put comments inside a RE; comments extend from a ``#``
1355character to the next newline. When used with triple-quoted strings, this
1356enables REs to be formatted more neatly::
1357
1358 pat = re.compile(r"""
1359 \s* # Skip leading whitespace
1360 (?P<header>[^:]+) # Header name
1361 \s* : # Whitespace, and a colon
1362 (?P<value>.*?) # The header's value -- *? used to
1363 # lose the following trailing whitespace
1364 \s*$ # Trailing whitespace to end-of-line
1365 """, re.VERBOSE)
1366
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001367This is far more readable than::
Georg Brandl116aa622007-08-15 14:28:22 +00001368
1369 pat = re.compile(r"\s*(?P<header>[^:]+)\s*:(?P<value>.*?)\s*$")
1370
Georg Brandl116aa622007-08-15 14:28:22 +00001371
1372Feedback
1373========
1374
1375Regular expressions are a complicated topic. Did this document help you
1376understand them? Were there parts that were unclear, or Problems you
1377encountered that weren't covered here? If so, please send suggestions for
1378improvements to the author.
1379
1380The most complete book on regular expressions is almost certainly Jeffrey
1381Friedl's Mastering Regular Expressions, published by O'Reilly. Unfortunately,
1382it exclusively concentrates on Perl and Java's flavours of regular expressions,
1383and doesn't contain any Python material at all, so it won't be useful as a
1384reference for programming in Python. (The first edition covered Python's
Serhiy Storchakacd195e22017-10-14 11:14:26 +03001385now-removed :mod:`!regex` module, which won't help you much.) Consider checking
Georg Brandl116aa622007-08-15 14:28:22 +00001386it out from your library.