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