blob: 371ef59ff52b0f3b8dee619852303f0786e682a0 [file] [log] [blame]
Christian Heimes2202f872008-02-06 14:31:34 +00001.. _regex-howto:
2
Georg Brandl116aa622007-08-15 14:28:22 +00003****************************
Georg Brandl6911e3c2007-09-04 07:15:32 +00004 Regular Expression HOWTO
Georg Brandl116aa622007-08-15 14:28:22 +00005****************************
6
Benjamin Petersonf07d0022009-03-21 17:31:58 +00007:Author: A.M. Kuchling <amk@amk.ca>
Georg Brandl116aa622007-08-15 14:28:22 +00008
Christian Heimes5b5e81c2007-12-31 16:14:33 +00009.. TODO:
10 Document lookbehind assertions
11 Better way of displaying a RE, a string, and what it matches
12 Mention optional argument to match.groups()
13 Unicode (at least a reference)
Georg Brandl116aa622007-08-15 14:28:22 +000014
15
16.. topic:: Abstract
17
18 This document is an introductory tutorial to using regular expressions in Python
19 with the :mod:`re` module. It provides a gentler introduction than the
20 corresponding section in the Library Reference.
21
22
23Introduction
24============
25
Georg Brandl116aa622007-08-15 14:28:22 +000026Regular expressions (called REs, or regexes, or regex patterns) are essentially
27a tiny, highly specialized programming language embedded inside Python and made
28available through the :mod:`re` module. Using this little language, you specify
29the rules for the set of possible strings that you want to match; this set might
30contain English sentences, or e-mail addresses, or TeX commands, or anything you
31like. You can then ask questions such as "Does this string match the pattern?",
32or "Is there a match for the pattern anywhere in this string?". You can also
33use REs to modify a string or to split it apart in various ways.
34
35Regular expression patterns are compiled into a series of bytecodes which are
36then executed by a matching engine written in C. For advanced use, it may be
37necessary to pay careful attention to how the engine will execute a given RE,
38and write the RE in a certain way in order to produce bytecode that runs faster.
39Optimization isn't covered in this document, because it requires that you have a
40good understanding of the matching engine's internals.
41
42The regular expression language is relatively small and restricted, so not all
43possible string processing tasks can be done using regular expressions. There
44are also tasks that *can* be done with regular expressions, but the expressions
45turn out to be very complicated. In these cases, you may be better off writing
46Python code to do the processing; while Python code will be slower than an
47elaborate regular expression, it will also probably be more understandable.
48
49
50Simple Patterns
51===============
52
53We'll start by learning about the simplest possible regular expressions. Since
54regular expressions are used to operate on strings, we'll begin with the most
55common task: matching characters.
56
57For a detailed explanation of the computer science underlying regular
58expressions (deterministic and non-deterministic finite automata), you can refer
59to almost any textbook on writing compilers.
60
61
62Matching Characters
63-------------------
64
65Most letters and characters will simply match themselves. For example, the
66regular expression ``test`` will match the string ``test`` exactly. (You can
67enable a case-insensitive mode that would let this RE match ``Test`` or ``TEST``
68as well; more about this later.)
69
70There are exceptions to this rule; some characters are special
71:dfn:`metacharacters`, and don't match themselves. Instead, they signal that
72some out-of-the-ordinary thing should be matched, or they affect other portions
73of the RE by repeating them or changing their meaning. Much of this document is
74devoted to discussing various metacharacters and what they do.
75
76Here's a complete list of the metacharacters; their meanings will be discussed
77in the rest of this HOWTO. ::
78
Georg Brandla2388be2011-03-06 11:07:11 +010079 . ^ $ * + ? { } [ ] \ | ( )
Georg Brandl116aa622007-08-15 14:28:22 +000080
81The first metacharacters we'll look at are ``[`` and ``]``. They're used for
82specifying a character class, which is a set of characters that you wish to
83match. Characters can be listed individually, or a range of characters can be
84indicated by giving two characters and separating them by a ``'-'``. For
85example, ``[abc]`` will match any of the characters ``a``, ``b``, or ``c``; this
86is the same as ``[a-c]``, which uses a range to express the same set of
87characters. If you wanted to match only lowercase letters, your RE would be
88``[a-z]``.
89
Georg Brandl116aa622007-08-15 14:28:22 +000090Metacharacters are not active inside classes. For example, ``[akm$]`` will
91match any of the characters ``'a'``, ``'k'``, ``'m'``, or ``'$'``; ``'$'`` is
92usually a metacharacter, but inside a character class it's stripped of its
93special nature.
94
95You can match the characters not listed within the class by :dfn:`complementing`
96the set. This is indicated by including a ``'^'`` as the first character of the
97class; ``'^'`` outside a character class will simply match the ``'^'``
98character. For example, ``[^5]`` will match any character except ``'5'``.
99
100Perhaps the most important metacharacter is the backslash, ``\``. As in Python
101string literals, the backslash can be followed by various characters to signal
102various special sequences. It's also used to escape all the metacharacters so
103you can still match them in patterns; for example, if you need to match a ``[``
104or ``\``, you can precede them with a backslash to remove their special
105meaning: ``\[`` or ``\\``.
106
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400107Some of the special sequences beginning with ``'\'`` represent
108predefined sets of characters that are often useful, such as the set
109of digits, the set of letters, or the set of anything that isn't
110whitespace.
111
112Let's take an example: ``\w`` matches any alphanumeric character. If
113the regex pattern is expressed in bytes, this is equivalent to the
114class ``[a-zA-Z0-9_]``. If the regex pattern is a string, ``\w`` will
115match all the characters marked as letters in the Unicode database
116provided by the :mod:`unicodedata` module. You can use the more
117restricted definition of ``\w`` in a string pattern by supplying the
118:const:`re.ASCII` flag when compiling the regular expression.
119
120The following list of special sequences isn't complete. For a complete
121list of sequences and expanded class definitions for Unicode string
122patterns, see the last part of :ref:`Regular Expression Syntax
123<re-syntax>` in the Standard Library reference. In general, the
124Unicode versions match any character that's in the appropriate
125category in the Unicode database.
Georg Brandl116aa622007-08-15 14:28:22 +0000126
127``\d``
128 Matches any decimal digit; this is equivalent to the class ``[0-9]``.
129
130``\D``
131 Matches any non-digit character; this is equivalent to the class ``[^0-9]``.
132
133``\s``
134 Matches any whitespace character; this is equivalent to the class ``[
135 \t\n\r\f\v]``.
136
137``\S``
138 Matches any non-whitespace character; this is equivalent to the class ``[^
139 \t\n\r\f\v]``.
140
141``\w``
142 Matches any alphanumeric character; this is equivalent to the class
143 ``[a-zA-Z0-9_]``.
144
145``\W``
146 Matches any non-alphanumeric character; this is equivalent to the class
147 ``[^a-zA-Z0-9_]``.
148
149These sequences can be included inside a character class. For example,
150``[\s,.]`` is a character class that will match any whitespace character, or
151``','`` or ``'.'``.
152
153The final metacharacter in this section is ``.``. It matches anything except a
154newline character, and there's an alternate mode (``re.DOTALL``) where it will
155match even a newline. ``'.'`` is often used where you want to match "any
156character".
157
158
159Repeating Things
160----------------
161
162Being able to match varying sets of characters is the first thing regular
163expressions can do that isn't already possible with the methods available on
164strings. However, if that was the only additional capability of regexes, they
165wouldn't be much of an advance. Another capability is that you can specify that
166portions of the RE must be repeated a certain number of times.
167
168The first metacharacter for repeating things that we'll look at is ``*``. ``*``
169doesn't match the literal character ``*``; instead, it specifies that the
170previous character can be matched zero or more times, instead of exactly once.
171
172For example, ``ca*t`` will match ``ct`` (0 ``a`` characters), ``cat`` (1 ``a``),
173``caaat`` (3 ``a`` characters), and so forth. The RE engine has various
174internal limitations stemming from the size of C's ``int`` type that will
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400175prevent it from matching over 2 billion ``a`` characters; patterns
176are usually not written to match that much data.
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
186this RE against the string ``abcbd``.
187
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
219The end of the RE has now been reached, and it has matched ``abcb``. This
220demonstrates 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,
230``ca+t`` will match ``cat`` (1 ``a``), ``caaat`` (3 ``a``'s), but won't match
231``ct``.
232
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
235being optional. For example, ``home-?brew`` matches either ``homebrew`` or
236``home-brew``.
237
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,
240and 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
242has 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
246omitting *n* results in an upper bound of infinity --- actually, the upper bound
247is the 2-billion limit mentioned earlier, but that might as well be infinity.
248
249Readers of a reductionist bent may notice that the three other qualifiers can
250all be expressed using this notation. ``{0,}`` is the same as ``*``, ``{1,}``
251is equivalent to ``+``, and ``{0,1}`` is the same as ``?``. It's better to use
252``*``, ``+``, or ``?`` when you can, simply because they're shorter and easier
253to read.
254
255
256Using Regular Expressions
257=========================
258
259Now that we've looked at some simple regular expressions, how do we actually use
260them in Python? The :mod:`re` module provides an interface to the regular
261expression engine, allowing you to compile REs into objects and then perform
262matches with them.
263
264
265Compiling Regular Expressions
266-----------------------------
267
Benjamin Peterson8cc7d882009-06-01 23:14:51 +0000268Regular expressions are compiled into pattern objects, which have
Georg Brandl116aa622007-08-15 14:28:22 +0000269methods for various operations such as searching for pattern matches or
270performing string substitutions. ::
271
272 >>> import re
273 >>> p = re.compile('ab*')
Ezio Melotti613a97e2013-11-25 22:47:01 +0200274 >>> p
275 re.compile('ab*')
Georg Brandl116aa622007-08-15 14:28:22 +0000276
277:func:`re.compile` also accepts an optional *flags* argument, used to enable
278various special features and syntax variations. We'll go over the available
279settings later, but for now a single example will do::
280
281 >>> p = re.compile('ab*', re.IGNORECASE)
282
283The RE is passed to :func:`re.compile` as a string. REs are handled as strings
284because regular expressions aren't part of the core Python language, and no
285special syntax was created for expressing them. (There are applications that
286don't need REs at all, so there's no need to bloat the language specification by
287including them.) Instead, the :mod:`re` module is simply a C extension module
288included with Python, just like the :mod:`socket` or :mod:`zlib` modules.
289
290Putting REs in strings keeps the Python language simpler, but has one
291disadvantage which is the topic of the next section.
292
293
294The Backslash Plague
295--------------------
296
297As stated earlier, regular expressions use the backslash character (``'\'``) to
298indicate special forms or to allow special characters to be used without
299invoking their special meaning. This conflicts with Python's usage of the same
300character for the same purpose in string literals.
301
302Let's say you want to write a RE that matches the string ``\section``, which
303might be found in a LaTeX file. To figure out what to write in the program
304code, start with the desired string to be matched. Next, you must escape any
305backslashes and other metacharacters by preceding them with a backslash,
306resulting in the string ``\\section``. The resulting string that must be passed
307to :func:`re.compile` must be ``\\section``. However, to express this as a
308Python string literal, both backslashes must be escaped *again*.
309
310+-------------------+------------------------------------------+
311| Characters | Stage |
312+===================+==========================================+
313| ``\section`` | Text string to be matched |
314+-------------------+------------------------------------------+
315| ``\\section`` | Escaped backslash for :func:`re.compile` |
316+-------------------+------------------------------------------+
317| ``"\\\\section"`` | Escaped backslashes for a string literal |
318+-------------------+------------------------------------------+
319
320In short, to match a literal backslash, one has to write ``'\\\\'`` as the RE
321string, because the regular expression must be ``\\``, and each backslash must
322be expressed as ``\\`` inside a regular Python string literal. In REs that
323feature backslashes repeatedly, this leads to lots of repeated backslashes and
324makes the resulting strings difficult to understand.
325
326The solution is to use Python's raw string notation for regular expressions;
327backslashes are not handled in any special way in a string literal prefixed with
328``'r'``, so ``r"\n"`` is a two-character string containing ``'\'`` and ``'n'``,
329while ``"\n"`` is a one-character string containing a newline. Regular
330expressions will often be written in Python code using this raw string notation.
331
332+-------------------+------------------+
333| Regular String | Raw string |
334+===================+==================+
335| ``"ab*"`` | ``r"ab*"`` |
336+-------------------+------------------+
337| ``"\\\\section"`` | ``r"\\section"`` |
338+-------------------+------------------+
339| ``"\\w+\\s+\\1"`` | ``r"\w+\s+\1"`` |
340+-------------------+------------------+
341
342
343Performing Matches
344------------------
345
346Once you have an object representing a compiled regular expression, what do you
Benjamin Peterson8cc7d882009-06-01 23:14:51 +0000347do with it? Pattern objects have several methods and attributes.
Georg Brandl86def6c2008-01-21 20:36:10 +0000348Only the most significant ones will be covered here; consult the :mod:`re` docs
349for a complete listing.
Georg Brandl116aa622007-08-15 14:28:22 +0000350
351+------------------+-----------------------------------------------+
352| Method/Attribute | Purpose |
353+==================+===============================================+
354| ``match()`` | Determine if the RE matches at the beginning |
355| | of the string. |
356+------------------+-----------------------------------------------+
357| ``search()`` | Scan through a string, looking for any |
358| | location where this RE matches. |
359+------------------+-----------------------------------------------+
360| ``findall()`` | Find all substrings where the RE matches, and |
361| | returns them as a list. |
362+------------------+-----------------------------------------------+
363| ``finditer()`` | Find all substrings where the RE matches, and |
Georg Brandl9afde1c2007-11-01 20:32:30 +0000364| | returns them as an :term:`iterator`. |
Georg Brandl116aa622007-08-15 14:28:22 +0000365+------------------+-----------------------------------------------+
366
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400367:meth:`~re.regex.match` and :meth:`~re.regex.search` return ``None`` if no match can be found. If
Ezio Melotti090f7be2012-12-25 18:10:49 +0200368they're successful, a :ref:`match object <match-objects>` instance is returned,
369containing information about the match: where it starts and ends, the substring
370it matched, and more.
Georg Brandl116aa622007-08-15 14:28:22 +0000371
372You can learn about this by interactively experimenting with the :mod:`re`
Terry Reedy8663e342011-01-10 21:49:11 +0000373module. If you have :mod:`tkinter` available, you may also want to look at
Éric Araujofdfaf0a2012-03-05 15:50:37 +0100374:source:`Tools/demo/redemo.py`, a demonstration program included with the
Georg Brandl116aa622007-08-15 14:28:22 +0000375Python distribution. It allows you to enter REs and strings, and displays
376whether the RE matches or fails. :file:`redemo.py` can be quite useful when
Berker Peksag79af27e2016-06-24 08:54:43 +0300377trying to debug a complicated RE.
Georg Brandl116aa622007-08-15 14:28:22 +0000378
379This HOWTO uses the standard Python interpreter for its examples. First, run the
380Python interpreter, import the :mod:`re` module, and compile a RE::
381
Georg Brandl116aa622007-08-15 14:28:22 +0000382 >>> import re
383 >>> p = re.compile('[a-z]+')
Ezio Melotti613a97e2013-11-25 22:47:01 +0200384 >>> p
385 re.compile('[a-z]+')
Georg Brandl116aa622007-08-15 14:28:22 +0000386
387Now, you can try matching various strings against the RE ``[a-z]+``. An empty
388string shouldn't match at all, since ``+`` means 'one or more repetitions'.
389:meth:`match` should return ``None`` in this case, which will cause the
390interpreter to print no output. You can explicitly print the result of
391:meth:`match` to make this clear. ::
392
393 >>> p.match("")
Georg Brandl6911e3c2007-09-04 07:15:32 +0000394 >>> print(p.match(""))
Georg Brandl116aa622007-08-15 14:28:22 +0000395 None
396
397Now, let's try it on a string that it should match, such as ``tempo``. In this
Ezio Melotti090f7be2012-12-25 18:10:49 +0200398case, :meth:`match` will return a :ref:`match object <match-objects>`, so you
399should store the result in a variable for later use. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000400
401 >>> m = p.match('tempo')
Ezio Melotti13bec9b2012-09-17 05:29:47 +0300402 >>> m #doctest: +ELLIPSIS
Ezio Melotti75719412013-11-23 20:27:27 +0200403 <_sre.SRE_Match object; span=(0, 5), match='tempo'>
Georg Brandl116aa622007-08-15 14:28:22 +0000404
Ezio Melotti090f7be2012-12-25 18:10:49 +0200405Now you can query the :ref:`match object <match-objects>` for information
406about the matching string. :ref:`match object <match-objects>` instances
407also have several methods and attributes; the most important ones are:
Georg Brandl116aa622007-08-15 14:28:22 +0000408
409+------------------+--------------------------------------------+
410| Method/Attribute | Purpose |
411+==================+============================================+
412| ``group()`` | Return the string matched by the RE |
413+------------------+--------------------------------------------+
414| ``start()`` | Return the starting position of the match |
415+------------------+--------------------------------------------+
416| ``end()`` | Return the ending position of the match |
417+------------------+--------------------------------------------+
418| ``span()`` | Return a tuple containing the (start, end) |
419| | positions of the match |
420+------------------+--------------------------------------------+
421
422Trying these methods will soon clarify their meaning::
423
424 >>> m.group()
425 'tempo'
426 >>> m.start(), m.end()
427 (0, 5)
428 >>> m.span()
429 (0, 5)
430
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400431:meth:`~re.match.group` returns the substring that was matched by the RE. :meth:`~re.match.start`
432and :meth:`~re.match.end` return the starting and ending index of the match. :meth:`~re.match.span`
Georg Brandl116aa622007-08-15 14:28:22 +0000433returns both start and end indexes in a single tuple. Since the :meth:`match`
434method only checks if the RE matches at the start of a string, :meth:`start`
Benjamin Peterson8cc7d882009-06-01 23:14:51 +0000435will always be zero. However, the :meth:`search` method of patterns
436scans through the string, so the match may not start at zero in that
Georg Brandl116aa622007-08-15 14:28:22 +0000437case. ::
438
Georg Brandl6911e3c2007-09-04 07:15:32 +0000439 >>> print(p.match('::: message'))
Georg Brandl116aa622007-08-15 14:28:22 +0000440 None
Ezio Melotti13bec9b2012-09-17 05:29:47 +0300441 >>> m = p.search('::: message'); print(m) #doctest: +ELLIPSIS
Ezio Melotti75719412013-11-23 20:27:27 +0200442 <_sre.SRE_Match object; span=(4, 11), match='message'>
Georg Brandl116aa622007-08-15 14:28:22 +0000443 >>> m.group()
444 'message'
445 >>> m.span()
446 (4, 11)
447
Ezio Melotti090f7be2012-12-25 18:10:49 +0200448In actual programs, the most common style is to store the
449:ref:`match object <match-objects>` in a variable, and then check if it was
450``None``. This usually looks like::
Georg Brandl116aa622007-08-15 14:28:22 +0000451
452 p = re.compile( ... )
453 m = p.match( 'string goes here' )
454 if m:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000455 print('Match found: ', m.group())
Georg Brandl116aa622007-08-15 14:28:22 +0000456 else:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000457 print('No match')
Georg Brandl116aa622007-08-15 14:28:22 +0000458
Benjamin Peterson8cc7d882009-06-01 23:14:51 +0000459Two pattern methods return all of the matches for a pattern.
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400460:meth:`~re.regex.findall` returns a list of matching strings::
Georg Brandl116aa622007-08-15 14:28:22 +0000461
462 >>> p = re.compile('\d+')
463 >>> p.findall('12 drummers drumming, 11 pipers piping, 10 lords a-leaping')
464 ['12', '11', '10']
465
466:meth:`findall` has to create the entire list before it can be returned as the
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400467result. The :meth:`~re.regex.finditer` method returns a sequence of
Ezio Melotti090f7be2012-12-25 18:10:49 +0200468:ref:`match object <match-objects>` instances as an :term:`iterator`::
Georg Brandl116aa622007-08-15 14:28:22 +0000469
470 >>> iterator = p.finditer('12 drummers drumming, 11 ... 10 ...')
Ezio Melotti13bec9b2012-09-17 05:29:47 +0300471 >>> iterator #doctest: +ELLIPSIS
Terry Reedy8663e342011-01-10 21:49:11 +0000472 <callable_iterator object at 0x...>
Georg Brandl116aa622007-08-15 14:28:22 +0000473 >>> for match in iterator:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000474 ... print(match.span())
Georg Brandl116aa622007-08-15 14:28:22 +0000475 ...
476 (0, 2)
477 (22, 24)
478 (29, 31)
479
480
481Module-Level Functions
482----------------------
483
Benjamin Peterson8cc7d882009-06-01 23:14:51 +0000484You don't have to create a pattern object and call its methods; the
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400485:mod:`re` module also provides top-level functions called :func:`~re.match`,
486:func:`~re.search`, :func:`~re.findall`, :func:`~re.sub`, and so forth. These functions
487take the same arguments as the corresponding pattern method with
Georg Brandl116aa622007-08-15 14:28:22 +0000488the RE string added as the first argument, and still return either ``None`` or a
Ezio Melotti090f7be2012-12-25 18:10:49 +0200489:ref:`match object <match-objects>` instance. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000490
Georg Brandl6911e3c2007-09-04 07:15:32 +0000491 >>> print(re.match(r'From\s+', 'Fromage amk'))
Georg Brandl116aa622007-08-15 14:28:22 +0000492 None
Ezio Melotti13bec9b2012-09-17 05:29:47 +0300493 >>> re.match(r'From\s+', 'From amk Thu May 14 19:12:10 1998') #doctest: +ELLIPSIS
Ezio Melotti75719412013-11-23 20:27:27 +0200494 <_sre.SRE_Match object; span=(0, 5), match='From '>
Georg Brandl116aa622007-08-15 14:28:22 +0000495
Benjamin Peterson8cc7d882009-06-01 23:14:51 +0000496Under the hood, these functions simply create a pattern object for you
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400497and call the appropriate method on it. They also store the compiled
498object in a cache, so future calls using the same RE won't need to
499parse the pattern again and again.
Georg Brandl116aa622007-08-15 14:28:22 +0000500
501Should you use these module-level functions, or should you get the
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400502pattern and call its methods yourself? If you're accessing a regex
503within a loop, pre-compiling it will save a few function calls.
504Outside of loops, there's not much difference thanks to the internal
505cache.
Georg Brandl116aa622007-08-15 14:28:22 +0000506
507
508Compilation Flags
509-----------------
510
511Compilation flags let you modify some aspects of how regular expressions work.
512Flags are available in the :mod:`re` module under two names, a long name such as
513:const:`IGNORECASE` and a short, one-letter form such as :const:`I`. (If you're
514familiar with Perl's pattern modifiers, the one-letter forms use the same
515letters; the short form of :const:`re.VERBOSE` is :const:`re.X`, for example.)
516Multiple flags can be specified by bitwise OR-ing them; ``re.I | re.M`` sets
517both the :const:`I` and :const:`M` flags, for example.
518
519Here's a table of the available flags, followed by a more detailed explanation
520of each one.
521
522+---------------------------------+--------------------------------------------+
523| Flag | Meaning |
524+=================================+============================================+
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400525| :const:`ASCII`, :const:`A` | Makes several escapes like ``\w``, ``\b``, |
526| | ``\s`` and ``\d`` match only on ASCII |
527| | characters with the respective property. |
528+---------------------------------+--------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000529| :const:`DOTALL`, :const:`S` | Make ``.`` match any character, including |
530| | newlines |
531+---------------------------------+--------------------------------------------+
532| :const:`IGNORECASE`, :const:`I` | Do case-insensitive matches |
533+---------------------------------+--------------------------------------------+
534| :const:`LOCALE`, :const:`L` | Do a locale-aware match |
535+---------------------------------+--------------------------------------------+
536| :const:`MULTILINE`, :const:`M` | Multi-line matching, affecting ``^`` and |
537| | ``$`` |
538+---------------------------------+--------------------------------------------+
539| :const:`VERBOSE`, :const:`X` | Enable verbose REs, which can be organized |
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400540| (for 'extended') | more cleanly and understandably. |
Georg Brandlce9fbd32009-03-31 18:41:03 +0000541+---------------------------------+--------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000542
543
544.. data:: I
545 IGNORECASE
546 :noindex:
547
548 Perform case-insensitive matching; character class and literal strings will
549 match letters by ignoring case. For example, ``[A-Z]`` will match lowercase
550 letters, too, and ``Spam`` will match ``Spam``, ``spam``, or ``spAM``. This
551 lowercasing doesn't take the current locale into account; it will if you also
552 set the :const:`LOCALE` flag.
553
554
555.. data:: L
556 LOCALE
557 :noindex:
558
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400559 Make ``\w``, ``\W``, ``\b``, and ``\B``, dependent on the current locale
560 instead of the Unicode database.
Georg Brandl116aa622007-08-15 14:28:22 +0000561
562 Locales are a feature of the C library intended to help in writing programs that
563 take account of language differences. For example, if you're processing French
564 text, you'd want to be able to write ``\w+`` to match words, but ``\w`` only
565 matches the character class ``[A-Za-z]``; it won't match ``'é'`` or ``'ç'``. If
566 your system is configured properly and a French locale is selected, certain C
567 functions will tell the program that ``'é'`` should also be considered a letter.
568 Setting the :const:`LOCALE` flag when compiling a regular expression will cause
569 the resulting compiled object to use these C functions for ``\w``; this is
570 slower, but also enables ``\w+`` to match French words as you'd expect.
571
572
573.. data:: M
574 MULTILINE
575 :noindex:
576
577 (``^`` and ``$`` haven't been explained yet; they'll be introduced in section
578 :ref:`more-metacharacters`.)
579
580 Usually ``^`` matches only at the beginning of the string, and ``$`` matches
581 only at the end of the string and immediately before the newline (if any) at the
582 end of the string. When this flag is specified, ``^`` matches at the beginning
583 of the string and at the beginning of each line within the string, immediately
584 following each newline. Similarly, the ``$`` metacharacter matches either at
585 the end of the string and at the end of each line (immediately preceding each
586 newline).
587
588
589.. data:: S
590 DOTALL
591 :noindex:
592
593 Makes the ``'.'`` special character match any character at all, including a
594 newline; without this flag, ``'.'`` will match anything *except* a newline.
595
596
Georg Brandlce9fbd32009-03-31 18:41:03 +0000597.. data:: A
598 ASCII
599 :noindex:
600
601 Make ``\w``, ``\W``, ``\b``, ``\B``, ``\s`` and ``\S`` perform ASCII-only
602 matching instead of full Unicode matching. This is only meaningful for
603 Unicode patterns, and is ignored for byte patterns.
604
605
Georg Brandl116aa622007-08-15 14:28:22 +0000606.. data:: X
607 VERBOSE
608 :noindex:
609
610 This flag allows you to write regular expressions that are more readable by
611 granting you more flexibility in how you can format them. When this flag has
612 been specified, whitespace within the RE string is ignored, except when the
613 whitespace is in a character class or preceded by an unescaped backslash; this
614 lets you organize and indent the RE more clearly. This flag also lets you put
615 comments within a RE that will be ignored by the engine; comments are marked by
616 a ``'#'`` that's neither in a character class or preceded by an unescaped
617 backslash.
618
619 For example, here's a RE that uses :const:`re.VERBOSE`; see how much easier it
620 is to read? ::
621
622 charref = re.compile(r"""
Georg Brandl06788c92009-01-03 21:31:47 +0000623 &[#] # Start of a numeric entity reference
Georg Brandl116aa622007-08-15 14:28:22 +0000624 (
625 0[0-7]+ # Octal form
626 | [0-9]+ # Decimal form
627 | x[0-9a-fA-F]+ # Hexadecimal form
628 )
629 ; # Trailing semicolon
630 """, re.VERBOSE)
631
632 Without the verbose setting, the RE would look like this::
633
634 charref = re.compile("&#(0[0-7]+"
635 "|[0-9]+"
636 "|x[0-9a-fA-F]+);")
637
638 In the above example, Python's automatic concatenation of string literals has
639 been used to break up the RE into smaller pieces, but it's still more difficult
640 to understand than the version using :const:`re.VERBOSE`.
641
642
643More Pattern Power
644==================
645
646So far we've only covered a part of the features of regular expressions. In
647this section, we'll cover some new metacharacters, and how to use groups to
648retrieve portions of the text that was matched.
649
650
651.. _more-metacharacters:
652
653More Metacharacters
654-------------------
655
656There are some metacharacters that we haven't covered yet. Most of them will be
657covered in this section.
658
659Some of the remaining metacharacters to be discussed are :dfn:`zero-width
660assertions`. They don't cause the engine to advance through the string;
661instead, they consume no characters at all, and simply succeed or fail. For
662example, ``\b`` is an assertion that the current position is located at a word
663boundary; the position isn't changed by the ``\b`` at all. This means that
664zero-width assertions should never be repeated, because if they match once at a
665given location, they can obviously be matched an infinite number of times.
666
667``|``
668 Alternation, or the "or" operator. If A and B are regular expressions,
669 ``A|B`` will match any string that matches either ``A`` or ``B``. ``|`` has very
670 low precedence in order to make it work reasonably when you're alternating
671 multi-character strings. ``Crow|Servo`` will match either ``Crow`` or ``Servo``,
672 not ``Cro``, a ``'w'`` or an ``'S'``, and ``ervo``.
673
674 To match a literal ``'|'``, use ``\|``, or enclose it inside a character class,
675 as in ``[|]``.
676
677``^``
678 Matches at the beginning of lines. Unless the :const:`MULTILINE` flag has been
679 set, this will only match at the beginning of the string. In :const:`MULTILINE`
680 mode, this also matches immediately after each newline within the string.
681
682 For example, if you wish to match the word ``From`` only at the beginning of a
683 line, the RE to use is ``^From``. ::
684
Ezio Melotti13bec9b2012-09-17 05:29:47 +0300685 >>> print(re.search('^From', 'From Here to Eternity')) #doctest: +ELLIPSIS
Ezio Melotti75719412013-11-23 20:27:27 +0200686 <_sre.SRE_Match object; span=(0, 4), match='From'>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000687 >>> print(re.search('^From', 'Reciting From Memory'))
Georg Brandl116aa622007-08-15 14:28:22 +0000688 None
689
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000690 .. To match a literal \character{\^}, use \regexp{\e\^} or enclose it
691 .. inside a character class, as in \regexp{[{\e}\^]}.
Georg Brandl116aa622007-08-15 14:28:22 +0000692
693``$``
694 Matches at the end of a line, which is defined as either the end of the string,
695 or any location followed by a newline character. ::
696
Ezio Melotti13bec9b2012-09-17 05:29:47 +0300697 >>> print(re.search('}$', '{block}')) #doctest: +ELLIPSIS
Ezio Melotti75719412013-11-23 20:27:27 +0200698 <_sre.SRE_Match object; span=(6, 7), match='}'>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000699 >>> print(re.search('}$', '{block} '))
Georg Brandl116aa622007-08-15 14:28:22 +0000700 None
Ezio Melotti13bec9b2012-09-17 05:29:47 +0300701 >>> print(re.search('}$', '{block}\n')) #doctest: +ELLIPSIS
Ezio Melotti75719412013-11-23 20:27:27 +0200702 <_sre.SRE_Match object; span=(6, 7), match='}'>
Georg Brandl116aa622007-08-15 14:28:22 +0000703
704 To match a literal ``'$'``, use ``\$`` or enclose it inside a character class,
705 as in ``[$]``.
706
Georg Brandl116aa622007-08-15 14:28:22 +0000707``\A``
708 Matches only at the start of the string. When not in :const:`MULTILINE` mode,
709 ``\A`` and ``^`` are effectively the same. In :const:`MULTILINE` mode, they're
710 different: ``\A`` still matches only at the beginning of the string, but ``^``
711 may match at any location inside the string that follows a newline character.
712
713``\Z``
714 Matches only at the end of the string.
715
716``\b``
717 Word boundary. This is a zero-width assertion that matches only at the
718 beginning or end of a word. A word is defined as a sequence of alphanumeric
719 characters, so the end of a word is indicated by whitespace or a
720 non-alphanumeric character.
721
722 The following example matches ``class`` only when it's a complete word; it won't
723 match when it's contained inside another word. ::
724
725 >>> p = re.compile(r'\bclass\b')
Ezio Melotti13bec9b2012-09-17 05:29:47 +0300726 >>> print(p.search('no class at all')) #doctest: +ELLIPSIS
Ezio Melotti75719412013-11-23 20:27:27 +0200727 <_sre.SRE_Match object; span=(3, 8), match='class'>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000728 >>> print(p.search('the declassified algorithm'))
Georg Brandl116aa622007-08-15 14:28:22 +0000729 None
Georg Brandl6911e3c2007-09-04 07:15:32 +0000730 >>> print(p.search('one subclass is'))
Georg Brandl116aa622007-08-15 14:28:22 +0000731 None
732
733 There are two subtleties you should remember when using this special sequence.
734 First, this is the worst collision between Python's string literals and regular
735 expression sequences. In Python's string literals, ``\b`` is the backspace
736 character, ASCII value 8. If you're not using raw strings, then Python will
737 convert the ``\b`` to a backspace, and your RE won't match as you expect it to.
738 The following example looks the same as our previous RE, but omits the ``'r'``
739 in front of the RE string. ::
740
741 >>> p = re.compile('\bclass\b')
Georg Brandl6911e3c2007-09-04 07:15:32 +0000742 >>> print(p.search('no class at all'))
Georg Brandl116aa622007-08-15 14:28:22 +0000743 None
Ezio Melotti13bec9b2012-09-17 05:29:47 +0300744 >>> print(p.search('\b' + 'class' + '\b')) #doctest: +ELLIPSIS
Ezio Melotti75719412013-11-23 20:27:27 +0200745 <_sre.SRE_Match object; span=(0, 7), match='\x08class\x08'>
Georg Brandl116aa622007-08-15 14:28:22 +0000746
747 Second, inside a character class, where there's no use for this assertion,
748 ``\b`` represents the backspace character, for compatibility with Python's
749 string literals.
750
751``\B``
752 Another zero-width assertion, this is the opposite of ``\b``, only matching when
753 the current position is not at a word boundary.
754
755
756Grouping
757--------
758
759Frequently you need to obtain more information than just whether the RE matched
760or not. Regular expressions are often used to dissect strings by writing a RE
761divided into several subgroups which match different components of interest.
762For example, an RFC-822 header line is divided into a header name and a value,
763separated by a ``':'``, like this::
764
765 From: author@example.com
766 User-Agent: Thunderbird 1.5.0.9 (X11/20061227)
767 MIME-Version: 1.0
768 To: editor@example.com
769
770This can be handled by writing a regular expression which matches an entire
771header line, and has one group which matches the header name, and another group
772which matches the header's value.
773
774Groups are marked by the ``'('``, ``')'`` metacharacters. ``'('`` and ``')'``
775have much the same meaning as they do in mathematical expressions; they group
776together the expressions contained inside them, and you can repeat the contents
777of a group with a repeating qualifier, such as ``*``, ``+``, ``?``, or
778``{m,n}``. For example, ``(ab)*`` will match zero or more repetitions of
779``ab``. ::
780
781 >>> p = re.compile('(ab)*')
Georg Brandl6911e3c2007-09-04 07:15:32 +0000782 >>> print(p.match('ababababab').span())
Georg Brandl116aa622007-08-15 14:28:22 +0000783 (0, 10)
784
785Groups indicated with ``'('``, ``')'`` also capture the starting and ending
786index of the text that they match; this can be retrieved by passing an argument
787to :meth:`group`, :meth:`start`, :meth:`end`, and :meth:`span`. Groups are
788numbered starting with 0. Group 0 is always present; it's the whole RE, so
Ezio Melotti090f7be2012-12-25 18:10:49 +0200789:ref:`match object <match-objects>` methods all have group 0 as their default
790argument. Later we'll see how to express groups that don't capture the span
791of text that they match. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000792
793 >>> p = re.compile('(a)b')
794 >>> m = p.match('ab')
795 >>> m.group()
796 'ab'
797 >>> m.group(0)
798 'ab'
799
800Subgroups are numbered from left to right, from 1 upward. Groups can be nested;
801to determine the number, just count the opening parenthesis characters, going
802from left to right. ::
803
804 >>> p = re.compile('(a(b)c)d')
805 >>> m = p.match('abcd')
806 >>> m.group(0)
807 'abcd'
808 >>> m.group(1)
809 'abc'
810 >>> m.group(2)
811 'b'
812
813:meth:`group` can be passed multiple group numbers at a time, in which case it
814will return a tuple containing the corresponding values for those groups. ::
815
816 >>> m.group(2,1,2)
817 ('b', 'abc', 'b')
818
819The :meth:`groups` method returns a tuple containing the strings for all the
820subgroups, from 1 up to however many there are. ::
821
822 >>> m.groups()
823 ('abc', 'b')
824
825Backreferences in a pattern allow you to specify that the contents of an earlier
826capturing group must also be found at the current location in the string. For
827example, ``\1`` will succeed if the exact contents of group 1 can be found at
828the current position, and fails otherwise. Remember that Python's string
829literals also use a backslash followed by numbers to allow including arbitrary
830characters in a string, so be sure to use a raw string when incorporating
831backreferences in a RE.
832
833For example, the following RE detects doubled words in a string. ::
834
835 >>> p = re.compile(r'(\b\w+)\s+\1')
836 >>> p.search('Paris in the the spring').group()
837 'the the'
838
839Backreferences like this aren't often useful for just searching through a string
840--- there are few text formats which repeat data in this way --- but you'll soon
841find out that they're *very* useful when performing string substitutions.
842
843
844Non-capturing and Named Groups
845------------------------------
846
847Elaborate REs may use many groups, both to capture substrings of interest, and
848to group and structure the RE itself. In complex REs, it becomes difficult to
849keep track of the group numbers. There are two features which help with this
850problem. Both of them use a common syntax for regular expression extensions, so
851we'll look at that first.
852
Donald Stufft8b852f12014-05-20 12:58:38 -0400853Perl 5 is well known for its powerful additions to standard regular expressions.
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400854For these new features the Perl developers couldn't choose new single-keystroke metacharacters
855or new special sequences beginning with ``\`` without making Perl's regular
856expressions confusingly different from standard REs. If they chose ``&`` as a
Georg Brandl116aa622007-08-15 14:28:22 +0000857new metacharacter, for example, old expressions would be assuming that ``&`` was
858a regular character and wouldn't have escaped it by writing ``\&`` or ``[&]``.
859
860The solution chosen by the Perl developers was to use ``(?...)`` as the
861extension syntax. ``?`` immediately after a parenthesis was a syntax error
862because the ``?`` would have nothing to repeat, so this didn't introduce any
863compatibility problems. The characters immediately after the ``?`` indicate
864what extension is being used, so ``(?=foo)`` is one thing (a positive lookahead
865assertion) and ``(?:foo)`` is something else (a non-capturing group containing
866the subexpression ``foo``).
867
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400868Python supports several of Perl's extensions and adds an extension
869syntax to Perl's extension syntax. If the first character after the
870question mark is a ``P``, you know that it's an extension that's
871specific to Python.
Georg Brandl116aa622007-08-15 14:28:22 +0000872
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400873Now that we've looked at the general extension syntax, we can return
874to the features that simplify working with groups in complex REs.
Georg Brandl116aa622007-08-15 14:28:22 +0000875
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400876Sometimes you'll want to use a group to denote a part of a regular expression,
Georg Brandl116aa622007-08-15 14:28:22 +0000877but aren't interested in retrieving the group's contents. You can make this fact
878explicit by using a non-capturing group: ``(?:...)``, where you can replace the
879``...`` with any other regular expression. ::
880
881 >>> m = re.match("([abc])+", "abc")
882 >>> m.groups()
883 ('c',)
884 >>> m = re.match("(?:[abc])+", "abc")
885 >>> m.groups()
886 ()
887
888Except for the fact that you can't retrieve the contents of what the group
889matched, a non-capturing group behaves exactly the same as a capturing group;
890you can put anything inside it, repeat it with a repetition metacharacter such
891as ``*``, and nest it within other groups (capturing or non-capturing).
892``(?:...)`` is particularly useful when modifying an existing pattern, since you
893can add new groups without changing how all the other groups are numbered. It
894should be mentioned that there's no performance difference in searching between
895capturing and non-capturing groups; neither form is any faster than the other.
896
897A more significant feature is named groups: instead of referring to them by
898numbers, groups can be referenced by a name.
899
900The syntax for a named group is one of the Python-specific extensions:
901``(?P<name>...)``. *name* is, obviously, the name of the group. Named groups
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400902behave exactly like capturing groups, and additionally associate a name
Ezio Melotti090f7be2012-12-25 18:10:49 +0200903with a group. The :ref:`match object <match-objects>` methods that deal with
904capturing groups all accept either integers that refer to the group by number
905or strings that contain the desired group's name. Named groups are still
906given numbers, so you can retrieve information about a group in two ways::
Georg Brandl116aa622007-08-15 14:28:22 +0000907
908 >>> p = re.compile(r'(?P<word>\b\w+\b)')
909 >>> m = p.search( '(((( Lots of punctuation )))' )
910 >>> m.group('word')
911 'Lots'
912 >>> m.group(1)
913 'Lots'
914
915Named groups are handy because they let you use easily-remembered names, instead
916of having to remember numbers. Here's an example RE from the :mod:`imaplib`
917module::
918
919 InternalDate = re.compile(r'INTERNALDATE "'
920 r'(?P<day>[ 123][0-9])-(?P<mon>[A-Z][a-z][a-z])-'
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000921 r'(?P<year>[0-9][0-9][0-9][0-9])'
Georg Brandl116aa622007-08-15 14:28:22 +0000922 r' (?P<hour>[0-9][0-9]):(?P<min>[0-9][0-9]):(?P<sec>[0-9][0-9])'
923 r' (?P<zonen>[-+])(?P<zoneh>[0-9][0-9])(?P<zonem>[0-9][0-9])'
924 r'"')
925
926It's obviously much easier to retrieve ``m.group('zonem')``, instead of having
927to remember to retrieve group 9.
928
929The syntax for backreferences in an expression such as ``(...)\1`` refers to the
930number of the group. There's naturally a variant that uses the group name
931instead of the number. This is another Python extension: ``(?P=name)`` indicates
932that the contents of the group called *name* should again be matched at the
933current point. The regular expression for finding doubled words,
934``(\b\w+)\s+\1`` can also be written as ``(?P<word>\b\w+)\s+(?P=word)``::
935
936 >>> p = re.compile(r'(?P<word>\b\w+)\s+(?P=word)')
937 >>> p.search('Paris in the the spring').group()
938 'the the'
939
940
941Lookahead Assertions
942--------------------
943
944Another zero-width assertion is the lookahead assertion. Lookahead assertions
945are available in both positive and negative form, and look like this:
946
947``(?=...)``
948 Positive lookahead assertion. This succeeds if the contained regular
949 expression, represented here by ``...``, successfully matches at the current
950 location, and fails otherwise. But, once the contained expression has been
951 tried, the matching engine doesn't advance at all; the rest of the pattern is
952 tried right where the assertion started.
953
954``(?!...)``
955 Negative lookahead assertion. This is the opposite of the positive assertion;
956 it succeeds if the contained expression *doesn't* match at the current position
957 in the string.
958
959To make this concrete, let's look at a case where a lookahead is useful.
960Consider a simple pattern to match a filename and split it apart into a base
961name and an extension, separated by a ``.``. For example, in ``news.rc``,
962``news`` is the base name, and ``rc`` is the filename's extension.
963
964The pattern to match this is quite simple:
965
966``.*[.].*$``
967
968Notice that the ``.`` needs to be treated specially because it's a
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -0400969metacharacter, so it's inside a character class to only match that
970specific character. Also notice the trailing ``$``; this is added to
971ensure that all the rest of the string must be included in the
972extension. This regular expression matches ``foo.bar`` and
Georg Brandl116aa622007-08-15 14:28:22 +0000973``autoexec.bat`` and ``sendmail.cf`` and ``printers.conf``.
974
975Now, consider complicating the problem a bit; what if you want to match
976filenames where the extension is not ``bat``? Some incorrect attempts:
977
978``.*[.][^b].*$`` The first attempt above tries to exclude ``bat`` by requiring
979that the first character of the extension is not a ``b``. This is wrong,
980because the pattern also doesn't match ``foo.bar``.
981
Georg Brandl116aa622007-08-15 14:28:22 +0000982``.*[.]([^b]..|.[^a].|..[^t])$``
983
Georg Brandl116aa622007-08-15 14:28:22 +0000984The expression gets messier when you try to patch up the first solution by
985requiring one of the following cases to match: the first character of the
986extension isn't ``b``; the second character isn't ``a``; or the third character
987isn't ``t``. This accepts ``foo.bar`` and rejects ``autoexec.bat``, but it
988requires a three-letter extension and won't accept a filename with a two-letter
989extension such as ``sendmail.cf``. We'll complicate the pattern again in an
990effort to fix it.
991
992``.*[.]([^b].?.?|.[^a]?.?|..?[^t]?)$``
993
994In the third attempt, the second and third letters are all made optional in
995order to allow matching extensions shorter than three characters, such as
996``sendmail.cf``.
997
998The pattern's getting really complicated now, which makes it hard to read and
999understand. Worse, if the problem changes and you want to exclude both ``bat``
1000and ``exe`` as extensions, the pattern would get even more complicated and
1001confusing.
1002
1003A negative lookahead cuts through all this confusion:
1004
Ezio Melotti84c63e82016-01-12 00:09:13 +02001005``.*[.](?!bat$)[^.]*$`` The negative lookahead means: if the expression ``bat``
Georg Brandl116aa622007-08-15 14:28:22 +00001006doesn't match at this point, try the rest of the pattern; if ``bat$`` does
1007match, the whole pattern will fail. The trailing ``$`` is required to ensure
1008that something like ``sample.batch``, where the extension only starts with
Ezio Melotti84c63e82016-01-12 00:09:13 +02001009``bat``, will be allowed. The ``[^.]*`` makes sure that the pattern works
1010when there are multiple dots in the filename.
Georg Brandl116aa622007-08-15 14:28:22 +00001011
Georg Brandl116aa622007-08-15 14:28:22 +00001012Excluding another filename extension is now easy; simply add it as an
1013alternative inside the assertion. The following pattern excludes filenames that
1014end in either ``bat`` or ``exe``:
1015
Ezio Melotti84c63e82016-01-12 00:09:13 +02001016``.*[.](?!bat$|exe$)[^.]*$``
Georg Brandl116aa622007-08-15 14:28:22 +00001017
Georg Brandl116aa622007-08-15 14:28:22 +00001018
1019Modifying Strings
1020=================
1021
1022Up to this point, we've simply performed searches against a static string.
1023Regular expressions are also commonly used to modify strings in various ways,
Benjamin Peterson8cc7d882009-06-01 23:14:51 +00001024using the following pattern methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001025
1026+------------------+-----------------------------------------------+
1027| Method/Attribute | Purpose |
1028+==================+===============================================+
1029| ``split()`` | Split the string into a list, splitting it |
1030| | wherever the RE matches |
1031+------------------+-----------------------------------------------+
1032| ``sub()`` | Find all substrings where the RE matches, and |
1033| | replace them with a different string |
1034+------------------+-----------------------------------------------+
1035| ``subn()`` | Does the same thing as :meth:`sub`, but |
1036| | returns the new string and the number of |
1037| | replacements |
1038+------------------+-----------------------------------------------+
1039
1040
1041Splitting Strings
1042-----------------
1043
Benjamin Peterson8cc7d882009-06-01 23:14:51 +00001044The :meth:`split` method of a pattern splits a string apart
Georg Brandl116aa622007-08-15 14:28:22 +00001045wherever the RE matches, returning a list of the pieces. It's similar to the
1046:meth:`split` method of strings but provides much more generality in the
Andrew Kuchling3f4f3ba2013-08-18 18:57:22 -04001047delimiters that you can split by; string :meth:`split` only supports splitting by
Georg Brandl116aa622007-08-15 14:28:22 +00001048whitespace or by a fixed string. As you'd expect, there's a module-level
1049:func:`re.split` function, too.
1050
1051
1052.. method:: .split(string [, maxsplit=0])
1053 :noindex:
1054
1055 Split *string* by the matches of the regular expression. If capturing
1056 parentheses are used in the RE, then their contents will also be returned as
1057 part of the resulting list. If *maxsplit* is nonzero, at most *maxsplit* splits
1058 are performed.
1059
1060You can limit the number of splits made, by passing a value for *maxsplit*.
1061When *maxsplit* is nonzero, at most *maxsplit* splits will be made, and the
1062remainder of the string is returned as the final element of the list. In the
1063following example, the delimiter is any sequence of non-alphanumeric characters.
1064::
1065
1066 >>> p = re.compile(r'\W+')
1067 >>> p.split('This is a test, short and sweet, of split().')
1068 ['This', 'is', 'a', 'test', 'short', 'and', 'sweet', 'of', 'split', '']
1069 >>> p.split('This is a test, short and sweet, of split().', 3)
1070 ['This', 'is', 'a', 'test, short and sweet, of split().']
1071
1072Sometimes you're not only interested in what the text between delimiters is, but
1073also need to know what the delimiter was. If capturing parentheses are used in
1074the RE, then their values are also returned as part of the list. Compare the
1075following calls::
1076
1077 >>> p = re.compile(r'\W+')
1078 >>> p2 = re.compile(r'(\W+)')
1079 >>> p.split('This... is a test.')
1080 ['This', 'is', 'a', 'test', '']
1081 >>> p2.split('This... is a test.')
1082 ['This', '... ', 'is', ' ', 'a', ' ', 'test', '.', '']
1083
1084The module-level function :func:`re.split` adds the RE to be used as the first
1085argument, but is otherwise the same. ::
1086
1087 >>> re.split('[\W]+', 'Words, words, words.')
1088 ['Words', 'words', 'words', '']
1089 >>> re.split('([\W]+)', 'Words, words, words.')
1090 ['Words', ', ', 'words', ', ', 'words', '.', '']
1091 >>> re.split('[\W]+', 'Words, words, words.', 1)
1092 ['Words', 'words, words.']
1093
1094
1095Search and Replace
1096------------------
1097
1098Another common task is to find all the matches for a pattern, and replace them
1099with a different string. The :meth:`sub` method takes a replacement value,
1100which can be either a string or a function, and the string to be processed.
1101
Georg Brandl116aa622007-08-15 14:28:22 +00001102.. method:: .sub(replacement, string[, count=0])
1103 :noindex:
1104
1105 Returns the string obtained by replacing the leftmost non-overlapping
1106 occurrences of the RE in *string* by the replacement *replacement*. If the
1107 pattern isn't found, *string* is returned unchanged.
1108
1109 The optional argument *count* is the maximum number of pattern occurrences to be
1110 replaced; *count* must be a non-negative integer. The default value of 0 means
1111 to replace all occurrences.
1112
1113Here's a simple example of using the :meth:`sub` method. It replaces colour
1114names with the word ``colour``::
1115
Serhiy Storchakadba90392016-05-10 12:01:23 +03001116 >>> p = re.compile('(blue|white|red)')
1117 >>> p.sub('colour', 'blue socks and red shoes')
Georg Brandl116aa622007-08-15 14:28:22 +00001118 'colour socks and colour shoes'
Serhiy Storchakadba90392016-05-10 12:01:23 +03001119 >>> p.sub('colour', 'blue socks and red shoes', count=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001120 'colour socks and red shoes'
1121
1122The :meth:`subn` method does the same work, but returns a 2-tuple containing the
1123new string value and the number of replacements that were performed::
1124
Serhiy Storchakadba90392016-05-10 12:01:23 +03001125 >>> p = re.compile('(blue|white|red)')
1126 >>> p.subn('colour', 'blue socks and red shoes')
Georg Brandl116aa622007-08-15 14:28:22 +00001127 ('colour socks and colour shoes', 2)
Serhiy Storchakadba90392016-05-10 12:01:23 +03001128 >>> p.subn('colour', 'no colours at all')
Georg Brandl116aa622007-08-15 14:28:22 +00001129 ('no colours at all', 0)
1130
1131Empty matches are replaced only when they're not adjacent to a previous match.
1132::
1133
1134 >>> p = re.compile('x*')
1135 >>> p.sub('-', 'abxd')
1136 '-a-b-d-'
1137
1138If *replacement* is a string, any backslash escapes in it are processed. That
1139is, ``\n`` is converted to a single newline character, ``\r`` is converted to a
Serhiy Storchakaa54aae02015-03-24 22:58:14 +02001140carriage return, and so forth. Unknown escapes such as ``\&`` are left alone.
Georg Brandl116aa622007-08-15 14:28:22 +00001141Backreferences, such as ``\6``, are replaced with the substring matched by the
1142corresponding group in the RE. This lets you incorporate portions of the
1143original text in the resulting replacement string.
1144
1145This example matches the word ``section`` followed by a string enclosed in
1146``{``, ``}``, and changes ``section`` to ``subsection``::
1147
1148 >>> p = re.compile('section{ ( [^}]* ) }', re.VERBOSE)
1149 >>> p.sub(r'subsection{\1}','section{First} section{second}')
1150 'subsection{First} subsection{second}'
1151
1152There's also a syntax for referring to named groups as defined by the
1153``(?P<name>...)`` syntax. ``\g<name>`` will use the substring matched by the
1154group named ``name``, and ``\g<number>`` uses the corresponding group number.
1155``\g<2>`` is therefore equivalent to ``\2``, but isn't ambiguous in a
1156replacement string such as ``\g<2>0``. (``\20`` would be interpreted as a
1157reference to group 20, not a reference to group 2 followed by the literal
1158character ``'0'``.) The following substitutions are all equivalent, but use all
1159three variations of the replacement string. ::
1160
1161 >>> p = re.compile('section{ (?P<name> [^}]* ) }', re.VERBOSE)
1162 >>> p.sub(r'subsection{\1}','section{First}')
1163 'subsection{First}'
1164 >>> p.sub(r'subsection{\g<1>}','section{First}')
1165 'subsection{First}'
1166 >>> p.sub(r'subsection{\g<name>}','section{First}')
1167 'subsection{First}'
1168
1169*replacement* can also be a function, which gives you even more control. If
1170*replacement* is a function, the function is called for every non-overlapping
Ezio Melotti090f7be2012-12-25 18:10:49 +02001171occurrence of *pattern*. On each call, the function is passed a
1172:ref:`match object <match-objects>` argument for the match and can use this
1173information to compute the desired replacement string and return it.
Georg Brandl116aa622007-08-15 14:28:22 +00001174
Ezio Melotti090f7be2012-12-25 18:10:49 +02001175In the following example, the replacement function translates decimals into
Georg Brandl116aa622007-08-15 14:28:22 +00001176hexadecimal::
1177
Ezio Melotti13bec9b2012-09-17 05:29:47 +03001178 >>> def hexrepl(match):
Georg Brandl116aa622007-08-15 14:28:22 +00001179 ... "Return the hex string for a decimal number"
Ezio Melotti13bec9b2012-09-17 05:29:47 +03001180 ... value = int(match.group())
Georg Brandl116aa622007-08-15 14:28:22 +00001181 ... return hex(value)
1182 ...
1183 >>> p = re.compile(r'\d+')
1184 >>> p.sub(hexrepl, 'Call 65490 for printing, 49152 for user code.')
1185 'Call 0xffd2 for printing, 0xc000 for user code.'
1186
1187When using the module-level :func:`re.sub` function, the pattern is passed as
Benjamin Peterson8cc7d882009-06-01 23:14:51 +00001188the first argument. The pattern may be provided as an object or as a string; if
Georg Brandl116aa622007-08-15 14:28:22 +00001189you need to specify regular expression flags, you must either use a
Benjamin Peterson8cc7d882009-06-01 23:14:51 +00001190pattern object as the first parameter, or use embedded modifiers in the
1191pattern string, e.g. ``sub("(?i)b+", "x", "bbbb BBBB")`` returns ``'x x'``.
Georg Brandl116aa622007-08-15 14:28:22 +00001192
1193
1194Common Problems
1195===============
1196
1197Regular expressions are a powerful tool for some applications, but in some ways
1198their behaviour isn't intuitive and at times they don't behave the way you may
1199expect them to. This section will point out some of the most common pitfalls.
1200
1201
1202Use String Methods
1203------------------
1204
1205Sometimes using the :mod:`re` module is a mistake. If you're matching a fixed
1206string, or a single character class, and you're not using any :mod:`re` features
1207such as the :const:`IGNORECASE` flag, then the full power of regular expressions
1208may not be required. Strings have several methods for performing operations with
1209fixed strings and they're usually much faster, because the implementation is a
1210single small C loop that's been optimized for the purpose, instead of the large,
1211more generalized regular expression engine.
1212
1213One example might be replacing a single fixed string with another one; for
1214example, you might replace ``word`` with ``deed``. ``re.sub()`` seems like the
1215function to use for this, but consider the :meth:`replace` method. Note that
1216:func:`replace` will also replace ``word`` inside words, turning ``swordfish``
1217into ``sdeedfish``, but the naive RE ``word`` would have done that, too. (To
1218avoid performing the substitution on parts of words, the pattern would have to
1219be ``\bword\b``, in order to require that ``word`` have a word boundary on
1220either side. This takes the job beyond :meth:`replace`'s abilities.)
1221
1222Another common task is deleting every occurrence of a single character from a
1223string or replacing it with another single character. You might do this with
1224something like ``re.sub('\n', ' ', S)``, but :meth:`translate` is capable of
1225doing both tasks and will be faster than any regular expression operation can
1226be.
1227
1228In short, before turning to the :mod:`re` module, consider whether your problem
1229can be solved with a faster and simpler string method.
1230
1231
1232match() versus search()
1233-----------------------
1234
1235The :func:`match` function only checks if the RE matches at the beginning of the
1236string while :func:`search` will scan forward through the string for a match.
1237It's important to keep this distinction in mind. Remember, :func:`match` will
1238only report a successful match which will start at 0; if the match wouldn't
1239start at zero, :func:`match` will *not* report it. ::
1240
Georg Brandl6911e3c2007-09-04 07:15:32 +00001241 >>> print(re.match('super', 'superstition').span())
Georg Brandl116aa622007-08-15 14:28:22 +00001242 (0, 5)
Georg Brandl6911e3c2007-09-04 07:15:32 +00001243 >>> print(re.match('super', 'insuperable'))
Georg Brandl116aa622007-08-15 14:28:22 +00001244 None
1245
1246On the other hand, :func:`search` will scan forward through the string,
1247reporting the first match it finds. ::
1248
Georg Brandl6911e3c2007-09-04 07:15:32 +00001249 >>> print(re.search('super', 'superstition').span())
Georg Brandl116aa622007-08-15 14:28:22 +00001250 (0, 5)
Georg Brandl6911e3c2007-09-04 07:15:32 +00001251 >>> print(re.search('super', 'insuperable').span())
Georg Brandl116aa622007-08-15 14:28:22 +00001252 (2, 7)
1253
1254Sometimes you'll be tempted to keep using :func:`re.match`, and just add ``.*``
1255to the front of your RE. Resist this temptation and use :func:`re.search`
1256instead. The regular expression compiler does some analysis of REs in order to
1257speed up the process of looking for a match. One such analysis figures out what
1258the first character of a match must be; for example, a pattern starting with
1259``Crow`` must match starting with a ``'C'``. The analysis lets the engine
1260quickly scan through the string looking for the starting character, only trying
1261the full match if a ``'C'`` is found.
1262
1263Adding ``.*`` defeats this optimization, requiring scanning to the end of the
1264string and then backtracking to find a match for the rest of the RE. Use
1265:func:`re.search` instead.
1266
1267
1268Greedy versus Non-Greedy
1269------------------------
1270
1271When repeating a regular expression, as in ``a*``, the resulting action is to
1272consume as much of the pattern as possible. This fact often bites you when
1273you're trying to match a pair of balanced delimiters, such as the angle brackets
1274surrounding an HTML tag. The naive pattern for matching a single HTML tag
1275doesn't work because of the greedy nature of ``.*``. ::
1276
1277 >>> s = '<html><head><title>Title</title>'
1278 >>> len(s)
1279 32
Georg Brandl6911e3c2007-09-04 07:15:32 +00001280 >>> print(re.match('<.*>', s).span())
Georg Brandl116aa622007-08-15 14:28:22 +00001281 (0, 32)
Georg Brandl6911e3c2007-09-04 07:15:32 +00001282 >>> print(re.match('<.*>', s).group())
Georg Brandl116aa622007-08-15 14:28:22 +00001283 <html><head><title>Title</title>
1284
1285The RE matches the ``'<'`` in ``<html>``, and the ``.*`` consumes the rest of
1286the string. There's still more left in the RE, though, and the ``>`` can't
1287match at the end of the string, so the regular expression engine has to
1288backtrack character by character until it finds a match for the ``>``. The
1289final match extends from the ``'<'`` in ``<html>`` to the ``'>'`` in
1290``</title>``, which isn't what you want.
1291
1292In this case, the solution is to use the non-greedy qualifiers ``*?``, ``+?``,
1293``??``, or ``{m,n}?``, which match as *little* text as possible. In the above
1294example, the ``'>'`` is tried immediately after the first ``'<'`` matches, and
1295when it fails, the engine advances a character at a time, retrying the ``'>'``
1296at every step. This produces just the right result::
1297
Georg Brandl6911e3c2007-09-04 07:15:32 +00001298 >>> print(re.match('<.*?>', s).group())
Georg Brandl116aa622007-08-15 14:28:22 +00001299 <html>
1300
1301(Note that parsing HTML or XML with regular expressions is painful.
1302Quick-and-dirty patterns will handle common cases, but HTML and XML have special
1303cases that will break the obvious regular expression; by the time you've written
1304a regular expression that handles all of the possible cases, the patterns will
1305be *very* complicated. Use an HTML or XML parser module for such tasks.)
1306
1307
Terry Reedy8663e342011-01-10 21:49:11 +00001308Using re.VERBOSE
1309----------------
Georg Brandl116aa622007-08-15 14:28:22 +00001310
1311By now you've probably noticed that regular expressions are a very compact
1312notation, but they're not terribly readable. REs of moderate complexity can
1313become lengthy collections of backslashes, parentheses, and metacharacters,
1314making them difficult to read and understand.
1315
1316For such REs, specifying the ``re.VERBOSE`` flag when compiling the regular
1317expression can be helpful, because it allows you to format the regular
1318expression more clearly.
1319
1320The ``re.VERBOSE`` flag has several effects. Whitespace in the regular
1321expression that *isn't* inside a character class is ignored. This means that an
1322expression such as ``dog | cat`` is equivalent to the less readable ``dog|cat``,
1323but ``[a b]`` will still match the characters ``'a'``, ``'b'``, or a space. In
1324addition, you can also put comments inside a RE; comments extend from a ``#``
1325character to the next newline. When used with triple-quoted strings, this
1326enables REs to be formatted more neatly::
1327
1328 pat = re.compile(r"""
1329 \s* # Skip leading whitespace
1330 (?P<header>[^:]+) # Header name
1331 \s* : # Whitespace, and a colon
1332 (?P<value>.*?) # The header's value -- *? used to
1333 # lose the following trailing whitespace
1334 \s*$ # Trailing whitespace to end-of-line
1335 """, re.VERBOSE)
1336
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001337This is far more readable than::
Georg Brandl116aa622007-08-15 14:28:22 +00001338
1339 pat = re.compile(r"\s*(?P<header>[^:]+)\s*:(?P<value>.*?)\s*$")
1340
Georg Brandl116aa622007-08-15 14:28:22 +00001341
1342Feedback
1343========
1344
1345Regular expressions are a complicated topic. Did this document help you
1346understand them? Were there parts that were unclear, or Problems you
1347encountered that weren't covered here? If so, please send suggestions for
1348improvements to the author.
1349
1350The most complete book on regular expressions is almost certainly Jeffrey
1351Friedl's Mastering Regular Expressions, published by O'Reilly. Unfortunately,
1352it exclusively concentrates on Perl and Java's flavours of regular expressions,
1353and doesn't contain any Python material at all, so it won't be useful as a
1354reference for programming in Python. (The first edition covered Python's
1355now-removed :mod:`regex` module, which won't help you much.) Consider checking
1356it out from your library.