Debian Codegraph @

cpython27/Doc/howto/regex.rst

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