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