blob: db7e1cfc32f87fd627d25dd9ace9db840535df58 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001
2:mod:`re` --- Regular expression operations
3===========================================
4
5.. module:: re
6 :synopsis: Regular expression operations.
7.. moduleauthor:: Fredrik Lundh <fredrik@pythonware.com>
8.. sectionauthor:: Andrew M. Kuchling <amk@amk.ca>
9
10
Georg Brandl8ec7f652007-08-15 14:28:01 +000011This module provides regular expression matching operations similar to
12those found in Perl. Both patterns and strings to be searched can be
Georg Brandl382edff2009-03-31 15:43:20 +000013Unicode strings as well as 8-bit strings.
Georg Brandl8ec7f652007-08-15 14:28:01 +000014
15Regular expressions use the backslash character (``'\'``) to indicate
16special forms or to allow special characters to be used without invoking
17their special meaning. This collides with Python's usage of the same
18character for the same purpose in string literals; for example, to match
19a literal backslash, one might have to write ``'\\\\'`` as the pattern
20string, because the regular expression must be ``\\``, and each
21backslash must be expressed as ``\\`` inside a regular Python string
22literal.
23
24The solution is to use Python's raw string notation for regular expression
25patterns; backslashes are not handled in any special way in a string literal
26prefixed with ``'r'``. So ``r"\n"`` is a two-character string containing
27``'\'`` and ``'n'``, while ``"\n"`` is a one-character string containing a
Georg Brandlba2e5192007-09-27 06:26:58 +000028newline. Usually patterns will be expressed in Python code using this raw
29string notation.
Georg Brandl8ec7f652007-08-15 14:28:01 +000030
Georg Brandlb8df1562007-12-05 18:30:48 +000031It is important to note that most regular expression operations are available as
32module-level functions and :class:`RegexObject` methods. The functions are
33shortcuts that don't require you to compile a regex object first, but miss some
34fine-tuning parameters.
35
Georg Brandl8ec7f652007-08-15 14:28:01 +000036
37.. _re-syntax:
38
39Regular Expression Syntax
40-------------------------
41
42A regular expression (or RE) specifies a set of strings that matches it; the
43functions in this module let you check if a particular string matches a given
44regular expression (or if a given regular expression matches a particular
45string, which comes down to the same thing).
46
47Regular expressions can be concatenated to form new regular expressions; if *A*
48and *B* are both regular expressions, then *AB* is also a regular expression.
49In general, if a string *p* matches *A* and another string *q* matches *B*, the
50string *pq* will match AB. This holds unless *A* or *B* contain low precedence
51operations; boundary conditions between *A* and *B*; or have numbered group
52references. Thus, complex expressions can easily be constructed from simpler
53primitive expressions like the ones described here. For details of the theory
54and implementation of regular expressions, consult the Friedl book referenced
55above, or almost any textbook about compiler construction.
56
57A brief explanation of the format of regular expressions follows. For further
Georg Brandl1cf05222008-02-05 12:01:24 +000058information and a gentler presentation, consult the :ref:`regex-howto`.
Georg Brandl8ec7f652007-08-15 14:28:01 +000059
60Regular expressions can contain both special and ordinary characters. Most
61ordinary characters, like ``'A'``, ``'a'``, or ``'0'``, are the simplest regular
62expressions; they simply match themselves. You can concatenate ordinary
63characters, so ``last`` matches the string ``'last'``. (In the rest of this
64section, we'll write RE's in ``this special style``, usually without quotes, and
65strings to be matched ``'in single quotes'``.)
66
67Some characters, like ``'|'`` or ``'('``, are special. Special
68characters either stand for classes of ordinary characters, or affect
69how the regular expressions around them are interpreted. Regular
70expression pattern strings may not contain null bytes, but can specify
71the null byte using the ``\number`` notation, e.g., ``'\x00'``.
72
73
74The special characters are:
75
Georg Brandl8ec7f652007-08-15 14:28:01 +000076``'.'``
77 (Dot.) In the default mode, this matches any character except a newline. If
78 the :const:`DOTALL` flag has been specified, this matches any character
79 including a newline.
80
81``'^'``
82 (Caret.) Matches the start of the string, and in :const:`MULTILINE` mode also
83 matches immediately after each newline.
84
85``'$'``
86 Matches the end of the string or just before the newline at the end of the
87 string, and in :const:`MULTILINE` mode also matches before a newline. ``foo``
88 matches both 'foo' and 'foobar', while the regular expression ``foo$`` matches
89 only 'foo'. More interestingly, searching for ``foo.$`` in ``'foo1\nfoo2\n'``
Amaury Forgeot d'Arcd08a8eb2008-01-10 21:59:42 +000090 matches 'foo2' normally, but 'foo1' in :const:`MULTILINE` mode; searching for
91 a single ``$`` in ``'foo\n'`` will find two (empty) matches: one just before
92 the newline, and one at the end of the string.
Georg Brandl8ec7f652007-08-15 14:28:01 +000093
94``'*'``
95 Causes the resulting RE to match 0 or more repetitions of the preceding RE, as
96 many repetitions as are possible. ``ab*`` will match 'a', 'ab', or 'a' followed
97 by any number of 'b's.
98
99``'+'``
100 Causes the resulting RE to match 1 or more repetitions of the preceding RE.
101 ``ab+`` will match 'a' followed by any non-zero number of 'b's; it will not
102 match just 'a'.
103
104``'?'``
105 Causes the resulting RE to match 0 or 1 repetitions of the preceding RE.
106 ``ab?`` will match either 'a' or 'ab'.
107
108``*?``, ``+?``, ``??``
109 The ``'*'``, ``'+'``, and ``'?'`` qualifiers are all :dfn:`greedy`; they match
110 as much text as possible. Sometimes this behaviour isn't desired; if the RE
111 ``<.*>`` is matched against ``'<H1>title</H1>'``, it will match the entire
112 string, and not just ``'<H1>'``. Adding ``'?'`` after the qualifier makes it
113 perform the match in :dfn:`non-greedy` or :dfn:`minimal` fashion; as *few*
114 characters as possible will be matched. Using ``.*?`` in the previous
115 expression will match only ``'<H1>'``.
116
117``{m}``
118 Specifies that exactly *m* copies of the previous RE should be matched; fewer
119 matches cause the entire RE not to match. For example, ``a{6}`` will match
120 exactly six ``'a'`` characters, but not five.
121
122``{m,n}``
123 Causes the resulting RE to match from *m* to *n* repetitions of the preceding
124 RE, attempting to match as many repetitions as possible. For example,
125 ``a{3,5}`` will match from 3 to 5 ``'a'`` characters. Omitting *m* specifies a
126 lower bound of zero, and omitting *n* specifies an infinite upper bound. As an
127 example, ``a{4,}b`` will match ``aaaab`` or a thousand ``'a'`` characters
128 followed by a ``b``, but not ``aaab``. The comma may not be omitted or the
129 modifier would be confused with the previously described form.
130
131``{m,n}?``
132 Causes the resulting RE to match from *m* to *n* repetitions of the preceding
133 RE, attempting to match as *few* repetitions as possible. This is the
134 non-greedy version of the previous qualifier. For example, on the
135 6-character string ``'aaaaaa'``, ``a{3,5}`` will match 5 ``'a'`` characters,
136 while ``a{3,5}?`` will only match 3 characters.
137
138``'\'``
139 Either escapes special characters (permitting you to match characters like
140 ``'*'``, ``'?'``, and so forth), or signals a special sequence; special
141 sequences are discussed below.
142
143 If you're not using a raw string to express the pattern, remember that Python
144 also uses the backslash as an escape sequence in string literals; if the escape
145 sequence isn't recognized by Python's parser, the backslash and subsequent
146 character are included in the resulting string. However, if Python would
147 recognize the resulting sequence, the backslash should be repeated twice. This
148 is complicated and hard to understand, so it's highly recommended that you use
149 raw strings for all but the simplest expressions.
150
151``[]``
Ezio Melottia1958732011-10-20 19:31:08 +0300152 Used to indicate a set of characters. In a set:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000153
Ezio Melottia1958732011-10-20 19:31:08 +0300154 * Characters can be listed individually, e.g. ``[amk]`` will match ``'a'``,
155 ``'m'``, or ``'k'``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000156
Ezio Melottia1958732011-10-20 19:31:08 +0300157 * Ranges of characters can be indicated by giving two characters and separating
158 them by a ``'-'``, for example ``[a-z]`` will match any lowercase ASCII letter,
159 ``[0-5][0-9]`` will match all the two-digits numbers from ``00`` to ``59``, and
160 ``[0-9A-Fa-f]`` will match any hexadecimal digit. If ``-`` is escaped (e.g.
161 ``[a\-z]``) or if it's placed as the first or last character (e.g. ``[a-]``),
162 it will match a literal ``'-'``.
163
164 * Special characters lose their special meaning inside sets. For example,
165 ``[(+*)]`` will match any of the literal characters ``'('``, ``'+'``,
166 ``'*'``, or ``')'``.
167
168 * Character classes such as ``\w`` or ``\S`` (defined below) are also accepted
169 inside a set, although the characters they match depends on whether
170 :const:`LOCALE` or :const:`UNICODE` mode is in force.
171
172 * Characters that are not within a range can be matched by :dfn:`complementing`
173 the set. If the first character of the set is ``'^'``, all the characters
174 that are *not* in the set will be matched. For example, ``[^5]`` will match
175 any character except ``'5'``, and ``[^^]`` will match any character except
176 ``'^'``. ``^`` has no special meaning if it's not the first character in
177 the set.
178
179 * To match a literal ``']'`` inside a set, precede it with a backslash, or
180 place it at the beginning of the set. For example, both ``[()[\]{}]`` and
181 ``[]()[{}]`` will both match a parenthesis.
Mark Summerfield700a6352008-05-31 13:05:34 +0000182
Georg Brandl8ec7f652007-08-15 14:28:01 +0000183``'|'``
184 ``A|B``, where A and B can be arbitrary REs, creates a regular expression that
185 will match either A or B. An arbitrary number of REs can be separated by the
186 ``'|'`` in this way. This can be used inside groups (see below) as well. As
187 the target string is scanned, REs separated by ``'|'`` are tried from left to
188 right. When one pattern completely matches, that branch is accepted. This means
189 that once ``A`` matches, ``B`` will not be tested further, even if it would
190 produce a longer overall match. In other words, the ``'|'`` operator is never
191 greedy. To match a literal ``'|'``, use ``\|``, or enclose it inside a
192 character class, as in ``[|]``.
193
194``(...)``
195 Matches whatever regular expression is inside the parentheses, and indicates the
196 start and end of a group; the contents of a group can be retrieved after a match
197 has been performed, and can be matched later in the string with the ``\number``
198 special sequence, described below. To match the literals ``'('`` or ``')'``,
199 use ``\(`` or ``\)``, or enclose them inside a character class: ``[(] [)]``.
200
201``(?...)``
202 This is an extension notation (a ``'?'`` following a ``'('`` is not meaningful
203 otherwise). The first character after the ``'?'`` determines what the meaning
204 and further syntax of the construct is. Extensions usually do not create a new
205 group; ``(?P<name>...)`` is the only exception to this rule. Following are the
206 currently supported extensions.
207
208``(?iLmsux)``
209 (One or more letters from the set ``'i'``, ``'L'``, ``'m'``, ``'s'``,
210 ``'u'``, ``'x'``.) The group matches the empty string; the letters
211 set the corresponding flags: :const:`re.I` (ignore case),
212 :const:`re.L` (locale dependent), :const:`re.M` (multi-line),
213 :const:`re.S` (dot matches all), :const:`re.U` (Unicode dependent),
214 and :const:`re.X` (verbose), for the entire regular expression. (The
215 flags are described in :ref:`contents-of-module-re`.) This
216 is useful if you wish to include the flags as part of the regular
217 expression, instead of passing a *flag* argument to the
Georg Brandl74f8fc02009-07-26 13:36:39 +0000218 :func:`re.compile` function.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000219
220 Note that the ``(?x)`` flag changes how the expression is parsed. It should be
221 used first in the expression string, or after one or more whitespace characters.
222 If there are non-whitespace characters before the flag, the results are
223 undefined.
224
225``(?:...)``
Georg Brandl3b85b9b2010-11-26 08:20:18 +0000226 A non-capturing version of regular parentheses. Matches whatever regular
Georg Brandl8ec7f652007-08-15 14:28:01 +0000227 expression is inside the parentheses, but the substring matched by the group
228 *cannot* be retrieved after performing a match or referenced later in the
229 pattern.
230
231``(?P<name>...)``
232 Similar to regular parentheses, but the substring matched by the group is
Georg Brandlddbdc9a2013-10-06 12:08:14 +0200233 accessible via the symbolic group name *name*. Group names must be valid
234 Python identifiers, and each group name must be defined only once within a
235 regular expression. A symbolic group is also a numbered group, just as if
236 the group were not named.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000237
Georg Brandlddbdc9a2013-10-06 12:08:14 +0200238 Named groups can be referenced in three contexts. If the pattern is
239 ``(?P<quote>['"]).*?(?P=quote)`` (i.e. matching a string quoted with either
240 single or double quotes):
241
242 +---------------------------------------+----------------------------------+
243 | Context of reference to group "quote" | Ways to reference it |
244 +=======================================+==================================+
245 | in the same pattern itself | * ``(?P=quote)`` (as shown) |
246 | | * ``\1`` |
247 +---------------------------------------+----------------------------------+
248 | when processing match object ``m`` | * ``m.group('quote')`` |
249 | | * ``m.end('quote')`` (etc.) |
250 +---------------------------------------+----------------------------------+
251 | in a string passed to the ``repl`` | * ``\g<quote>`` |
252 | argument of ``re.sub()`` | * ``\g<1>`` |
253 | | * ``\1`` |
254 +---------------------------------------+----------------------------------+
Georg Brandl8ec7f652007-08-15 14:28:01 +0000255
256``(?P=name)``
Georg Brandlddbdc9a2013-10-06 12:08:14 +0200257 A backreference to a named group; it matches whatever text was matched by the
258 earlier group named *name*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000259
260``(?#...)``
261 A comment; the contents of the parentheses are simply ignored.
262
263``(?=...)``
264 Matches if ``...`` matches next, but doesn't consume any of the string. This is
265 called a lookahead assertion. For example, ``Isaac (?=Asimov)`` will match
266 ``'Isaac '`` only if it's followed by ``'Asimov'``.
267
268``(?!...)``
269 Matches if ``...`` doesn't match next. This is a negative lookahead assertion.
270 For example, ``Isaac (?!Asimov)`` will match ``'Isaac '`` only if it's *not*
271 followed by ``'Asimov'``.
272
273``(?<=...)``
274 Matches if the current position in the string is preceded by a match for ``...``
275 that ends at the current position. This is called a :dfn:`positive lookbehind
276 assertion`. ``(?<=abc)def`` will find a match in ``abcdef``, since the
277 lookbehind will back up 3 characters and check if the contained pattern matches.
278 The contained pattern must only match strings of some fixed length, meaning that
279 ``abc`` or ``a|b`` are allowed, but ``a*`` and ``a{3,4}`` are not. Note that
Ezio Melotti11427732012-04-29 07:34:22 +0300280 patterns which start with positive lookbehind assertions will not match at the
Georg Brandl8ec7f652007-08-15 14:28:01 +0000281 beginning of the string being searched; you will most likely want to use the
Georg Brandl6199e322008-03-22 12:04:26 +0000282 :func:`search` function rather than the :func:`match` function:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000283
284 >>> import re
285 >>> m = re.search('(?<=abc)def', 'abcdef')
286 >>> m.group(0)
287 'def'
288
Georg Brandl6199e322008-03-22 12:04:26 +0000289 This example looks for a word following a hyphen:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000290
291 >>> m = re.search('(?<=-)\w+', 'spam-egg')
292 >>> m.group(0)
293 'egg'
294
295``(?<!...)``
296 Matches if the current position in the string is not preceded by a match for
297 ``...``. This is called a :dfn:`negative lookbehind assertion`. Similar to
298 positive lookbehind assertions, the contained pattern must only match strings of
299 some fixed length. Patterns which start with negative lookbehind assertions may
300 match at the beginning of the string being searched.
301
302``(?(id/name)yes-pattern|no-pattern)``
303 Will try to match with ``yes-pattern`` if the group with given *id* or *name*
304 exists, and with ``no-pattern`` if it doesn't. ``no-pattern`` is optional and
305 can be omitted. For example, ``(<)?(\w+@\w+(?:\.\w+)+)(?(1)>)`` is a poor email
306 matching pattern, which will match with ``'<user@host.com>'`` as well as
307 ``'user@host.com'``, but not with ``'<user@host.com'``.
308
309 .. versionadded:: 2.4
310
311The special sequences consist of ``'\'`` and a character from the list below.
312If the ordinary character is not on the list, then the resulting RE will match
313the second character. For example, ``\$`` matches the character ``'$'``.
314
Georg Brandl8ec7f652007-08-15 14:28:01 +0000315``\number``
316 Matches the contents of the group of the same number. Groups are numbered
317 starting from 1. For example, ``(.+) \1`` matches ``'the the'`` or ``'55 55'``,
Georg Brandl980db0a2013-10-06 12:58:20 +0200318 but not ``'thethe'`` (note the space after the group). This special sequence
Georg Brandl8ec7f652007-08-15 14:28:01 +0000319 can only be used to match one of the first 99 groups. If the first digit of
320 *number* is 0, or *number* is 3 octal digits long, it will not be interpreted as
321 a group match, but as the character with octal value *number*. Inside the
322 ``'['`` and ``']'`` of a character class, all numeric escapes are treated as
323 characters.
324
325``\A``
326 Matches only at the start of the string.
327
328``\b``
329 Matches the empty string, but only at the beginning or end of a word. A word is
330 defined as a sequence of alphanumeric or underscore characters, so the end of a
331 word is indicated by whitespace or a non-alphanumeric, non-underscore character.
Ezio Melotti38ae5b22012-02-29 11:40:00 +0200332 Note that formally, ``\b`` is defined as the boundary between a ``\w`` and
333 a ``\W`` character (or vice versa), or between ``\w`` and the beginning/end
334 of the string, so the precise set of characters deemed to be alphanumeric
335 depends on the values of the ``UNICODE`` and ``LOCALE`` flags.
336 For example, ``r'\bfoo\b'`` matches ``'foo'``, ``'foo.'``, ``'(foo)'``,
337 ``'bar foo baz'`` but not ``'foobar'`` or ``'foo3'``.
Georg Brandlddbdc9a2013-10-06 12:08:14 +0200338 Inside a character range, ``\b`` represents the backspace character, for
339 compatibility with Python's string literals.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000340
341``\B``
342 Matches the empty string, but only when it is *not* at the beginning or end of a
Ezio Melotti38ae5b22012-02-29 11:40:00 +0200343 word. This means that ``r'py\B'`` matches ``'python'``, ``'py3'``, ``'py2'``,
344 but not ``'py'``, ``'py.'``, or ``'py!'``.
345 ``\B`` is just the opposite of ``\b``, so is also subject to the settings
Georg Brandl8ec7f652007-08-15 14:28:01 +0000346 of ``LOCALE`` and ``UNICODE``.
347
348``\d``
349 When the :const:`UNICODE` flag is not specified, matches any decimal digit; this
350 is equivalent to the set ``[0-9]``. With :const:`UNICODE`, it will match
Mark Dickinsonfe67bd92009-07-28 20:35:03 +0000351 whatever is classified as a decimal digit in the Unicode character properties
352 database.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000353
354``\D``
355 When the :const:`UNICODE` flag is not specified, matches any non-digit
356 character; this is equivalent to the set ``[^0-9]``. With :const:`UNICODE`, it
357 will match anything other than character marked as digits in the Unicode
358 character properties database.
359
360``\s``
Senthil Kumarandc0b3242012-04-11 03:22:58 +0800361 When the :const:`UNICODE` flag is not specified, it matches any whitespace
362 character, this is equivalent to the set ``[ \t\n\r\f\v]``. The
363 :const:`LOCALE` flag has no extra effect on matching of the space.
364 If :const:`UNICODE` is set, this will match the characters ``[ \t\n\r\f\v]``
365 plus whatever is classified as space in the Unicode character properties
366 database.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000367
368``\S``
Benjamin Peterson72275ef2014-11-25 14:54:45 -0600369 When the :const:`UNICODE` flag is not specified, matches any non-whitespace
Senthil Kumarandc0b3242012-04-11 03:22:58 +0800370 character; this is equivalent to the set ``[^ \t\n\r\f\v]`` The
371 :const:`LOCALE` flag has no extra effect on non-whitespace match. If
372 :const:`UNICODE` is set, then any character not marked as space in the
373 Unicode character properties database is matched.
374
Georg Brandl8ec7f652007-08-15 14:28:01 +0000375
376``\w``
377 When the :const:`LOCALE` and :const:`UNICODE` flags are not specified, matches
378 any alphanumeric character and the underscore; this is equivalent to the set
379 ``[a-zA-Z0-9_]``. With :const:`LOCALE`, it will match the set ``[0-9_]`` plus
380 whatever characters are defined as alphanumeric for the current locale. If
381 :const:`UNICODE` is set, this will match the characters ``[0-9_]`` plus whatever
382 is classified as alphanumeric in the Unicode character properties database.
383
384``\W``
385 When the :const:`LOCALE` and :const:`UNICODE` flags are not specified, matches
386 any non-alphanumeric character; this is equivalent to the set ``[^a-zA-Z0-9_]``.
387 With :const:`LOCALE`, it will match any character not in the set ``[0-9_]``, and
388 not defined as alphanumeric for the current locale. If :const:`UNICODE` is set,
Zachary Ware7ca2a902014-10-19 01:06:58 -0500389 this will match anything other than ``[0-9_]`` plus characters classified as
Senthil Kumaran15b6f3f2012-03-11 20:37:39 -0700390 not alphanumeric in the Unicode character properties database.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000391
392``\Z``
393 Matches only at the end of the string.
394
Senthil Kumaran15b6f3f2012-03-11 20:37:39 -0700395If both :const:`LOCALE` and :const:`UNICODE` flags are included for a
396particular sequence, then :const:`LOCALE` flag takes effect first followed by
397the :const:`UNICODE`.
398
Georg Brandl8ec7f652007-08-15 14:28:01 +0000399Most of the standard escapes supported by Python string literals are also
400accepted by the regular expression parser::
401
402 \a \b \f \n
403 \r \t \v \x
404 \\
405
Ezio Melotti48d886b2012-04-29 04:46:34 +0300406(Note that ``\b`` is used to represent word boundaries, and means "backspace"
407only inside character classes.)
408
Georg Brandl8ec7f652007-08-15 14:28:01 +0000409Octal escapes are included in a limited form: If the first digit is a 0, or if
410there are three octal digits, it is considered an octal escape. Otherwise, it is
411a group reference. As for string literals, octal escapes are always at most
412three digits in length.
413
Georg Brandlae4ca792014-10-28 21:41:51 +0100414.. seealso::
415
416 Mastering Regular Expressions
417 Book on regular expressions by Jeffrey Friedl, published by O'Reilly. The
418 second edition of the book no longer covers Python at all, but the first
419 edition covered writing good regular expression patterns in great detail.
420
421
Georg Brandl8ec7f652007-08-15 14:28:01 +0000422
Georg Brandl8ec7f652007-08-15 14:28:01 +0000423.. _contents-of-module-re:
424
425Module Contents
426---------------
427
428The module defines several functions, constants, and an exception. Some of the
429functions are simplified versions of the full featured methods for compiled
430regular expressions. Most non-trivial applications always use the compiled
431form.
432
433
Eli Benderskyeb711382011-11-14 01:02:20 +0200434.. function:: compile(pattern, flags=0)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000435
Georg Brandlba2e5192007-09-27 06:26:58 +0000436 Compile a regular expression pattern into a regular expression object, which
Ezio Melotti33b810d2014-06-20 00:47:11 +0300437 can be used for matching using its :func:`~RegexObject.match` and
438 :func:`~RegexObject.search` methods, described below.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000439
440 The expression's behaviour can be modified by specifying a *flags* value.
441 Values can be any of the following variables, combined using bitwise OR (the
442 ``|`` operator).
443
444 The sequence ::
445
Gregory P. Smith0261e5d2009-03-02 04:53:24 +0000446 prog = re.compile(pattern)
447 result = prog.match(string)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000448
449 is equivalent to ::
450
Gregory P. Smith0261e5d2009-03-02 04:53:24 +0000451 result = re.match(pattern, string)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000452
Georg Brandl74f8fc02009-07-26 13:36:39 +0000453 but using :func:`re.compile` and saving the resulting regular expression
454 object for reuse is more efficient when the expression will be used several
455 times in a single program.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000456
Gregory P. Smith0261e5d2009-03-02 04:53:24 +0000457 .. note::
458
459 The compiled versions of the most recent patterns passed to
460 :func:`re.match`, :func:`re.search` or :func:`re.compile` are cached, so
461 programs that use only a few regular expressions at a time needn't worry
462 about compiling regular expressions.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000463
464
Sandro Tosie827c132012-01-01 12:52:24 +0100465.. data:: DEBUG
466
467 Display debug information about compiled expression.
468
469
Georg Brandl8ec7f652007-08-15 14:28:01 +0000470.. data:: I
471 IGNORECASE
472
473 Perform case-insensitive matching; expressions like ``[A-Z]`` will match
474 lowercase letters, too. This is not affected by the current locale.
475
476
477.. data:: L
478 LOCALE
479
Georg Brandlba2e5192007-09-27 06:26:58 +0000480 Make ``\w``, ``\W``, ``\b``, ``\B``, ``\s`` and ``\S`` dependent on the
481 current locale.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000482
483
484.. data:: M
485 MULTILINE
486
487 When specified, the pattern character ``'^'`` matches at the beginning of the
488 string and at the beginning of each line (immediately following each newline);
489 and the pattern character ``'$'`` matches at the end of the string and at the
490 end of each line (immediately preceding each newline). By default, ``'^'``
491 matches only at the beginning of the string, and ``'$'`` only at the end of the
492 string and immediately before the newline (if any) at the end of the string.
493
494
495.. data:: S
496 DOTALL
497
498 Make the ``'.'`` special character match any character at all, including a
499 newline; without this flag, ``'.'`` will match anything *except* a newline.
500
501
502.. data:: U
503 UNICODE
504
505 Make ``\w``, ``\W``, ``\b``, ``\B``, ``\d``, ``\D``, ``\s`` and ``\S`` dependent
506 on the Unicode character properties database.
507
508 .. versionadded:: 2.0
509
510
511.. data:: X
512 VERBOSE
513
514 This flag allows you to write regular expressions that look nicer. Whitespace
515 within the pattern is ignored, except when in a character class or preceded by
516 an unescaped backslash, and, when a line contains a ``'#'`` neither in a
517 character class or preceded by an unescaped backslash, all characters from the
518 leftmost such ``'#'`` through the end of the line are ignored.
519
Georg Brandlb8df1562007-12-05 18:30:48 +0000520 That means that the two following regular expression objects that match a
521 decimal number are functionally equal::
522
523 a = re.compile(r"""\d + # the integral part
524 \. # the decimal point
525 \d * # some fractional digits""", re.X)
526 b = re.compile(r"\d+\.\d*")
Georg Brandl8ec7f652007-08-15 14:28:01 +0000527
528
Eli Benderskyeb711382011-11-14 01:02:20 +0200529.. function:: search(pattern, string, flags=0)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000530
Terry Jan Reedy9f7f62f2014-05-30 16:19:50 -0400531 Scan through *string* looking for the first location where the regular expression
Georg Brandl8ec7f652007-08-15 14:28:01 +0000532 *pattern* produces a match, and return a corresponding :class:`MatchObject`
533 instance. Return ``None`` if no position in the string matches the pattern; note
534 that this is different from finding a zero-length match at some point in the
535 string.
536
537
Eli Benderskyeb711382011-11-14 01:02:20 +0200538.. function:: match(pattern, string, flags=0)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000539
540 If zero or more characters at the beginning of *string* match the regular
541 expression *pattern*, return a corresponding :class:`MatchObject` instance.
542 Return ``None`` if the string does not match the pattern; note that this is
543 different from a zero-length match.
544
Ezio Melottid9de93e2012-02-29 13:37:07 +0200545 Note that even in :const:`MULTILINE` mode, :func:`re.match` will only match
546 at the beginning of the string and not at the beginning of each line.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000547
Ezio Melottid9de93e2012-02-29 13:37:07 +0200548 If you want to locate a match anywhere in *string*, use :func:`search`
549 instead (see also :ref:`search-vs-match`).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000550
551
Eli Benderskyeb711382011-11-14 01:02:20 +0200552.. function:: split(pattern, string, maxsplit=0, flags=0)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000553
554 Split *string* by the occurrences of *pattern*. If capturing parentheses are
555 used in *pattern*, then the text of all groups in the pattern are also returned
556 as part of the resulting list. If *maxsplit* is nonzero, at most *maxsplit*
557 splits occur, and the remainder of the string is returned as the final element
558 of the list. (Incompatibility note: in the original Python 1.5 release,
Georg Brandl6199e322008-03-22 12:04:26 +0000559 *maxsplit* was ignored. This has been fixed in later releases.)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000560
561 >>> re.split('\W+', 'Words, words, words.')
562 ['Words', 'words', 'words', '']
563 >>> re.split('(\W+)', 'Words, words, words.')
564 ['Words', ', ', 'words', ', ', 'words', '.', '']
565 >>> re.split('\W+', 'Words, words, words.', 1)
566 ['Words', 'words, words.']
Gregory P. Smithae91d092009-03-02 05:13:57 +0000567 >>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
568 ['0', '3', '9']
Georg Brandl8ec7f652007-08-15 14:28:01 +0000569
Georg Brandl70992c32008-03-06 07:19:15 +0000570 If there are capturing groups in the separator and it matches at the start of
571 the string, the result will start with an empty string. The same holds for
Georg Brandl6199e322008-03-22 12:04:26 +0000572 the end of the string:
Georg Brandl70992c32008-03-06 07:19:15 +0000573
574 >>> re.split('(\W+)', '...words, words...')
575 ['', '...', 'words', ', ', 'words', '...', '']
576
577 That way, separator components are always found at the same relative
578 indices within the result list (e.g., if there's one capturing group
579 in the separator, the 0th, the 2nd and so forth).
580
Skip Montanaro222907d2007-09-01 17:40:03 +0000581 Note that *split* will never split a string on an empty pattern match.
Georg Brandl6199e322008-03-22 12:04:26 +0000582 For example:
Skip Montanaro222907d2007-09-01 17:40:03 +0000583
584 >>> re.split('x*', 'foo')
585 ['foo']
586 >>> re.split("(?m)^$", "foo\n\nbar\n")
587 ['foo\n\nbar\n']
Georg Brandl8ec7f652007-08-15 14:28:01 +0000588
Ezio Melotti1e5d3182010-11-26 09:30:44 +0000589 .. versionchanged:: 2.7
Gregory P. Smithae91d092009-03-02 05:13:57 +0000590 Added the optional flags argument.
591
Georg Brandl70992c32008-03-06 07:19:15 +0000592
Eli Benderskyeb711382011-11-14 01:02:20 +0200593.. function:: findall(pattern, string, flags=0)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000594
Georg Brandlba2e5192007-09-27 06:26:58 +0000595 Return all non-overlapping matches of *pattern* in *string*, as a list of
Georg Brandlb46d6ff2008-07-19 13:48:44 +0000596 strings. The *string* is scanned left-to-right, and matches are returned in
597 the order found. If one or more groups are present in the pattern, return a
598 list of groups; this will be a list of tuples if the pattern has more than
599 one group. Empty matches are included in the result unless they touch the
600 beginning of another match.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000601
602 .. versionadded:: 1.5.2
603
604 .. versionchanged:: 2.4
605 Added the optional flags argument.
606
607
Eli Benderskyeb711382011-11-14 01:02:20 +0200608.. function:: finditer(pattern, string, flags=0)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000609
Georg Brandle7a09902007-10-21 12:10:28 +0000610 Return an :term:`iterator` yielding :class:`MatchObject` instances over all
Georg Brandlb46d6ff2008-07-19 13:48:44 +0000611 non-overlapping matches for the RE *pattern* in *string*. The *string* is
612 scanned left-to-right, and matches are returned in the order found. Empty
613 matches are included in the result unless they touch the beginning of another
614 match.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000615
616 .. versionadded:: 2.2
617
618 .. versionchanged:: 2.4
619 Added the optional flags argument.
620
621
Eli Benderskyeb711382011-11-14 01:02:20 +0200622.. function:: sub(pattern, repl, string, count=0, flags=0)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000623
624 Return the string obtained by replacing the leftmost non-overlapping occurrences
625 of *pattern* in *string* by the replacement *repl*. If the pattern isn't found,
626 *string* is returned unchanged. *repl* can be a string or a function; if it is
627 a string, any backslash escapes in it are processed. That is, ``\n`` is
Sandro Tosia7eb3c82011-08-19 22:54:33 +0200628 converted to a single newline character, ``\r`` is converted to a carriage return, and
Georg Brandl8ec7f652007-08-15 14:28:01 +0000629 so forth. Unknown escapes such as ``\j`` are left alone. Backreferences, such
630 as ``\6``, are replaced with the substring matched by group 6 in the pattern.
Georg Brandl6199e322008-03-22 12:04:26 +0000631 For example:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000632
633 >>> re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',
634 ... r'static PyObject*\npy_\1(void)\n{',
635 ... 'def myfunc():')
636 'static PyObject*\npy_myfunc(void)\n{'
637
638 If *repl* is a function, it is called for every non-overlapping occurrence of
639 *pattern*. The function takes a single match object argument, and returns the
Georg Brandl6199e322008-03-22 12:04:26 +0000640 replacement string. For example:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000641
642 >>> def dashrepl(matchobj):
643 ... if matchobj.group(0) == '-': return ' '
644 ... else: return '-'
645 >>> re.sub('-{1,2}', dashrepl, 'pro----gram-files')
646 'pro--gram files'
Gregory P. Smithae91d092009-03-02 05:13:57 +0000647 >>> re.sub(r'\sAND\s', ' & ', 'Baked Beans And Spam', flags=re.IGNORECASE)
648 'Baked Beans & Spam'
Georg Brandl8ec7f652007-08-15 14:28:01 +0000649
Georg Brandl04fd3242009-08-13 07:48:05 +0000650 The pattern may be a string or an RE object.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000651
652 The optional argument *count* is the maximum number of pattern occurrences to be
653 replaced; *count* must be a non-negative integer. If omitted or zero, all
654 occurrences will be replaced. Empty matches for the pattern are replaced only
655 when not adjacent to a previous match, so ``sub('x*', '-', 'abc')`` returns
656 ``'-a-b-c-'``.
657
Georg Brandlddbdc9a2013-10-06 12:08:14 +0200658 In string-type *repl* arguments, in addition to the character escapes and
659 backreferences described above,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000660 ``\g<name>`` will use the substring matched by the group named ``name``, as
661 defined by the ``(?P<name>...)`` syntax. ``\g<number>`` uses the corresponding
662 group number; ``\g<2>`` is therefore equivalent to ``\2``, but isn't ambiguous
663 in a replacement such as ``\g<2>0``. ``\20`` would be interpreted as a
664 reference to group 20, not a reference to group 2 followed by the literal
665 character ``'0'``. The backreference ``\g<0>`` substitutes in the entire
666 substring matched by the RE.
667
Ezio Melotti1e5d3182010-11-26 09:30:44 +0000668 .. versionchanged:: 2.7
Gregory P. Smithae91d092009-03-02 05:13:57 +0000669 Added the optional flags argument.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000670
Gregory P. Smithae91d092009-03-02 05:13:57 +0000671
Eli Benderskyeb711382011-11-14 01:02:20 +0200672.. function:: subn(pattern, repl, string, count=0, flags=0)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000673
674 Perform the same operation as :func:`sub`, but return a tuple ``(new_string,
675 number_of_subs_made)``.
676
Ezio Melotti1e5d3182010-11-26 09:30:44 +0000677 .. versionchanged:: 2.7
Gregory P. Smithae91d092009-03-02 05:13:57 +0000678 Added the optional flags argument.
679
Georg Brandl8ec7f652007-08-15 14:28:01 +0000680
681.. function:: escape(string)
682
683 Return *string* with all non-alphanumerics backslashed; this is useful if you
684 want to match an arbitrary literal string that may have regular expression
685 metacharacters in it.
686
687
R. David Murraya63f9b62010-07-10 14:25:18 +0000688.. function:: purge()
689
690 Clear the regular expression cache.
691
692
Georg Brandl8ec7f652007-08-15 14:28:01 +0000693.. exception:: error
694
695 Exception raised when a string passed to one of the functions here is not a
696 valid regular expression (for example, it might contain unmatched parentheses)
697 or when some other error occurs during compilation or matching. It is never an
698 error if a string contains no match for a pattern.
699
700
701.. _re-objects:
702
703Regular Expression Objects
704--------------------------
705
Brian Curtinfbe51992010-03-25 23:48:54 +0000706.. class:: RegexObject
707
708 The :class:`RegexObject` class supports the following methods and attributes:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000709
Georg Brandlb1a14052010-06-01 07:25:23 +0000710 .. method:: RegexObject.search(string[, pos[, endpos]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000711
Georg Brandlb1a14052010-06-01 07:25:23 +0000712 Scan through *string* looking for a location where this regular expression
713 produces a match, and return a corresponding :class:`MatchObject` instance.
714 Return ``None`` if no position in the string matches the pattern; note that this
715 is different from finding a zero-length match at some point in the string.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000716
Brian Curtinfbe51992010-03-25 23:48:54 +0000717 The optional second parameter *pos* gives an index in the string where the
718 search is to start; it defaults to ``0``. This is not completely equivalent to
719 slicing the string; the ``'^'`` pattern character matches at the real beginning
720 of the string and at positions just after a newline, but not necessarily at the
721 index where the search is to start.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000722
Brian Curtinfbe51992010-03-25 23:48:54 +0000723 The optional parameter *endpos* limits how far the string will be searched; it
724 will be as if the string is *endpos* characters long, so only the characters
725 from *pos* to ``endpos - 1`` will be searched for a match. If *endpos* is less
726 than *pos*, no match will be found, otherwise, if *rx* is a compiled regular
Georg Brandlb1a14052010-06-01 07:25:23 +0000727 expression object, ``rx.search(string, 0, 50)`` is equivalent to
728 ``rx.search(string[:50], 0)``.
Georg Brandlb8df1562007-12-05 18:30:48 +0000729
Georg Brandlb1a14052010-06-01 07:25:23 +0000730 >>> pattern = re.compile("d")
731 >>> pattern.search("dog") # Match at index 0
732 <_sre.SRE_Match object at ...>
733 >>> pattern.search("dog", 1) # No match; search doesn't include the "d"
Georg Brandl8ec7f652007-08-15 14:28:01 +0000734
735
Georg Brandlb1a14052010-06-01 07:25:23 +0000736 .. method:: RegexObject.match(string[, pos[, endpos]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000737
Georg Brandlb1a14052010-06-01 07:25:23 +0000738 If zero or more characters at the *beginning* of *string* match this regular
739 expression, return a corresponding :class:`MatchObject` instance. Return
740 ``None`` if the string does not match the pattern; note that this is different
741 from a zero-length match.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000742
Brian Curtinfbe51992010-03-25 23:48:54 +0000743 The optional *pos* and *endpos* parameters have the same meaning as for the
Georg Brandlb1a14052010-06-01 07:25:23 +0000744 :meth:`~RegexObject.search` method.
745
Georg Brandlb1a14052010-06-01 07:25:23 +0000746 >>> pattern = re.compile("o")
747 >>> pattern.match("dog") # No match as "o" is not at the start of "dog".
748 >>> pattern.match("dog", 1) # Match as "o" is the 2nd character of "dog".
749 <_sre.SRE_Match object at ...>
Georg Brandl8ec7f652007-08-15 14:28:01 +0000750
Ezio Melottid9de93e2012-02-29 13:37:07 +0200751 If you want to locate a match anywhere in *string*, use
752 :meth:`~RegexObject.search` instead (see also :ref:`search-vs-match`).
753
Georg Brandl8ec7f652007-08-15 14:28:01 +0000754
Eli Benderskyeb711382011-11-14 01:02:20 +0200755 .. method:: RegexObject.split(string, maxsplit=0)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000756
Brian Curtinfbe51992010-03-25 23:48:54 +0000757 Identical to the :func:`split` function, using the compiled pattern.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000758
759
Brian Curtinfbe51992010-03-25 23:48:54 +0000760 .. method:: RegexObject.findall(string[, pos[, endpos]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000761
Georg Brandlf93ce0c2010-05-22 08:17:23 +0000762 Similar to the :func:`findall` function, using the compiled pattern, but
763 also accepts optional *pos* and *endpos* parameters that limit the search
764 region like for :meth:`match`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000765
766
Brian Curtinfbe51992010-03-25 23:48:54 +0000767 .. method:: RegexObject.finditer(string[, pos[, endpos]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000768
Georg Brandlf93ce0c2010-05-22 08:17:23 +0000769 Similar to the :func:`finditer` function, using the compiled pattern, but
770 also accepts optional *pos* and *endpos* parameters that limit the search
771 region like for :meth:`match`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000772
773
Eli Benderskyeb711382011-11-14 01:02:20 +0200774 .. method:: RegexObject.sub(repl, string, count=0)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000775
Brian Curtinfbe51992010-03-25 23:48:54 +0000776 Identical to the :func:`sub` function, using the compiled pattern.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000777
778
Eli Benderskyeb711382011-11-14 01:02:20 +0200779 .. method:: RegexObject.subn(repl, string, count=0)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000780
Brian Curtinfbe51992010-03-25 23:48:54 +0000781 Identical to the :func:`subn` function, using the compiled pattern.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000782
783
Brian Curtinfbe51992010-03-25 23:48:54 +0000784 .. attribute:: RegexObject.flags
Georg Brandl8ec7f652007-08-15 14:28:01 +0000785
Georg Brandl94a10572012-03-17 17:31:32 +0100786 The regex matching flags. This is a combination of the flags given to
787 :func:`.compile` and any ``(?...)`` inline flags in the pattern.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000788
789
Brian Curtinfbe51992010-03-25 23:48:54 +0000790 .. attribute:: RegexObject.groups
Georg Brandlb46f0d72008-12-05 07:49:49 +0000791
Brian Curtinfbe51992010-03-25 23:48:54 +0000792 The number of capturing groups in the pattern.
Georg Brandlb46f0d72008-12-05 07:49:49 +0000793
794
Brian Curtinfbe51992010-03-25 23:48:54 +0000795 .. attribute:: RegexObject.groupindex
Georg Brandl8ec7f652007-08-15 14:28:01 +0000796
Brian Curtinfbe51992010-03-25 23:48:54 +0000797 A dictionary mapping any symbolic group names defined by ``(?P<id>)`` to group
798 numbers. The dictionary is empty if no symbolic groups were used in the
799 pattern.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000800
801
Brian Curtinfbe51992010-03-25 23:48:54 +0000802 .. attribute:: RegexObject.pattern
Georg Brandl8ec7f652007-08-15 14:28:01 +0000803
Brian Curtinfbe51992010-03-25 23:48:54 +0000804 The pattern string from which the RE object was compiled.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000805
806
807.. _match-objects:
808
809Match Objects
810-------------
811
Brian Curtinfbe51992010-03-25 23:48:54 +0000812.. class:: MatchObject
813
Ezio Melotti51c374d2012-11-04 06:46:28 +0200814 Match objects always have a boolean value of ``True``.
815 Since :meth:`~regex.match` and :meth:`~regex.search` return ``None``
816 when there is no match, you can test whether there was a match with a simple
817 ``if`` statement::
818
819 match = re.search(pattern, string)
820 if match:
821 process(match)
822
823 Match objects support the following methods and attributes:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000824
825
Brian Curtinfbe51992010-03-25 23:48:54 +0000826 .. method:: MatchObject.expand(template)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000827
Brian Curtinfbe51992010-03-25 23:48:54 +0000828 Return the string obtained by doing backslash substitution on the template
829 string *template*, as done by the :meth:`~RegexObject.sub` method. Escapes
830 such as ``\n`` are converted to the appropriate characters, and numeric
831 backreferences (``\1``, ``\2``) and named backreferences (``\g<1>``,
832 ``\g<name>``) are replaced by the contents of the corresponding group.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000833
834
Brian Curtinfbe51992010-03-25 23:48:54 +0000835 .. method:: MatchObject.group([group1, ...])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000836
Brian Curtinfbe51992010-03-25 23:48:54 +0000837 Returns one or more subgroups of the match. If there is a single argument, the
838 result is a single string; if there are multiple arguments, the result is a
839 tuple with one item per argument. Without arguments, *group1* defaults to zero
840 (the whole match is returned). If a *groupN* argument is zero, the corresponding
841 return value is the entire matching string; if it is in the inclusive range
842 [1..99], it is the string matching the corresponding parenthesized group. If a
843 group number is negative or larger than the number of groups defined in the
844 pattern, an :exc:`IndexError` exception is raised. If a group is contained in a
845 part of the pattern that did not match, the corresponding result is ``None``.
846 If a group is contained in a part of the pattern that matched multiple times,
847 the last match is returned.
Georg Brandlb8df1562007-12-05 18:30:48 +0000848
Brian Curtinfbe51992010-03-25 23:48:54 +0000849 >>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
850 >>> m.group(0) # The entire match
851 'Isaac Newton'
852 >>> m.group(1) # The first parenthesized subgroup.
853 'Isaac'
854 >>> m.group(2) # The second parenthesized subgroup.
855 'Newton'
856 >>> m.group(1, 2) # Multiple arguments give us a tuple.
857 ('Isaac', 'Newton')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000858
Brian Curtinfbe51992010-03-25 23:48:54 +0000859 If the regular expression uses the ``(?P<name>...)`` syntax, the *groupN*
860 arguments may also be strings identifying groups by their group name. If a
861 string argument is not used as a group name in the pattern, an :exc:`IndexError`
862 exception is raised.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000863
Brian Curtinfbe51992010-03-25 23:48:54 +0000864 A moderately complicated example:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000865
Brian Curtinfbe51992010-03-25 23:48:54 +0000866 >>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds")
867 >>> m.group('first_name')
868 'Malcolm'
869 >>> m.group('last_name')
870 'Reynolds'
Georg Brandl8ec7f652007-08-15 14:28:01 +0000871
Brian Curtinfbe51992010-03-25 23:48:54 +0000872 Named groups can also be referred to by their index:
Georg Brandlb8df1562007-12-05 18:30:48 +0000873
Brian Curtinfbe51992010-03-25 23:48:54 +0000874 >>> m.group(1)
875 'Malcolm'
876 >>> m.group(2)
877 'Reynolds'
Georg Brandlb8df1562007-12-05 18:30:48 +0000878
Brian Curtinfbe51992010-03-25 23:48:54 +0000879 If a group matches multiple times, only the last match is accessible:
Georg Brandl6199e322008-03-22 12:04:26 +0000880
Brian Curtinfbe51992010-03-25 23:48:54 +0000881 >>> m = re.match(r"(..)+", "a1b2c3") # Matches 3 times.
882 >>> m.group(1) # Returns only the last match.
883 'c3'
Georg Brandl8ec7f652007-08-15 14:28:01 +0000884
885
Brian Curtinfbe51992010-03-25 23:48:54 +0000886 .. method:: MatchObject.groups([default])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000887
Brian Curtinfbe51992010-03-25 23:48:54 +0000888 Return a tuple containing all the subgroups of the match, from 1 up to however
889 many groups are in the pattern. The *default* argument is used for groups that
890 did not participate in the match; it defaults to ``None``. (Incompatibility
891 note: in the original Python 1.5 release, if the tuple was one element long, a
892 string would be returned instead. In later versions (from 1.5.1 on), a
893 singleton tuple is returned in such cases.)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000894
Brian Curtinfbe51992010-03-25 23:48:54 +0000895 For example:
Georg Brandlb8df1562007-12-05 18:30:48 +0000896
Brian Curtinfbe51992010-03-25 23:48:54 +0000897 >>> m = re.match(r"(\d+)\.(\d+)", "24.1632")
898 >>> m.groups()
899 ('24', '1632')
Georg Brandlb8df1562007-12-05 18:30:48 +0000900
Brian Curtinfbe51992010-03-25 23:48:54 +0000901 If we make the decimal place and everything after it optional, not all groups
902 might participate in the match. These groups will default to ``None`` unless
903 the *default* argument is given:
Georg Brandlb8df1562007-12-05 18:30:48 +0000904
Brian Curtinfbe51992010-03-25 23:48:54 +0000905 >>> m = re.match(r"(\d+)\.?(\d+)?", "24")
906 >>> m.groups() # Second group defaults to None.
907 ('24', None)
908 >>> m.groups('0') # Now, the second group defaults to '0'.
909 ('24', '0')
Georg Brandlb8df1562007-12-05 18:30:48 +0000910
Georg Brandl8ec7f652007-08-15 14:28:01 +0000911
Brian Curtinfbe51992010-03-25 23:48:54 +0000912 .. method:: MatchObject.groupdict([default])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000913
Brian Curtinfbe51992010-03-25 23:48:54 +0000914 Return a dictionary containing all the *named* subgroups of the match, keyed by
915 the subgroup name. The *default* argument is used for groups that did not
916 participate in the match; it defaults to ``None``. For example:
Georg Brandlb8df1562007-12-05 18:30:48 +0000917
Brian Curtinfbe51992010-03-25 23:48:54 +0000918 >>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds")
919 >>> m.groupdict()
920 {'first_name': 'Malcolm', 'last_name': 'Reynolds'}
Georg Brandl8ec7f652007-08-15 14:28:01 +0000921
922
Brian Curtinfbe51992010-03-25 23:48:54 +0000923 .. method:: MatchObject.start([group])
924 MatchObject.end([group])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000925
Brian Curtinfbe51992010-03-25 23:48:54 +0000926 Return the indices of the start and end of the substring matched by *group*;
927 *group* defaults to zero (meaning the whole matched substring). Return ``-1`` if
928 *group* exists but did not contribute to the match. For a match object *m*, and
929 a group *g* that did contribute to the match, the substring matched by group *g*
930 (equivalent to ``m.group(g)``) is ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000931
Brian Curtinfbe51992010-03-25 23:48:54 +0000932 m.string[m.start(g):m.end(g)]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000933
Brian Curtinfbe51992010-03-25 23:48:54 +0000934 Note that ``m.start(group)`` will equal ``m.end(group)`` if *group* matched a
935 null string. For example, after ``m = re.search('b(c?)', 'cba')``,
936 ``m.start(0)`` is 1, ``m.end(0)`` is 2, ``m.start(1)`` and ``m.end(1)`` are both
937 2, and ``m.start(2)`` raises an :exc:`IndexError` exception.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000938
Brian Curtinfbe51992010-03-25 23:48:54 +0000939 An example that will remove *remove_this* from email addresses:
Georg Brandlb8df1562007-12-05 18:30:48 +0000940
Brian Curtinfbe51992010-03-25 23:48:54 +0000941 >>> email = "tony@tiremove_thisger.net"
942 >>> m = re.search("remove_this", email)
943 >>> email[:m.start()] + email[m.end():]
944 'tony@tiger.net'
Georg Brandlb8df1562007-12-05 18:30:48 +0000945
Georg Brandl8ec7f652007-08-15 14:28:01 +0000946
Brian Curtinfbe51992010-03-25 23:48:54 +0000947 .. method:: MatchObject.span([group])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000948
Brian Curtinfbe51992010-03-25 23:48:54 +0000949 For :class:`MatchObject` *m*, return the 2-tuple ``(m.start(group),
950 m.end(group))``. Note that if *group* did not contribute to the match, this is
951 ``(-1, -1)``. *group* defaults to zero, the entire match.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000952
953
Brian Curtinfbe51992010-03-25 23:48:54 +0000954 .. attribute:: MatchObject.pos
Georg Brandl8ec7f652007-08-15 14:28:01 +0000955
Brian Curtinfbe51992010-03-25 23:48:54 +0000956 The value of *pos* which was passed to the :meth:`~RegexObject.search` or
957 :meth:`~RegexObject.match` method of the :class:`RegexObject`. This is the
958 index into the string at which the RE engine started looking for a match.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000959
960
Brian Curtinfbe51992010-03-25 23:48:54 +0000961 .. attribute:: MatchObject.endpos
Georg Brandl8ec7f652007-08-15 14:28:01 +0000962
Brian Curtinfbe51992010-03-25 23:48:54 +0000963 The value of *endpos* which was passed to the :meth:`~RegexObject.search` or
964 :meth:`~RegexObject.match` method of the :class:`RegexObject`. This is the
965 index into the string beyond which the RE engine will not go.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000966
967
Brian Curtinfbe51992010-03-25 23:48:54 +0000968 .. attribute:: MatchObject.lastindex
Georg Brandl8ec7f652007-08-15 14:28:01 +0000969
Brian Curtinfbe51992010-03-25 23:48:54 +0000970 The integer index of the last matched capturing group, or ``None`` if no group
971 was matched at all. For example, the expressions ``(a)b``, ``((a)(b))``, and
972 ``((ab))`` will have ``lastindex == 1`` if applied to the string ``'ab'``, while
973 the expression ``(a)(b)`` will have ``lastindex == 2``, if applied to the same
974 string.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000975
976
Brian Curtinfbe51992010-03-25 23:48:54 +0000977 .. attribute:: MatchObject.lastgroup
Georg Brandl8ec7f652007-08-15 14:28:01 +0000978
Brian Curtinfbe51992010-03-25 23:48:54 +0000979 The name of the last matched capturing group, or ``None`` if the group didn't
980 have a name, or if no group was matched at all.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000981
982
Brian Curtinfbe51992010-03-25 23:48:54 +0000983 .. attribute:: MatchObject.re
Georg Brandl8ec7f652007-08-15 14:28:01 +0000984
Brian Curtinfbe51992010-03-25 23:48:54 +0000985 The regular expression object whose :meth:`~RegexObject.match` or
986 :meth:`~RegexObject.search` method produced this :class:`MatchObject`
987 instance.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000988
989
Brian Curtinfbe51992010-03-25 23:48:54 +0000990 .. attribute:: MatchObject.string
Georg Brandl8ec7f652007-08-15 14:28:01 +0000991
Brian Curtinfbe51992010-03-25 23:48:54 +0000992 The string passed to :meth:`~RegexObject.match` or
993 :meth:`~RegexObject.search`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000994
995
996Examples
997--------
998
Georg Brandlb8df1562007-12-05 18:30:48 +0000999
1000Checking For a Pair
1001^^^^^^^^^^^^^^^^^^^
1002
1003In this example, we'll use the following helper function to display match
Georg Brandl6199e322008-03-22 12:04:26 +00001004objects a little more gracefully:
1005
Georg Brandl838b4b02008-03-22 13:07:06 +00001006.. testcode::
Georg Brandlb8df1562007-12-05 18:30:48 +00001007
1008 def displaymatch(match):
1009 if match is None:
1010 return None
1011 return '<Match: %r, groups=%r>' % (match.group(), match.groups())
1012
1013Suppose you are writing a poker program where a player's hand is represented as
1014a 5-character string with each character representing a card, "a" for ace, "k"
Ezio Melotti13c82d02011-12-17 01:17:17 +02001015for king, "q" for queen, "j" for jack, "t" for 10, and "2" through "9"
Georg Brandlb8df1562007-12-05 18:30:48 +00001016representing the card with that value.
1017
Georg Brandl6199e322008-03-22 12:04:26 +00001018To see if a given string is a valid hand, one could do the following:
Georg Brandlb8df1562007-12-05 18:30:48 +00001019
Ezio Melotti13c82d02011-12-17 01:17:17 +02001020 >>> valid = re.compile(r"^[a2-9tjqk]{5}$")
1021 >>> displaymatch(valid.match("akt5q")) # Valid.
1022 "<Match: 'akt5q', groups=()>"
1023 >>> displaymatch(valid.match("akt5e")) # Invalid.
1024 >>> displaymatch(valid.match("akt")) # Invalid.
Georg Brandlb8df1562007-12-05 18:30:48 +00001025 >>> displaymatch(valid.match("727ak")) # Valid.
Georg Brandl6199e322008-03-22 12:04:26 +00001026 "<Match: '727ak', groups=()>"
Georg Brandlb8df1562007-12-05 18:30:48 +00001027
1028That last hand, ``"727ak"``, contained a pair, or two of the same valued cards.
Georg Brandl6199e322008-03-22 12:04:26 +00001029To match this with a regular expression, one could use backreferences as such:
Georg Brandlb8df1562007-12-05 18:30:48 +00001030
1031 >>> pair = re.compile(r".*(.).*\1")
1032 >>> displaymatch(pair.match("717ak")) # Pair of 7s.
Georg Brandl6199e322008-03-22 12:04:26 +00001033 "<Match: '717', groups=('7',)>"
Georg Brandlb8df1562007-12-05 18:30:48 +00001034 >>> displaymatch(pair.match("718ak")) # No pairs.
1035 >>> displaymatch(pair.match("354aa")) # Pair of aces.
Georg Brandl6199e322008-03-22 12:04:26 +00001036 "<Match: '354aa', groups=('a',)>"
Georg Brandlb8df1562007-12-05 18:30:48 +00001037
Georg Brandl74f8fc02009-07-26 13:36:39 +00001038To find out what card the pair consists of, one could use the
1039:meth:`~MatchObject.group` method of :class:`MatchObject` in the following
1040manner:
Georg Brandl6199e322008-03-22 12:04:26 +00001041
Georg Brandl838b4b02008-03-22 13:07:06 +00001042.. doctest::
Georg Brandlb8df1562007-12-05 18:30:48 +00001043
1044 >>> pair.match("717ak").group(1)
1045 '7'
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001046
Georg Brandlb8df1562007-12-05 18:30:48 +00001047 # Error because re.match() returns None, which doesn't have a group() method:
1048 >>> pair.match("718ak").group(1)
1049 Traceback (most recent call last):
1050 File "<pyshell#23>", line 1, in <module>
1051 re.match(r".*(.).*\1", "718ak").group(1)
1052 AttributeError: 'NoneType' object has no attribute 'group'
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001053
Georg Brandlb8df1562007-12-05 18:30:48 +00001054 >>> pair.match("354aa").group(1)
1055 'a'
1056
1057
1058Simulating scanf()
1059^^^^^^^^^^^^^^^^^^
Georg Brandl8ec7f652007-08-15 14:28:01 +00001060
1061.. index:: single: scanf()
1062
Sandro Tosi98ed08f2012-01-14 16:42:02 +01001063Python does not currently have an equivalent to :c:func:`scanf`. Regular
Georg Brandl8ec7f652007-08-15 14:28:01 +00001064expressions are generally more powerful, though also more verbose, than
Sandro Tosi98ed08f2012-01-14 16:42:02 +01001065:c:func:`scanf` format strings. The table below offers some more-or-less
1066equivalent mappings between :c:func:`scanf` format tokens and regular
Georg Brandl8ec7f652007-08-15 14:28:01 +00001067expressions.
1068
1069+--------------------------------+---------------------------------------------+
Sandro Tosi98ed08f2012-01-14 16:42:02 +01001070| :c:func:`scanf` Token | Regular Expression |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001071+================================+=============================================+
1072| ``%c`` | ``.`` |
1073+--------------------------------+---------------------------------------------+
1074| ``%5c`` | ``.{5}`` |
1075+--------------------------------+---------------------------------------------+
1076| ``%d`` | ``[-+]?\d+`` |
1077+--------------------------------+---------------------------------------------+
1078| ``%e``, ``%E``, ``%f``, ``%g`` | ``[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?`` |
1079+--------------------------------+---------------------------------------------+
1080| ``%i`` | ``[-+]?(0[xX][\dA-Fa-f]+|0[0-7]*|\d+)`` |
1081+--------------------------------+---------------------------------------------+
Ezio Melotti89500192012-04-29 11:47:28 +03001082| ``%o`` | ``[-+]?[0-7]+`` |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001083+--------------------------------+---------------------------------------------+
1084| ``%s`` | ``\S+`` |
1085+--------------------------------+---------------------------------------------+
1086| ``%u`` | ``\d+`` |
1087+--------------------------------+---------------------------------------------+
Ezio Melotti89500192012-04-29 11:47:28 +03001088| ``%x``, ``%X`` | ``[-+]?(0[xX])?[\dA-Fa-f]+`` |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001089+--------------------------------+---------------------------------------------+
1090
1091To extract the filename and numbers from a string like ::
1092
1093 /usr/sbin/sendmail - 0 errors, 4 warnings
1094
Sandro Tosi98ed08f2012-01-14 16:42:02 +01001095you would use a :c:func:`scanf` format like ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001096
1097 %s - %d errors, %d warnings
1098
1099The equivalent regular expression would be ::
1100
1101 (\S+) - (\d+) errors, (\d+) warnings
1102
Georg Brandlb8df1562007-12-05 18:30:48 +00001103
Ezio Melottid9de93e2012-02-29 13:37:07 +02001104.. _search-vs-match:
Georg Brandlb8df1562007-12-05 18:30:48 +00001105
1106search() vs. match()
1107^^^^^^^^^^^^^^^^^^^^
1108
Ezio Melottid9de93e2012-02-29 13:37:07 +02001109.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
Georg Brandlb8df1562007-12-05 18:30:48 +00001110
Ezio Melottid9de93e2012-02-29 13:37:07 +02001111Python offers two different primitive operations based on regular expressions:
1112:func:`re.match` checks for a match only at the beginning of the string, while
1113:func:`re.search` checks for a match anywhere in the string (this is what Perl
1114does by default).
1115
1116For example::
1117
1118 >>> re.match("c", "abcdef") # No match
1119 >>> re.search("c", "abcdef") # Match
Georg Brandl6199e322008-03-22 12:04:26 +00001120 <_sre.SRE_Match object at ...>
Georg Brandlb8df1562007-12-05 18:30:48 +00001121
Ezio Melottid9de93e2012-02-29 13:37:07 +02001122Regular expressions beginning with ``'^'`` can be used with :func:`search` to
1123restrict the match at the beginning of the string::
Georg Brandlb8df1562007-12-05 18:30:48 +00001124
Ezio Melottid9de93e2012-02-29 13:37:07 +02001125 >>> re.match("c", "abcdef") # No match
1126 >>> re.search("^c", "abcdef") # No match
1127 >>> re.search("^a", "abcdef") # Match
Georg Brandl6199e322008-03-22 12:04:26 +00001128 <_sre.SRE_Match object at ...>
Ezio Melottid9de93e2012-02-29 13:37:07 +02001129
1130Note however that in :const:`MULTILINE` mode :func:`match` only matches at the
1131beginning of the string, whereas using :func:`search` with a regular expression
1132beginning with ``'^'`` will match at the beginning of each line.
1133
1134 >>> re.match('X', 'A\nB\nX', re.MULTILINE) # No match
1135 >>> re.search('^X', 'A\nB\nX', re.MULTILINE) # Match
1136 <_sre.SRE_Match object at ...>
Georg Brandlb8df1562007-12-05 18:30:48 +00001137
1138
1139Making a Phonebook
1140^^^^^^^^^^^^^^^^^^
1141
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001142:func:`split` splits a string into a list delimited by the passed pattern. The
Georg Brandlb8df1562007-12-05 18:30:48 +00001143method is invaluable for converting textual data into data structures that can be
1144easily read and modified by Python as demonstrated in the following example that
1145creates a phonebook.
1146
Georg Brandld6b20dc2007-12-06 09:45:39 +00001147First, here is the input. Normally it may come from a file, here we are using
Georg Brandl6199e322008-03-22 12:04:26 +00001148triple-quoted string syntax:
Georg Brandlb8df1562007-12-05 18:30:48 +00001149
Georg Brandl5a607b02012-03-17 17:26:27 +01001150 >>> text = """Ross McFluff: 834.345.1254 155 Elm Street
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001151 ...
Georg Brandl6199e322008-03-22 12:04:26 +00001152 ... Ronald Heathmore: 892.345.3428 436 Finley Avenue
1153 ... Frank Burger: 925.541.7625 662 South Dogwood Way
1154 ...
1155 ...
1156 ... Heather Albrecht: 548.326.4584 919 Park Place"""
Georg Brandld6b20dc2007-12-06 09:45:39 +00001157
1158The entries are separated by one or more newlines. Now we convert the string
Georg Brandl6199e322008-03-22 12:04:26 +00001159into a list with each nonempty line having its own entry:
1160
Georg Brandl838b4b02008-03-22 13:07:06 +00001161.. doctest::
Georg Brandl6199e322008-03-22 12:04:26 +00001162 :options: +NORMALIZE_WHITESPACE
Georg Brandld6b20dc2007-12-06 09:45:39 +00001163
Georg Brandl5a607b02012-03-17 17:26:27 +01001164 >>> entries = re.split("\n+", text)
Georg Brandlb8df1562007-12-05 18:30:48 +00001165 >>> entries
Georg Brandl6199e322008-03-22 12:04:26 +00001166 ['Ross McFluff: 834.345.1254 155 Elm Street',
1167 'Ronald Heathmore: 892.345.3428 436 Finley Avenue',
1168 'Frank Burger: 925.541.7625 662 South Dogwood Way',
1169 'Heather Albrecht: 548.326.4584 919 Park Place']
Georg Brandlb8df1562007-12-05 18:30:48 +00001170
1171Finally, split each entry into a list with first name, last name, telephone
Georg Brandl907a7202008-02-22 12:31:45 +00001172number, and address. We use the ``maxsplit`` parameter of :func:`split`
Georg Brandl6199e322008-03-22 12:04:26 +00001173because the address has spaces, our splitting pattern, in it:
1174
Georg Brandl838b4b02008-03-22 13:07:06 +00001175.. doctest::
Georg Brandl6199e322008-03-22 12:04:26 +00001176 :options: +NORMALIZE_WHITESPACE
Georg Brandlb8df1562007-12-05 18:30:48 +00001177
Georg Brandld6b20dc2007-12-06 09:45:39 +00001178 >>> [re.split(":? ", entry, 3) for entry in entries]
Georg Brandlb8df1562007-12-05 18:30:48 +00001179 [['Ross', 'McFluff', '834.345.1254', '155 Elm Street'],
1180 ['Ronald', 'Heathmore', '892.345.3428', '436 Finley Avenue'],
1181 ['Frank', 'Burger', '925.541.7625', '662 South Dogwood Way'],
1182 ['Heather', 'Albrecht', '548.326.4584', '919 Park Place']]
1183
Georg Brandld6b20dc2007-12-06 09:45:39 +00001184The ``:?`` pattern matches the colon after the last name, so that it does not
Georg Brandl907a7202008-02-22 12:31:45 +00001185occur in the result list. With a ``maxsplit`` of ``4``, we could separate the
Georg Brandl6199e322008-03-22 12:04:26 +00001186house number from the street name:
1187
Georg Brandl838b4b02008-03-22 13:07:06 +00001188.. doctest::
Georg Brandl6199e322008-03-22 12:04:26 +00001189 :options: +NORMALIZE_WHITESPACE
Georg Brandlb8df1562007-12-05 18:30:48 +00001190
Georg Brandld6b20dc2007-12-06 09:45:39 +00001191 >>> [re.split(":? ", entry, 4) for entry in entries]
Georg Brandlb8df1562007-12-05 18:30:48 +00001192 [['Ross', 'McFluff', '834.345.1254', '155', 'Elm Street'],
1193 ['Ronald', 'Heathmore', '892.345.3428', '436', 'Finley Avenue'],
1194 ['Frank', 'Burger', '925.541.7625', '662', 'South Dogwood Way'],
1195 ['Heather', 'Albrecht', '548.326.4584', '919', 'Park Place']]
1196
1197
1198Text Munging
1199^^^^^^^^^^^^
1200
1201:func:`sub` replaces every occurrence of a pattern with a string or the
1202result of a function. This example demonstrates using :func:`sub` with
1203a function to "munge" text, or randomize the order of all the characters
1204in each word of a sentence except for the first and last characters::
1205
1206 >>> def repl(m):
1207 ... inner_word = list(m.group(2))
1208 ... random.shuffle(inner_word)
1209 ... return m.group(1) + "".join(inner_word) + m.group(3)
1210 >>> text = "Professor Abdolmalek, please report your absences promptly."
Georg Brandle0289a32010-08-01 21:44:38 +00001211 >>> re.sub(r"(\w)(\w+)(\w)", repl, text)
Georg Brandlb8df1562007-12-05 18:30:48 +00001212 'Poefsrosr Aealmlobdk, pslaee reorpt your abnseces plmrptoy.'
Georg Brandle0289a32010-08-01 21:44:38 +00001213 >>> re.sub(r"(\w)(\w+)(\w)", repl, text)
Georg Brandlb8df1562007-12-05 18:30:48 +00001214 'Pofsroser Aodlambelk, plasee reoprt yuor asnebces potlmrpy.'
1215
1216
1217Finding all Adverbs
1218^^^^^^^^^^^^^^^^^^^
1219
Georg Brandl907a7202008-02-22 12:31:45 +00001220:func:`findall` matches *all* occurrences of a pattern, not just the first
Georg Brandlb8df1562007-12-05 18:30:48 +00001221one as :func:`search` does. For example, if one was a writer and wanted to
1222find all of the adverbs in some text, he or she might use :func:`findall` in
Georg Brandl6199e322008-03-22 12:04:26 +00001223the following manner:
Georg Brandlb8df1562007-12-05 18:30:48 +00001224
1225 >>> text = "He was carefully disguised but captured quickly by police."
1226 >>> re.findall(r"\w+ly", text)
1227 ['carefully', 'quickly']
1228
1229
1230Finding all Adverbs and their Positions
1231^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1232
1233If one wants more information about all matches of a pattern than the matched
1234text, :func:`finditer` is useful as it provides instances of
1235:class:`MatchObject` instead of strings. Continuing with the previous example,
1236if one was a writer who wanted to find all of the adverbs *and their positions*
Georg Brandl6199e322008-03-22 12:04:26 +00001237in some text, he or she would use :func:`finditer` in the following manner:
Georg Brandlb8df1562007-12-05 18:30:48 +00001238
1239 >>> text = "He was carefully disguised but captured quickly by police."
1240 >>> for m in re.finditer(r"\w+ly", text):
Georg Brandl6199e322008-03-22 12:04:26 +00001241 ... print '%02d-%02d: %s' % (m.start(), m.end(), m.group(0))
Georg Brandlb8df1562007-12-05 18:30:48 +00001242 07-16: carefully
1243 40-47: quickly
1244
1245
1246Raw String Notation
1247^^^^^^^^^^^^^^^^^^^
1248
1249Raw string notation (``r"text"``) keeps regular expressions sane. Without it,
1250every backslash (``'\'``) in a regular expression would have to be prefixed with
1251another one to escape it. For example, the two following lines of code are
Georg Brandl6199e322008-03-22 12:04:26 +00001252functionally identical:
Georg Brandlb8df1562007-12-05 18:30:48 +00001253
1254 >>> re.match(r"\W(.)\1\W", " ff ")
Georg Brandl6199e322008-03-22 12:04:26 +00001255 <_sre.SRE_Match object at ...>
Georg Brandlb8df1562007-12-05 18:30:48 +00001256 >>> re.match("\\W(.)\\1\\W", " ff ")
Georg Brandl6199e322008-03-22 12:04:26 +00001257 <_sre.SRE_Match object at ...>
Georg Brandlb8df1562007-12-05 18:30:48 +00001258
1259When one wants to match a literal backslash, it must be escaped in the regular
1260expression. With raw string notation, this means ``r"\\"``. Without raw string
1261notation, one must use ``"\\\\"``, making the following lines of code
Georg Brandl6199e322008-03-22 12:04:26 +00001262functionally identical:
Georg Brandlb8df1562007-12-05 18:30:48 +00001263
1264 >>> re.match(r"\\", r"\\")
Georg Brandl6199e322008-03-22 12:04:26 +00001265 <_sre.SRE_Match object at ...>
Georg Brandlb8df1562007-12-05 18:30:48 +00001266 >>> re.match("\\\\", r"\\")
Georg Brandl6199e322008-03-22 12:04:26 +00001267 <_sre.SRE_Match object at ...>