rest25/library/re.rst => rest262/library/re.rst
f1
2:mod:`re` --- Regular expression operations
3===========================================
4
5.. module:: re
n6+   :synopsis: Regular expression operations.
6.. moduleauthor:: Fredrik Lundh <fredrik@pythonware.com>
7.. sectionauthor:: Andrew M. Kuchling <amk@amk.ca>
8
9
n10- 
11- 
12-This module provides regular expression matching operations similar to those
11+This module provides regular expression matching operations similar to
13-found in Perl.  Regular expression pattern strings may not contain null bytes,
12+those found in Perl. Both patterns and strings to be searched can be
14-but can specify the null byte using the ``\number`` notation.  Both patterns and
13+Unicode strings as well as 8-bit strings.
15-strings to be searched can be Unicode strings as well as 8-bit strings.  The
16-:mod:`re` module is always available.
17
n18-Regular expressions use the backslash character (``'\'``) to indicate special
n15+Regular expressions use the backslash character (``'\'``) to indicate
19-forms or to allow special characters to be used without invoking their special
16+special forms or to allow special characters to be used without invoking
20-meaning.  This collides with Python's usage of the same character for the same
17+their special meaning.  This collides with Python's usage of the same
21-purpose in string literals; for example, to match a literal backslash, one might
18+character for the same purpose in string literals; for example, to match
22-have to write ``'\\\\'`` as the pattern string, because the regular expression
19+a literal backslash, one might have to write ``'\\\\'`` as the pattern
23-must be ``\\``, and each backslash must be expressed as ``\\`` inside a regular
20+string, because the regular expression must be ``\\``, and each
24-Python string literal.
21+backslash must be expressed as ``\\`` inside a regular Python string
22+literal.
25
26The solution is to use Python's raw string notation for regular expression
27patterns; backslashes are not handled in any special way in a string literal
28prefixed with ``'r'``.  So ``r"\n"`` is a two-character string containing
29``'\'`` and ``'n'``, while ``"\n"`` is a one-character string containing a
n30-newline. Usually patterns will be expressed in Python code using this raw string
n28+newline.  Usually patterns will be expressed in Python code using this raw
31-notation.
29+string notation.
32
n31+It is important to note that most regular expression operations are available as
32+module-level functions and :class:`RegexObject` methods.  The functions are
33+shortcuts that don't require you to compile a regex object first, but miss some
34+fine-tuning parameters.
33
34.. seealso::
35
36   Mastering Regular Expressions
37      Book on regular expressions by Jeffrey Friedl, published by O'Reilly.  The
n38-      second  edition of the book no longer covers Python at all,  but the first
n40+      second edition of the book no longer covers Python at all, but the first
39      edition covered writing good regular expression patterns in great detail.
40
41
42.. _re-syntax:
43
44Regular Expression Syntax
45-------------------------
46
55string *pq* will match AB.  This holds unless *A* or *B* contain low precedence
56operations; boundary conditions between *A* and *B*; or have numbered group
57references.  Thus, complex expressions can easily be constructed from simpler
58primitive expressions like the ones described here.  For details of the theory
59and implementation of regular expressions, consult the Friedl book referenced
60above, or almost any textbook about compiler construction.
61
62A brief explanation of the format of regular expressions follows.  For further
n63-information and a gentler presentation, consult the Regular Expression HOWTO,
n65+information and a gentler presentation, consult the :ref:`regex-howto`.
64-accessible from `<http://www.python.org/doc/howto/>`_.
65
66Regular expressions can contain both special and ordinary characters. Most
67ordinary characters, like ``'A'``, ``'a'``, or ``'0'``, are the simplest regular
68expressions; they simply match themselves.  You can concatenate ordinary
69characters, so ``last`` matches the string ``'last'``.  (In the rest of this
70section, we'll write RE's in ``this special style``, usually without quotes, and
71strings to be matched ``'in single quotes'``.)
72
n73-Some characters, like ``'|'`` or ``'('``, are special. Special characters either
n74+Some characters, like ``'|'`` or ``'('``, are special. Special
74-stand for classes of ordinary characters, or affect how the regular expressions
75+characters either stand for classes of ordinary characters, or affect
75-around them are interpreted.
76+how the regular expressions around them are interpreted. Regular
77+expression pattern strings may not contain null bytes, but can specify
78+the null byte using the ``\number`` notation, e.g., ``'\x00'``.
79+ 
76
77The special characters are:
n78- 
79-.. % 
80
81``'.'``
82   (Dot.)  In the default mode, this matches any character except a newline.  If
83   the :const:`DOTALL` flag has been specified, this matches any character
84   including a newline.
85
86``'^'``
87   (Caret.)  Matches the start of the string, and in :const:`MULTILINE` mode also
88   matches immediately after each newline.
89
90``'$'``
91   Matches the end of the string or just before the newline at the end of the
92   string, and in :const:`MULTILINE` mode also matches before a newline.  ``foo``
93   matches both 'foo' and 'foobar', while the regular expression ``foo$`` matches
n94-   only 'foo'.  More interestingly, searching for ``foo.$`` in 'foo1\\nfoo2\\n'
n96+   only 'foo'.  More interestingly, searching for ``foo.$`` in ``'foo1\nfoo2\n'``
95-   matches 'foo2' normally, but 'foo1' in :const:`MULTILINE` mode.
97+   matches 'foo2' normally, but 'foo1' in :const:`MULTILINE` mode; searching for
98+   a single ``$`` in ``'foo\n'`` will find two (empty) matches: one just before
99+   the newline, and one at the end of the string.
96
97``'*'``
98   Causes the resulting RE to match 0 or more repetitions of the preceding RE, as
99   many repetitions as are possible.  ``ab*`` will match 'a', 'ab', or 'a' followed
100   by any number of 'b's.
101
102``'+'``
103   Causes the resulting RE to match 1 or more repetitions of the preceding RE.
128   ``a{3,5}`` will match from 3 to 5 ``'a'`` characters.  Omitting *m* specifies a
129   lower bound of zero,  and omitting *n* specifies an infinite upper bound.  As an
130   example, ``a{4,}b`` will match ``aaaab`` or a thousand ``'a'`` characters
131   followed by a ``b``, but not ``aaab``. The comma may not be omitted or the
132   modifier would be confused with the previously described form.
133
134``{m,n}?``
135   Causes the resulting RE to match from *m* to *n* repetitions of the preceding
n136-   RE, attempting to match as *few* repetitions as possible.  This is the non-
n140+   RE, attempting to match as *few* repetitions as possible.  This is the
137-   greedy version of the previous qualifier.  For example, on the 6-character
141+   non-greedy version of the previous qualifier.  For example, on the
138-   string ``'aaaaaa'``, ``a{3,5}`` will match 5 ``'a'`` characters, while
142+   6-character string ``'aaaaaa'``, ``a{3,5}`` will match 5 ``'a'`` characters,
139-   ``a{3,5}?`` will only match 3 characters.
143+   while ``a{3,5}?`` will only match 3 characters.
140
141``'\'``
142   Either escapes special characters (permitting you to match characters like
143   ``'*'``, ``'?'``, and so forth), or signals a special sequence; special
144   sequences are discussed below.
145
146   If you're not using a raw string to express the pattern, remember that Python
147   also uses the backslash as an escape sequence in string literals; if the escape
150   recognize the resulting sequence, the backslash should be repeated twice.  This
151   is complicated and hard to understand, so it's highly recommended that you use
152   raw strings for all but the simplest expressions.
153
154``[]``
155   Used to indicate a set of characters.  Characters can be listed individually, or
156   a range of characters can be indicated by giving two characters and separating
157   them by a ``'-'``.  Special characters are not active inside sets.  For example,
n158-   ``[akm$]`` will match any of the characters ``'a'``, ``'k'``, ``'m'``, or
n162+   ``[akm$]`` will match any of the characters ``'a'``, ``'k'``,
159-   ``'$'``; ``[a-z]`` will match any lowercase letter, and ``[a-zA-Z0-9]`` matches
163+   ``'m'``, or ``'$'``; ``[a-z]`` will match any lowercase letter, and
160-   any letter or digit.  Character classes such as ``\w`` or ``\S`` (defined below)
164+   ``[a-zA-Z0-9]`` matches any letter or digit.  Character classes such
161-   are also acceptable inside a range.  If you want to include a ``']'`` or a
165+   as ``\w`` or ``\S`` (defined below) are also acceptable inside a
166+   range, although the characters they match depends on whether :const:`LOCALE`
167+   or  :const:`UNICODE` mode is in force.  If you want to include a
162-   ``'-'`` inside a set, precede it with a backslash, or place it as the first
168+   ``']'`` or a ``'-'`` inside a set, precede it with a backslash, or
163-   character.  The pattern ``[]]`` will match ``']'``, for example.
169+   place it as the first character.  The pattern ``[]]`` will match
170+   ``']'``, for example.
164
165   You can match the characters not within a range by :dfn:`complementing` the set.
166   This is indicated by including a ``'^'`` as the first character of the set;
167   ``'^'`` elsewhere will simply match the ``'^'`` character.  For example,
168   ``[^5]`` will match any character except ``'5'``, and ``[^^]`` will match any
169   character except ``'^'``.
n177+ 
178+   Note that inside ``[]`` the special forms and special characters lose
179+   their meanings and only the syntaxes described here are valid. For
180+   example, ``+``, ``*``, ``(``, ``)``, and so on are treated as
181+   literals inside ``[]``, and backreferences cannot be used inside
182+   ``[]``.
170
171``'|'``
172   ``A|B``, where A and B can be arbitrary REs, creates a regular expression that
173   will match either A or B.  An arbitrary number of REs can be separated by the
174   ``'|'`` in this way.  This can be used inside groups (see below) as well.  As
175   the target string is scanned, REs separated by ``'|'`` are tried from left to
176   right. When one pattern completely matches, that branch is accepted. This means
177   that once ``A`` matches, ``B`` will not be tested further, even if it would
189``(?...)``
190   This is an extension notation (a ``'?'`` following a ``'('`` is not meaningful
191   otherwise).  The first character after the ``'?'`` determines what the meaning
192   and further syntax of the construct is. Extensions usually do not create a new
193   group; ``(?P<name>...)`` is the only exception to this rule. Following are the
194   currently supported extensions.
195
196``(?iLmsux)``
n197-   (One or more letters from the set ``'i'``, ``'L'``, ``'m'``, ``'s'``, ``'u'``,
n210+   (One or more letters from the set ``'i'``, ``'L'``, ``'m'``, ``'s'``,
198-   ``'x'``.)  The group matches the empty string; the letters set the corresponding
211+   ``'u'``, ``'x'``.)  The group matches the empty string; the letters
199-   flags (:const:`re.I`, :const:`re.L`, :const:`re.M`, :const:`re.S`,
212+   set the corresponding flags: :const:`re.I` (ignore case),
213+   :const:`re.L` (locale dependent), :const:`re.M` (multi-line),
214+   :const:`re.S` (dot matches all), :const:`re.U` (Unicode dependent),
200-   :const:`re.U`, :const:`re.X`) for the entire regular expression.  This is useful
215+   and :const:`re.X` (verbose), for the entire regular expression. (The
216+   flags are described in :ref:`contents-of-module-re`.) This
201-   if you wish to include the flags as part of the regular expression, instead of
217+   is useful if you wish to include the flags as part of the regular
202-   passing a *flag* argument to the :func:`compile` function.
218+   expression, instead of passing a *flag* argument to the
219+   :func:`compile` function.
203
204   Note that the ``(?x)`` flag changes how the expression is parsed. It should be
205   used first in the expression string, or after one or more whitespace characters.
206   If there are non-whitespace characters before the flag, the results are
207   undefined.
208
209``(?:...)``
210   A non-grouping version of regular parentheses. Matches whatever regular
211   expression is inside the parentheses, but the substring matched by the group
212   *cannot* be retrieved after performing a match or referenced later in the
213   pattern.
214
215``(?P<name>...)``
216   Similar to regular parentheses, but the substring matched by the group is
n217-   accessible via the symbolic group name *name*.  Group names must be valid Python
n234+   accessible within the rest of the regular expression via the symbolic group
218-   identifiers, and each group name must be defined only once within a regular
235+   name *name*.  Group names must be valid Python identifiers, and each group
219-   expression.  A symbolic group is also a numbered group, just as if the group
236+   name must be defined only once within a regular expression.  A symbolic group
220-   were not named.  So the group named 'id' in the example above can also be
237+   is also a numbered group, just as if the group were not named.  So the group
221-   referenced as the numbered group 1.
238+   named ``id`` in the example below can also be referenced as the numbered group
239+   ``1``.
222
223   For example, if the pattern is ``(?P<id>[a-zA-Z_]\w*)``, the group can be
224   referenced by its name in arguments to methods of match objects, such as
n225-   ``m.group('id')`` or ``m.end('id')``, and also by name in pattern text (for
n243+   ``m.group('id')`` or ``m.end('id')``, and also by name in the regular
226-   example, ``(?P=id)``) and replacement text (such as ``\g<id>``).
244+   expression itself (using ``(?P=id)``) and replacement text given to
245+   ``.sub()`` (using ``\g<id>``).
227
228``(?P=name)``
229   Matches whatever text was matched by the earlier group named *name*.
230
231``(?#...)``
232   A comment; the contents of the parentheses are simply ignored.
233
234``(?=...)``
245   Matches if the current position in the string is preceded by a match for ``...``
246   that ends at the current position.  This is called a :dfn:`positive lookbehind
247   assertion`. ``(?<=abc)def`` will find a match in ``abcdef``, since the
248   lookbehind will back up 3 characters and check if the contained pattern matches.
249   The contained pattern must only match strings of some fixed length, meaning that
250   ``abc`` or ``a|b`` are allowed, but ``a*`` and ``a{3,4}`` are not.  Note that
251   patterns which start with positive lookbehind assertions will never match at the
252   beginning of the string being searched; you will most likely want to use the
n253-   :func:`search` function rather than the :func:`match` function::
n272+   :func:`search` function rather than the :func:`match` function:
254
255      >>> import re
256      >>> m = re.search('(?<=abc)def', 'abcdef')
257      >>> m.group(0)
258      'def'
259
n260-   This example looks for a word following a hyphen::
n279+   This example looks for a word following a hyphen:
261
262      >>> m = re.search('(?<=-)\w+', 'spam-egg')
263      >>> m.group(0)
264      'egg'
265
266``(?<!...)``
267   Matches if the current position in the string is not preceded by a match for
268   ``...``.  This is called a :dfn:`negative lookbehind assertion`.  Similar to
269   positive lookbehind assertions, the contained pattern must only match strings of
270   some fixed length.  Patterns which start with negative lookbehind assertions may
271   match at the beginning of the string being searched.
272
273``(?(id/name)yes-pattern|no-pattern)``
274   Will try to match with ``yes-pattern`` if the group with given *id* or *name*
n275-   exists, and with ``no-pattern`` if it doesn't. ``|no-pattern`` is optional and
n294+   exists, and with ``no-pattern`` if it doesn't. ``no-pattern`` is optional and
276   can be omitted. For example,  ``(<)?(\w+@\w+(?:\.\w+)+)(?(1)>)`` is a poor email
277   matching pattern, which will match with ``'<user@host.com>'`` as well as
278   ``'user@host.com'``, but not with ``'<user@host.com'``.
279
280   .. versionadded:: 2.4
281
282The special sequences consist of ``'\'`` and a character from the list below.
283If the ordinary character is not on the list, then the resulting RE will match
284the second character.  For example, ``\$`` matches the character ``'$'``.
n285- 
286-.. % 
287
288``\number``
289   Matches the contents of the group of the same number.  Groups are numbered
290   starting from 1.  For example, ``(.+) \1`` matches ``'the the'`` or ``'55 55'``,
291   but not ``'the end'`` (note the space after the group).  This special sequence
292   can only be used to match one of the first 99 groups.  If the first digit of
293   *number* is 0, or *number* is 3 octal digits long, it will not be interpreted as
294   a group match, but as the character with octal value *number*. Inside the
304   word is indicated by whitespace or a non-alphanumeric, non-underscore character.
305   Note that  ``\b`` is defined as the boundary between ``\w`` and ``\ W``, so the
306   precise set of characters deemed to be alphanumeric depends on the values of the
307   ``UNICODE`` and ``LOCALE`` flags.  Inside a character range, ``\b`` represents
308   the backspace character, for compatibility with Python's string literals.
309
310``\B``
311   Matches the empty string, but only when it is *not* at the beginning or end of a
n312-   word.  This is just the opposite of ``\ b``, so is also subject to the settings
n329+   word.  This is just the opposite of ``\b``, so is also subject to the settings
313   of ``LOCALE`` and ``UNICODE``.
314
315``\d``
316   When the :const:`UNICODE` flag is not specified, matches any decimal digit; this
317   is equivalent to the set ``[0-9]``.  With :const:`UNICODE`, it will match
318   whatever is classified as a digit in the Unicode character properties database.
319
320``\D``
365   \r      \t      \v      \x
366   \\
367
368Octal escapes are included in a limited form: If the first digit is a 0, or if
369there are three octal digits, it is considered an octal escape. Otherwise, it is
370a group reference.  As for string literals, octal escapes are always at most
371three digits in length.
372
n373-.. % Note the lack of a period in the section title; it causes problems
374-.. % with readers of the GNU info version.  See http://www.python.org/sf/581414.
375- 
376
377.. _matching-searching:
378
379Matching vs Searching
380---------------------
381
382.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
383
384
385Python offers two different primitive operations based on regular expressions:
n386-match and search.  If you are accustomed to Perl's semantics, the search
n400+**match** checks for a match only at the beginning of the string, while
387-operation is what you're looking for.  See the :func:`search` function and
401+**search** checks for a match anywhere in the string (this is what Perl does
388-corresponding method of compiled regular expression objects.
402+by default).
389
n390-Note that match may differ from search using a regular expression beginning with
n404+Note that match may differ from search even when using a regular expression
391-``'^'``: ``'^'`` matches only at the start of the string, or in
405+beginning with ``'^'``: ``'^'`` matches only at the start of the string, or in
392:const:`MULTILINE` mode also immediately following a newline.  The "match"
393operation succeeds only if the pattern matches at the start of the string
394regardless of mode, or at the starting position given by the optional *pos*
395argument regardless of whether a newline precedes it.
396
n397-.. % Examples from Tim Peters:
n411+   >>> re.match("c", "abcdef")  # No match
412+   >>> re.search("c", "abcdef") # Match
413+   <_sre.SRE_Match object at ...>
398
n399-::
400
n401-   re.compile("a").match("ba", 1)           # succeeds
n416+.. _contents-of-module-re:
402-   re.compile("^a").search("ba", 1)         # fails; 'a' not at start
403-   re.compile("^a").search("\na", 1)        # fails; 'a' not at start
404-   re.compile("^a", re.M).search("\na", 1)  # succeeds
405-   re.compile("^a", re.M).search("ba", 1)   # fails; no preceding \n
406- 
407
408Module Contents
409---------------
n410- 
411-.. _contents of module re:
412
413The module defines several functions, constants, and an exception. Some of the
414functions are simplified versions of the full featured methods for compiled
415regular expressions.  Most non-trivial applications always use the compiled
416form.
417
418
419.. function:: compile(pattern[, flags])
420
n421-   Compile a regular expression pattern into a regular expression object, which can
n429+   Compile a regular expression pattern into a regular expression object, which
422-   be used for matching using its :func:`match` and :func:`search` methods,
430+   can be used for matching using its :func:`match` and :func:`search` methods,
423   described below.
424
425   The expression's behaviour can be modified by specifying a *flags* value.
426   Values can be any of the following variables, combined using bitwise OR (the
427   ``|`` operator).
428
429   The sequence ::
430
n431-      prog = re.compile(pat)
n439+      prog = re.compile(pattern)
432-      result = prog.match(str)
440+      result = prog.match(string)
433
434   is equivalent to ::
435
n436-      result = re.match(pat, str)
n444+      result = re.match(pattern, string)
437
n438-   but the version using :func:`compile` is more efficient when the expression will
n446+   but using :func:`compile` and saving the resulting regular expression object
439-   be used several times in a single program.
447+   for reuse is more efficient when the expression will be used several times
448+   in a single program.
440
n450+   .. note::
451+ 
441-   .. % (The compiled version of the last pattern passed to
452+      The compiled versions of the most recent patterns passed to
442-   .. % \function{re.match()} or \function{re.search()} is cached, so
453+      :func:`re.match`, :func:`re.search` or :func:`re.compile` are cached, so
443-   .. % programs that use only a single regular expression at a time needn't
454+      programs that use only a few regular expressions at a time needn't worry
444-   .. % worry about compiling regular expressions.)
455+      about compiling regular expressions.
445
446
447.. data:: I
448          IGNORECASE
449
450   Perform case-insensitive matching; expressions like ``[A-Z]`` will match
451   lowercase letters, too.  This is not affected by the current locale.
452
453
454.. data:: L
455          LOCALE
456
n457-   Make ``\w``, ``\W``, ``\b``, ``\B``, ``\s`` and ``\S`` dependent on the current
n468+   Make ``\w``, ``\W``, ``\b``, ``\B``, ``\s`` and ``\S`` dependent on the
458-   locale.
469+   current locale.
459
460
461.. data:: M
462          MULTILINE
463
464   When specified, the pattern character ``'^'`` matches at the beginning of the
465   string and at the beginning of each line (immediately following each newline);
466   and the pattern character ``'$'`` matches at the end of the string and at the
489          VERBOSE
490
491   This flag allows you to write regular expressions that look nicer. Whitespace
492   within the pattern is ignored, except when in a character class or preceded by
493   an unescaped backslash, and, when a line contains a ``'#'`` neither in a
494   character class or preceded by an unescaped backslash, all characters from the
495   leftmost such ``'#'`` through the end of the line are ignored.
496
n497-   .. % XXX should add an example here
n508+   That means that the two following regular expression objects that match a
509+   decimal number are functionally equal::
510+ 
511+      a = re.compile(r"""\d +  # the integral part
512+                         \.    # the decimal point
513+                         \d *  # some fractional digits""", re.X)
514+      b = re.compile(r"\d+\.\d*")
498
499
500.. function:: search(pattern, string[, flags])
501
502   Scan through *string* looking for a location where the regular expression
503   *pattern* produces a match, and return a corresponding :class:`MatchObject`
504   instance. Return ``None`` if no position in the string matches the pattern; note
505   that this is different from finding a zero-length match at some point in the
510
511   If zero or more characters at the beginning of *string* match the regular
512   expression *pattern*, return a corresponding :class:`MatchObject` instance.
513   Return ``None`` if the string does not match the pattern; note that this is
514   different from a zero-length match.
515
516   .. note::
517
n518-      If you want to locate a match anywhere in *string*, use :meth:`search` instead.
n535+      If you want to locate a match anywhere in *string*, use :meth:`search`
536+      instead.
519
520
n521-.. function:: split(pattern, string[, maxsplit\ ``= 0``])
n539+.. function:: split(pattern, string[, maxsplit=0])
522
523   Split *string* by the occurrences of *pattern*.  If capturing parentheses are
524   used in *pattern*, then the text of all groups in the pattern are also returned
525   as part of the resulting list. If *maxsplit* is nonzero, at most *maxsplit*
526   splits occur, and the remainder of the string is returned as the final element
527   of the list.  (Incompatibility note: in the original Python 1.5 release,
n528-   *maxsplit* was ignored.  This has been fixed in later releases.) ::
n546+   *maxsplit* was ignored.  This has been fixed in later releases.)
529
530      >>> re.split('\W+', 'Words, words, words.')
531      ['Words', 'words', 'words', '']
532      >>> re.split('(\W+)', 'Words, words, words.')
533      ['Words', ', ', 'words', ', ', 'words', '.', '']
534      >>> re.split('\W+', 'Words, words, words.', 1)
535      ['Words', 'words, words.']
536
n555+   If there are capturing groups in the separator and it matches at the start of
556+   the string, the result will start with an empty string.  The same holds for
557+   the end of the string:
558+ 
559+      >>> re.split('(\W+)', '...words, words...')
560+      ['', '...', 'words', ', ', 'words', '...', '']
561+ 
562+   That way, separator components are always found at the same relative
563+   indices within the result list (e.g., if there's one capturing group
564+   in the separator, the 0th, the 2nd and so forth).
565+ 
566+   Note that *split* will never split a string on an empty pattern match.
567+   For example:
568+ 
569+      >>> re.split('x*', 'foo')
570+      ['foo']
571+      >>> re.split("(?m)^$", "foo\n\nbar\n")
572+      ['foo\n\nbar\n']
573+ 
537
538.. function:: findall(pattern, string[, flags])
539
n540-   Return a list of all non-overlapping matches of *pattern* in *string*.  If one
n577+   Return all non-overlapping matches of *pattern* in *string*, as a list of
541-   or more groups are present in the pattern, return a list of groups; this will be
578+   strings.  The *string* is scanned left-to-right, and matches are returned in
542-   a list of tuples if the pattern has more than one group.  Empty matches are
579+   the order found.  If one or more groups are present in the pattern, return a
543-   included in the result unless they touch the beginning of another match.
580+   list of groups; this will be a list of tuples if the pattern has more than
581+   one group.  Empty matches are included in the result unless they touch the
582+   beginning of another match.
544
545   .. versionadded:: 1.5.2
546
547   .. versionchanged:: 2.4
548      Added the optional flags argument.
549
550
551.. function:: finditer(pattern, string[, flags])
552
n553-   Return an iterator over all non-overlapping matches for the RE *pattern* in
n592+   Return an :term:`iterator` yielding :class:`MatchObject` instances over all
554-   *string*.  For each match, the iterator returns a match object.  Empty matches
593+   non-overlapping matches for the RE *pattern* in *string*.  The *string* is
594+   scanned left-to-right, and matches are returned in the order found.  Empty
555-   are included in the result unless they touch the beginning of another match.
595+   matches are included in the result unless they touch the beginning of another
596+   match.
556
557   .. versionadded:: 2.2
558
559   .. versionchanged:: 2.4
560      Added the optional flags argument.
561
562
563.. function:: sub(pattern, repl, string[, count])
564
565   Return the string obtained by replacing the leftmost non-overlapping occurrences
566   of *pattern* in *string* by the replacement *repl*.  If the pattern isn't found,
567   *string* is returned unchanged.  *repl* can be a string or a function; if it is
568   a string, any backslash escapes in it are processed.  That is, ``\n`` is
569   converted to a single newline character, ``\r`` is converted to a linefeed, and
570   so forth.  Unknown escapes such as ``\j`` are left alone.  Backreferences, such
571   as ``\6``, are replaced with the substring matched by group 6 in the pattern.
n572-   For example::
n613+   For example:
573
574      >>> re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',
575      ...        r'static PyObject*\npy_\1(void)\n{',
576      ...        'def myfunc():')
577      'static PyObject*\npy_myfunc(void)\n{'
578
579   If *repl* is a function, it is called for every non-overlapping occurrence of
580   *pattern*.  The function takes a single match object argument, and returns the
n581-   replacement string.  For example::
n622+   replacement string.  For example:
582
583      >>> def dashrepl(matchobj):
584      ...     if matchobj.group(0) == '-': return ' '
585      ...     else: return '-'
586      >>> re.sub('-{1,2}', dashrepl, 'pro----gram-files')
587      'pro--gram files'
588
589   The pattern may be a string or an RE object; if you need to specify regular
640
641   If zero or more characters at the beginning of *string* match this regular
642   expression, return a corresponding :class:`MatchObject` instance.  Return
643   ``None`` if the string does not match the pattern; note that this is different
644   from a zero-length match.
645
646   .. note::
647
n648-      If you want to locate a match anywhere in *string*, use :meth:`search` instead.
n689+      If you want to locate a match anywhere in *string*, use :meth:`search`
690+      instead.
649
650   The optional second parameter *pos* gives an index in the string where the
651   search is to start; it defaults to ``0``.  This is not completely equivalent to
652   slicing the string; the ``'^'`` pattern character matches at the real beginning
653   of the string and at positions just after a newline, but not necessarily at the
654   index where the search is to start.
655
656   The optional parameter *endpos* limits how far the string will be searched; it
657   will be as if the string is *endpos* characters long, so only the characters
658   from *pos* to ``endpos - 1`` will be searched for a match.  If *endpos* is less
659   than *pos*, no match will be found, otherwise, if *rx* is a compiled regular
660   expression object, ``rx.match(string, 0, 50)`` is equivalent to
661   ``rx.match(string[:50], 0)``.
662
n705+      >>> pattern = re.compile("o")
706+      >>> pattern.match("dog")      # No match as "o" is not at the start of "dog."
707+      >>> pattern.match("dog", 1)   # Match as "o" is the 2nd character of "dog".
708+      <_sre.SRE_Match object at ...>
709+ 
663
664.. method:: RegexObject.search(string[, pos[, endpos]])
665
666   Scan through *string* looking for a location where this regular expression
667   produces a match, and return a corresponding :class:`MatchObject` instance.
668   Return ``None`` if no position in the string matches the pattern; note that this
669   is different from finding a zero-length match at some point in the string.
670
671   The optional *pos* and *endpos* parameters have the same meaning as for the
672   :meth:`match` method.
673
674
n675-.. method:: RegexObject.split(string[, maxsplit\ ``= 0``])
n722+.. method:: RegexObject.split(string[, maxsplit=0])
676
677   Identical to the :func:`split` function, using the compiled pattern.
678
679
680.. method:: RegexObject.findall(string[, pos[, endpos]])
681
682   Identical to the :func:`findall` function, using the compiled pattern.
683
684
685.. method:: RegexObject.finditer(string[, pos[, endpos]])
686
687   Identical to the :func:`finditer` function, using the compiled pattern.
688
689
n690-.. method:: RegexObject.sub(repl, string[, count\ ``= 0``])
n737+.. method:: RegexObject.sub(repl, string[, count=0])
691
692   Identical to the :func:`sub` function, using the compiled pattern.
693
694
n695-.. method:: RegexObject.subn(repl, string[, count\ ``= 0``])
n742+.. method:: RegexObject.subn(repl, string[, count=0])
696
697   Identical to the :func:`subn` function, using the compiled pattern.
698
699
700.. attribute:: RegexObject.flags
701
702   The flags argument used when the RE object was compiled, or ``0`` if no flags
703   were provided.
n751+ 
752+ 
753+.. attribute:: RegexObject.groups
754+ 
755+   The number of capturing groups in the pattern.
704
705
706.. attribute:: RegexObject.groupindex
707
708   A dictionary mapping any symbolic group names defined by ``(?P<id>)`` to group
709   numbers.  The dictionary is empty if no symbolic groups were used in the
710   pattern.
711
715   The pattern string from which the RE object was compiled.
716
717
718.. _match-objects:
719
720Match Objects
721-------------
722
n723-:class:`MatchObject` instances support the following methods and attributes:
n775+Match objects always have a boolean value of :const:`True`, so that you can test
776+whether e.g. :func:`match` resulted in a match with a simple if statement.  They
777+support the following methods and attributes:
724
725
726.. method:: MatchObject.expand(template)
727
728   Return the string obtained by doing backslash substitution on the template
729   string *template*, as done by the :meth:`sub` method. Escapes such as ``\n`` are
730   converted to the appropriate characters, and numeric backreferences (``\1``,
731   ``\2``) and named backreferences (``\g<1>``, ``\g<name>``) are replaced by the
741   return value is the entire matching string; if it is in the inclusive range
742   [1..99], it is the string matching the corresponding parenthesized group.  If a
743   group number is negative or larger than the number of groups defined in the
744   pattern, an :exc:`IndexError` exception is raised. If a group is contained in a
745   part of the pattern that did not match, the corresponding result is ``None``.
746   If a group is contained in a part of the pattern that matched multiple times,
747   the last match is returned.
748
n803+      >>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
804+      >>> m.group(0)       # The entire match
805+      'Isaac Newton'
806+      >>> m.group(1)       # The first parenthesized subgroup.
807+      'Isaac'
808+      >>> m.group(2)       # The second parenthesized subgroup.
809+      'Newton'
810+      >>> m.group(1, 2)    # Multiple arguments give us a tuple.
811+      ('Isaac', 'Newton')
812+ 
749   If the regular expression uses the ``(?P<name>...)`` syntax, the *groupN*
750   arguments may also be strings identifying groups by their group name.  If a
751   string argument is not used as a group name in the pattern, an :exc:`IndexError`
752   exception is raised.
753
n754-   A moderately complicated example::
n818+   A moderately complicated example:
755
n756-      m = re.match(r"(?P<int>\d+)\.(\d*)", '3.14')
n820+      >>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcom Reynolds")
821+      >>> m.group('first_name')
822+      'Malcom'
823+      >>> m.group('last_name')
824+      'Reynolds'
757
n758-   After performing this match, ``m.group(1)`` is ``'3'``, as is
n826+   Named groups can also be referred to by their index:
759-   ``m.group('int')``, and ``m.group(2)`` is ``'14'``.
827+ 
828+      >>> m.group(1)
829+      'Malcom'
830+      >>> m.group(2)
831+      'Reynolds'
832+ 
833+   If a group matches multiple times, only the last match is accessible:
834+ 
835+      >>> m = re.match(r"(..)+", "a1b2c3")  # Matches 3 times.
836+      >>> m.group(1)                        # Returns only the last match.
837+      'c3'
760
761
762.. method:: MatchObject.groups([default])
763
764   Return a tuple containing all the subgroups of the match, from 1 up to however
765   many groups are in the pattern.  The *default* argument is used for groups that
766   did not participate in the match; it defaults to ``None``.  (Incompatibility
767   note: in the original Python 1.5 release, if the tuple was one element long, a
768   string would be returned instead.  In later versions (from 1.5.1 on), a
769   singleton tuple is returned in such cases.)
770
n849+   For example:
850+ 
851+      >>> m = re.match(r"(\d+)\.(\d+)", "24.1632")
852+      >>> m.groups()
853+      ('24', '1632')
854+ 
855+   If we make the decimal place and everything after it optional, not all groups
856+   might participate in the match.  These groups will default to ``None`` unless
857+   the *default* argument is given:
858+ 
859+      >>> m = re.match(r"(\d+)\.?(\d+)?", "24")
860+      >>> m.groups()      # Second group defaults to None.
861+      ('24', None)
862+      >>> m.groups('0')   # Now, the second group defaults to '0'.
863+      ('24', '0')
864+ 
771
772.. method:: MatchObject.groupdict([default])
773
774   Return a dictionary containing all the *named* subgroups of the match, keyed by
775   the subgroup name.  The *default* argument is used for groups that did not
n776-   participate in the match; it defaults to ``None``.
n870+   participate in the match; it defaults to ``None``.  For example:
871+ 
872+      >>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcom Reynolds")
873+      >>> m.groupdict()
874+      {'first_name': 'Malcom', 'last_name': 'Reynolds'}
777
778
779.. method:: MatchObject.start([group])
n780-            XXX Class.end([group])
n878+            MatchObject.end([group])
781
782   Return the indices of the start and end of the substring matched by *group*;
783   *group* defaults to zero (meaning the whole matched substring). Return ``-1`` if
784   *group* exists but did not contribute to the match.  For a match object *m*, and
785   a group *g* that did contribute to the match, the substring matched by group *g*
786   (equivalent to ``m.group(g)``) is ::
787
788      m.string[m.start(g):m.end(g)]
789
790   Note that ``m.start(group)`` will equal ``m.end(group)`` if *group* matched a
791   null string.  For example, after ``m = re.search('b(c?)', 'cba')``,
792   ``m.start(0)`` is 1, ``m.end(0)`` is 2, ``m.start(1)`` and ``m.end(1)`` are both
793   2, and ``m.start(2)`` raises an :exc:`IndexError` exception.
794
n893+   An example that will remove *remove_this* from email addresses:
894+ 
895+      >>> email = "tony@tiremove_thisger.net"
896+      >>> m = re.search("remove_this", email)
897+      >>> email[:m.start()] + email[m.end():]
898+      'tony@tiger.net'
899+ 
795
796.. method:: MatchObject.span([group])
797
798   For :class:`MatchObject` *m*, return the 2-tuple ``(m.start(group),
799   m.end(group))``. Note that if *group* did not contribute to the match, this is
n800-   ``(-1, -1)``.  Again, *group* defaults to zero.
n905+   ``(-1, -1)``.  *group* defaults to zero, the entire match.
801
802
803.. attribute:: MatchObject.pos
804
805   The value of *pos* which was passed to the :func:`search` or :func:`match`
806   method of the :class:`RegexObject`.  This is the index into the string at which
807   the RE engine started looking for a match.
808
838.. attribute:: MatchObject.string
839
840   The string passed to :func:`match` or :func:`search`.
841
842
843Examples
844--------
845
n951+ 
952+Checking For a Pair
953+^^^^^^^^^^^^^^^^^^^
954+ 
955+In this example, we'll use the following helper function to display match
956+objects a little more gracefully:
957+ 
958+.. testcode::
959+ 
960+   def displaymatch(match):
961+       if match is None:
962+           return None
963+       return '<Match: %r, groups=%r>' % (match.group(), match.groups())
964+ 
965+Suppose you are writing a poker program where a player's hand is represented as
966+a 5-character string with each character representing a card, "a" for ace, "k"
967+for king, "q" for queen, j for jack, "0" for 10, and "1" through "9"
968+representing the card with that value.
969+ 
970+To see if a given string is a valid hand, one could do the following:
971+ 
972+   >>> valid = re.compile(r"[0-9akqj]{5}$")
973+   >>> displaymatch(valid.match("ak05q"))  # Valid.
974+   "<Match: 'ak05q', groups=()>"
975+   >>> displaymatch(valid.match("ak05e"))  # Invalid.
976+   >>> displaymatch(valid.match("ak0"))    # Invalid.
977+   >>> displaymatch(valid.match("727ak"))  # Valid.
978+   "<Match: '727ak', groups=()>"
979+ 
980+That last hand, ``"727ak"``, contained a pair, or two of the same valued cards.
981+To match this with a regular expression, one could use backreferences as such:
982+ 
983+   >>> pair = re.compile(r".*(.).*\1")
984+   >>> displaymatch(pair.match("717ak"))     # Pair of 7s.
985+   "<Match: '717', groups=('7',)>"
986+   >>> displaymatch(pair.match("718ak"))     # No pairs.
987+   >>> displaymatch(pair.match("354aa"))     # Pair of aces.
988+   "<Match: '354aa', groups=('a',)>"
989+ 
990+To find out what card the pair consists of, one could use the :func:`group`
991+method of :class:`MatchObject` in the following manner:
992+ 
993+.. doctest::
994+ 
995+   >>> pair.match("717ak").group(1)
996+   '7'
997+ 
998+   # Error because re.match() returns None, which doesn't have a group() method:
999+   >>> pair.match("718ak").group(1)
1000+   Traceback (most recent call last):
1001+     File "<pyshell#23>", line 1, in <module>
1002+       re.match(r".*(.).*\1", "718ak").group(1)
1003+   AttributeError: 'NoneType' object has no attribute 'group'
1004+ 
1005+   >>> pair.match("354aa").group(1)
1006+   'a'
1007+ 
1008+ 
846-**Simulating scanf()**
1009+Simulating scanf()
1010+^^^^^^^^^^^^^^^^^^
847
848.. index:: single: scanf()
849
850Python does not currently have an equivalent to :cfunc:`scanf`.  Regular
851expressions are generally more powerful, though also more verbose, than
852:cfunc:`scanf` format strings.  The table below offers some more-or-less
853equivalent mappings between :cfunc:`scanf` format tokens and regular
854expressions.
882you would use a :cfunc:`scanf` format like ::
883
884   %s - %d errors, %d warnings
885
886The equivalent regular expression would be ::
887
888   (\S+) - (\d+) errors, (\d+) warnings
889
n1054+ 
890-**Avoiding recursion**
1055+Avoiding recursion
1056+^^^^^^^^^^^^^^^^^^
891
892If you create regular expressions that require the engine to perform a lot of
893recursion, you may encounter a :exc:`RuntimeError` exception with the message
894``maximum recursion limit`` exceeded. For example, ::
895
n896-   >>> import re
897   >>> s = 'Begin ' + 1000*'a very long string ' + 'end'
898   >>> re.match('Begin (\w| )*? end', s).end()
899   Traceback (most recent call last):
900     File "<stdin>", line 1, in ?
901     File "/usr/local/lib/python2.5/re.py", line 132, in match
902       return _compile(pattern, flags).match(string)
903   RuntimeError: maximum recursion limit exceeded
904
905You can often restructure your regular expression to avoid recursion.
906
907Starting with Python 2.3, simple uses of the ``*?`` pattern are special-cased to
908avoid recursion.  Thus, the above regular expression can avoid recursion by
909being recast as ``Begin [a-zA-Z0-9_ ]*?end``.  As a further benefit, such
910regular expressions will run faster than their recursive equivalents.
911
t1077+ 
1078+search() vs. match()
1079+^^^^^^^^^^^^^^^^^^^^
1080+ 
1081+In a nutshell, :func:`match` only attempts to match a pattern at the beginning
1082+of a string where :func:`search` will match a pattern anywhere in a string.
1083+For example:
1084+ 
1085+   >>> re.match("o", "dog")  # No match as "o" is not the first letter of "dog".
1086+   >>> re.search("o", "dog") # Match as search() looks everywhere in the string.
1087+   <_sre.SRE_Match object at ...>
1088+ 
1089+.. note::
1090+ 
1091+   The following applies only to regular expression objects like those created
1092+   with ``re.compile("pattern")``, not the primitives ``re.match(pattern,
1093+   string)`` or ``re.search(pattern, string)``.
1094+ 
1095+:func:`match` has an optional second parameter that gives an index in the string
1096+where the search is to start::
1097+ 
1098+   >>> pattern = re.compile("o")
1099+   >>> pattern.match("dog")      # No match as "o" is not at the start of "dog."
1100+ 
1101+   # Equivalent to the above expression as 0 is the default starting index:
1102+   >>> pattern.match("dog", 0)
1103+ 
1104+   # Match as "o" is the 2nd character of "dog" (index 0 is the first):
1105+   >>> pattern.match("dog", 1)
1106+   <_sre.SRE_Match object at ...>
1107+   >>> pattern.match("dog", 2)   # No match as "o" is not the 3rd character of "dog."
1108+ 
1109+ 
1110+Making a Phonebook
1111+^^^^^^^^^^^^^^^^^^
1112+ 
1113+:func:`split` splits a string into a list delimited by the passed pattern.  The
1114+method is invaluable for converting textual data into data structures that can be
1115+easily read and modified by Python as demonstrated in the following example that
1116+creates a phonebook.
1117+ 
1118+First, here is the input.  Normally it may come from a file, here we are using
1119+triple-quoted string syntax:
1120+ 
1121+   >>> input = """Ross McFluff: 834.345.1254 155 Elm Street
1122+   ...
1123+   ... Ronald Heathmore: 892.345.3428 436 Finley Avenue
1124+   ... Frank Burger: 925.541.7625 662 South Dogwood Way
1125+   ...
1126+   ...
1127+   ... Heather Albrecht: 548.326.4584 919 Park Place"""
1128+ 
1129+The entries are separated by one or more newlines. Now we convert the string
1130+into a list with each nonempty line having its own entry:
1131+ 
1132+.. doctest::
1133+   :options: +NORMALIZE_WHITESPACE
1134+ 
1135+   >>> entries = re.split("\n+", input)
1136+   >>> entries
1137+   ['Ross McFluff: 834.345.1254 155 Elm Street',
1138+   'Ronald Heathmore: 892.345.3428 436 Finley Avenue',
1139+   'Frank Burger: 925.541.7625 662 South Dogwood Way',
1140+   'Heather Albrecht: 548.326.4584 919 Park Place']
1141+ 
1142+Finally, split each entry into a list with first name, last name, telephone
1143+number, and address.  We use the ``maxsplit`` parameter of :func:`split`
1144+because the address has spaces, our splitting pattern, in it:
1145+ 
1146+.. doctest::
1147+   :options: +NORMALIZE_WHITESPACE
1148+ 
1149+   >>> [re.split(":? ", entry, 3) for entry in entries]
1150+   [['Ross', 'McFluff', '834.345.1254', '155 Elm Street'],
1151+   ['Ronald', 'Heathmore', '892.345.3428', '436 Finley Avenue'],
1152+   ['Frank', 'Burger', '925.541.7625', '662 South Dogwood Way'],
1153+   ['Heather', 'Albrecht', '548.326.4584', '919 Park Place']]
1154+ 
1155+The ``:?`` pattern matches the colon after the last name, so that it does not
1156+occur in the result list.  With a ``maxsplit`` of ``4``, we could separate the
1157+house number from the street name:
1158+ 
1159+.. doctest::
1160+   :options: +NORMALIZE_WHITESPACE
1161+ 
1162+   >>> [re.split(":? ", entry, 4) for entry in entries]
1163+   [['Ross', 'McFluff', '834.345.1254', '155', 'Elm Street'],
1164+   ['Ronald', 'Heathmore', '892.345.3428', '436', 'Finley Avenue'],
1165+   ['Frank', 'Burger', '925.541.7625', '662', 'South Dogwood Way'],
1166+   ['Heather', 'Albrecht', '548.326.4584', '919', 'Park Place']]
1167+ 
1168+ 
1169+Text Munging
1170+^^^^^^^^^^^^
1171+ 
1172+:func:`sub` replaces every occurrence of a pattern with a string or the
1173+result of a function.  This example demonstrates using :func:`sub` with
1174+a function to "munge" text, or randomize the order of all the characters
1175+in each word of a sentence except for the first and last characters::
1176+ 
1177+   >>> def repl(m):
1178+   ...   inner_word = list(m.group(2))
1179+   ...   random.shuffle(inner_word)
1180+   ...   return m.group(1) + "".join(inner_word) + m.group(3)
1181+   >>> text = "Professor Abdolmalek, please report your absences promptly."
1182+   >>> re.sub("(\w)(\w+)(\w)", repl, text)
1183+   'Poefsrosr Aealmlobdk, pslaee reorpt your abnseces plmrptoy.'
1184+   >>> re.sub("(\w)(\w+)(\w)", repl, text)
1185+   'Pofsroser Aodlambelk, plasee reoprt yuor asnebces potlmrpy.'
1186+ 
1187+ 
1188+Finding all Adverbs
1189+^^^^^^^^^^^^^^^^^^^
1190+ 
1191+:func:`findall` matches *all* occurrences of a pattern, not just the first
1192+one as :func:`search` does.  For example, if one was a writer and wanted to
1193+find all of the adverbs in some text, he or she might use :func:`findall` in
1194+the following manner:
1195+ 
1196+   >>> text = "He was carefully disguised but captured quickly by police."
1197+   >>> re.findall(r"\w+ly", text)
1198+   ['carefully', 'quickly']
1199+ 
1200+ 
1201+Finding all Adverbs and their Positions
1202+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1203+ 
1204+If one wants more information about all matches of a pattern than the matched
1205+text, :func:`finditer` is useful as it provides instances of
1206+:class:`MatchObject` instead of strings.  Continuing with the previous example,
1207+if one was a writer who wanted to find all of the adverbs *and their positions*
1208+in some text, he or she would use :func:`finditer` in the following manner:
1209+ 
1210+   >>> text = "He was carefully disguised but captured quickly by police."
1211+   >>> for m in re.finditer(r"\w+ly", text):
1212+   ...     print '%02d-%02d: %s' % (m.start(), m.end(), m.group(0))
1213+   07-16: carefully
1214+   40-47: quickly
1215+ 
1216+ 
1217+Raw String Notation
1218+^^^^^^^^^^^^^^^^^^^
1219+ 
1220+Raw string notation (``r"text"``) keeps regular expressions sane.  Without it,
1221+every backslash (``'\'``) in a regular expression would have to be prefixed with
1222+another one to escape it.  For example, the two following lines of code are
1223+functionally identical:
1224+ 
1225+   >>> re.match(r"\W(.)\1\W", " ff ")
1226+   <_sre.SRE_Match object at ...>
1227+   >>> re.match("\\W(.)\\1\\W", " ff ")
1228+   <_sre.SRE_Match object at ...>
1229+ 
1230+When one wants to match a literal backslash, it must be escaped in the regular
1231+expression.  With raw string notation, this means ``r"\\"``.  Without raw string
1232+notation, one must use ``"\\\\"``, making the following lines of code
1233+functionally identical:
1234+ 
1235+   >>> re.match(r"\\", r"\\")
1236+   <_sre.SRE_Match object at ...>
1237+   >>> re.match("\\\\", r"\\")
1238+   <_sre.SRE_Match object at ...>
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op