blob: 307bc7e188b01f56c4d1a5b5a4e23f42875b6c45 [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.. seealso::
37
38 Mastering Regular Expressions
39 Book on regular expressions by Jeffrey Friedl, published by O'Reilly. The
Georg Brandlba2e5192007-09-27 06:26:58 +000040 second edition of the book no longer covers Python at all, but the first
Georg Brandl8ec7f652007-08-15 14:28:01 +000041 edition covered writing good regular expression patterns in great detail.
42
43
44.. _re-syntax:
45
46Regular Expression Syntax
47-------------------------
48
49A regular expression (or RE) specifies a set of strings that matches it; the
50functions in this module let you check if a particular string matches a given
51regular expression (or if a given regular expression matches a particular
52string, which comes down to the same thing).
53
54Regular expressions can be concatenated to form new regular expressions; if *A*
55and *B* are both regular expressions, then *AB* is also a regular expression.
56In general, if a string *p* matches *A* and another string *q* matches *B*, the
57string *pq* will match AB. This holds unless *A* or *B* contain low precedence
58operations; boundary conditions between *A* and *B*; or have numbered group
59references. Thus, complex expressions can easily be constructed from simpler
60primitive expressions like the ones described here. For details of the theory
61and implementation of regular expressions, consult the Friedl book referenced
62above, or almost any textbook about compiler construction.
63
64A brief explanation of the format of regular expressions follows. For further
Georg Brandl1cf05222008-02-05 12:01:24 +000065information and a gentler presentation, consult the :ref:`regex-howto`.
Georg Brandl8ec7f652007-08-15 14:28:01 +000066
67Regular expressions can contain both special and ordinary characters. Most
68ordinary characters, like ``'A'``, ``'a'``, or ``'0'``, are the simplest regular
69expressions; they simply match themselves. You can concatenate ordinary
70characters, so ``last`` matches the string ``'last'``. (In the rest of this
71section, we'll write RE's in ``this special style``, usually without quotes, and
72strings to be matched ``'in single quotes'``.)
73
74Some characters, like ``'|'`` or ``'('``, are special. Special
75characters either stand for classes of ordinary characters, or affect
76how the regular expressions around them are interpreted. Regular
77expression pattern strings may not contain null bytes, but can specify
78the null byte using the ``\number`` notation, e.g., ``'\x00'``.
79
80
81The special characters are:
82
Georg Brandl8ec7f652007-08-15 14:28:01 +000083``'.'``
84 (Dot.) In the default mode, this matches any character except a newline. If
85 the :const:`DOTALL` flag has been specified, this matches any character
86 including a newline.
87
88``'^'``
89 (Caret.) Matches the start of the string, and in :const:`MULTILINE` mode also
90 matches immediately after each newline.
91
92``'$'``
93 Matches the end of the string or just before the newline at the end of the
94 string, and in :const:`MULTILINE` mode also matches before a newline. ``foo``
95 matches both 'foo' and 'foobar', while the regular expression ``foo$`` matches
96 only 'foo'. More interestingly, searching for ``foo.$`` in ``'foo1\nfoo2\n'``
Amaury Forgeot d'Arcd08a8eb2008-01-10 21:59:42 +000097 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.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000100
101``'*'``
102 Causes the resulting RE to match 0 or more repetitions of the preceding RE, as
103 many repetitions as are possible. ``ab*`` will match 'a', 'ab', or 'a' followed
104 by any number of 'b's.
105
106``'+'``
107 Causes the resulting RE to match 1 or more repetitions of the preceding RE.
108 ``ab+`` will match 'a' followed by any non-zero number of 'b's; it will not
109 match just 'a'.
110
111``'?'``
112 Causes the resulting RE to match 0 or 1 repetitions of the preceding RE.
113 ``ab?`` will match either 'a' or 'ab'.
114
115``*?``, ``+?``, ``??``
116 The ``'*'``, ``'+'``, and ``'?'`` qualifiers are all :dfn:`greedy`; they match
117 as much text as possible. Sometimes this behaviour isn't desired; if the RE
118 ``<.*>`` is matched against ``'<H1>title</H1>'``, it will match the entire
119 string, and not just ``'<H1>'``. Adding ``'?'`` after the qualifier makes it
120 perform the match in :dfn:`non-greedy` or :dfn:`minimal` fashion; as *few*
121 characters as possible will be matched. Using ``.*?`` in the previous
122 expression will match only ``'<H1>'``.
123
124``{m}``
125 Specifies that exactly *m* copies of the previous RE should be matched; fewer
126 matches cause the entire RE not to match. For example, ``a{6}`` will match
127 exactly six ``'a'`` characters, but not five.
128
129``{m,n}``
130 Causes the resulting RE to match from *m* to *n* repetitions of the preceding
131 RE, attempting to match as many repetitions as possible. For example,
132 ``a{3,5}`` will match from 3 to 5 ``'a'`` characters. Omitting *m* specifies a
133 lower bound of zero, and omitting *n* specifies an infinite upper bound. As an
134 example, ``a{4,}b`` will match ``aaaab`` or a thousand ``'a'`` characters
135 followed by a ``b``, but not ``aaab``. The comma may not be omitted or the
136 modifier would be confused with the previously described form.
137
138``{m,n}?``
139 Causes the resulting RE to match from *m* to *n* repetitions of the preceding
140 RE, attempting to match as *few* repetitions as possible. This is the
141 non-greedy version of the previous qualifier. For example, on the
142 6-character string ``'aaaaaa'``, ``a{3,5}`` will match 5 ``'a'`` characters,
143 while ``a{3,5}?`` will only match 3 characters.
144
145``'\'``
146 Either escapes special characters (permitting you to match characters like
147 ``'*'``, ``'?'``, and so forth), or signals a special sequence; special
148 sequences are discussed below.
149
150 If you're not using a raw string to express the pattern, remember that Python
151 also uses the backslash as an escape sequence in string literals; if the escape
152 sequence isn't recognized by Python's parser, the backslash and subsequent
153 character are included in the resulting string. However, if Python would
154 recognize the resulting sequence, the backslash should be repeated twice. This
155 is complicated and hard to understand, so it's highly recommended that you use
156 raw strings for all but the simplest expressions.
157
158``[]``
Ezio Melottia1958732011-10-20 19:31:08 +0300159 Used to indicate a set of characters. In a set:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000160
Ezio Melottia1958732011-10-20 19:31:08 +0300161 * Characters can be listed individually, e.g. ``[amk]`` will match ``'a'``,
162 ``'m'``, or ``'k'``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000163
Ezio Melottia1958732011-10-20 19:31:08 +0300164 * Ranges of characters can be indicated by giving two characters and separating
165 them by a ``'-'``, for example ``[a-z]`` will match any lowercase ASCII letter,
166 ``[0-5][0-9]`` will match all the two-digits numbers from ``00`` to ``59``, and
167 ``[0-9A-Fa-f]`` will match any hexadecimal digit. If ``-`` is escaped (e.g.
168 ``[a\-z]``) or if it's placed as the first or last character (e.g. ``[a-]``),
169 it will match a literal ``'-'``.
170
171 * Special characters lose their special meaning inside sets. For example,
172 ``[(+*)]`` will match any of the literal characters ``'('``, ``'+'``,
173 ``'*'``, or ``')'``.
174
175 * Character classes such as ``\w`` or ``\S`` (defined below) are also accepted
176 inside a set, although the characters they match depends on whether
177 :const:`LOCALE` or :const:`UNICODE` mode is in force.
178
179 * Characters that are not within a range can be matched by :dfn:`complementing`
180 the set. If the first character of the set is ``'^'``, all the characters
181 that are *not* in the set will be matched. For example, ``[^5]`` will match
182 any character except ``'5'``, and ``[^^]`` will match any character except
183 ``'^'``. ``^`` has no special meaning if it's not the first character in
184 the set.
185
186 * To match a literal ``']'`` inside a set, precede it with a backslash, or
187 place it at the beginning of the set. For example, both ``[()[\]{}]`` and
188 ``[]()[{}]`` will both match a parenthesis.
Mark Summerfield700a6352008-05-31 13:05:34 +0000189
Georg Brandl8ec7f652007-08-15 14:28:01 +0000190``'|'``
191 ``A|B``, where A and B can be arbitrary REs, creates a regular expression that
192 will match either A or B. An arbitrary number of REs can be separated by the
193 ``'|'`` in this way. This can be used inside groups (see below) as well. As
194 the target string is scanned, REs separated by ``'|'`` are tried from left to
195 right. When one pattern completely matches, that branch is accepted. This means
196 that once ``A`` matches, ``B`` will not be tested further, even if it would
197 produce a longer overall match. In other words, the ``'|'`` operator is never
198 greedy. To match a literal ``'|'``, use ``\|``, or enclose it inside a
199 character class, as in ``[|]``.
200
201``(...)``
202 Matches whatever regular expression is inside the parentheses, and indicates the
203 start and end of a group; the contents of a group can be retrieved after a match
204 has been performed, and can be matched later in the string with the ``\number``
205 special sequence, described below. To match the literals ``'('`` or ``')'``,
206 use ``\(`` or ``\)``, or enclose them inside a character class: ``[(] [)]``.
207
208``(?...)``
209 This is an extension notation (a ``'?'`` following a ``'('`` is not meaningful
210 otherwise). The first character after the ``'?'`` determines what the meaning
211 and further syntax of the construct is. Extensions usually do not create a new
212 group; ``(?P<name>...)`` is the only exception to this rule. Following are the
213 currently supported extensions.
214
215``(?iLmsux)``
216 (One or more letters from the set ``'i'``, ``'L'``, ``'m'``, ``'s'``,
217 ``'u'``, ``'x'``.) The group matches the empty string; the letters
218 set the corresponding flags: :const:`re.I` (ignore case),
219 :const:`re.L` (locale dependent), :const:`re.M` (multi-line),
220 :const:`re.S` (dot matches all), :const:`re.U` (Unicode dependent),
221 and :const:`re.X` (verbose), for the entire regular expression. (The
222 flags are described in :ref:`contents-of-module-re`.) This
223 is useful if you wish to include the flags as part of the regular
224 expression, instead of passing a *flag* argument to the
Georg Brandl74f8fc02009-07-26 13:36:39 +0000225 :func:`re.compile` function.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000226
227 Note that the ``(?x)`` flag changes how the expression is parsed. It should be
228 used first in the expression string, or after one or more whitespace characters.
229 If there are non-whitespace characters before the flag, the results are
230 undefined.
231
232``(?:...)``
Georg Brandl3b85b9b2010-11-26 08:20:18 +0000233 A non-capturing version of regular parentheses. Matches whatever regular
Georg Brandl8ec7f652007-08-15 14:28:01 +0000234 expression is inside the parentheses, but the substring matched by the group
235 *cannot* be retrieved after performing a match or referenced later in the
236 pattern.
237
238``(?P<name>...)``
239 Similar to regular parentheses, but the substring matched by the group is
Georg Brandl52060862009-03-31 19:06:57 +0000240 accessible within the rest of the regular expression via the symbolic group
241 name *name*. Group names must be valid Python identifiers, and each group
242 name must be defined only once within a regular expression. A symbolic group
243 is also a numbered group, just as if the group were not named. So the group
244 named ``id`` in the example below can also be referenced as the numbered group
245 ``1``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000246
247 For example, if the pattern is ``(?P<id>[a-zA-Z_]\w*)``, the group can be
248 referenced by its name in arguments to methods of match objects, such as
Georg Brandl52060862009-03-31 19:06:57 +0000249 ``m.group('id')`` or ``m.end('id')``, and also by name in the regular
250 expression itself (using ``(?P=id)``) and replacement text given to
251 ``.sub()`` (using ``\g<id>``).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000252
253``(?P=name)``
254 Matches whatever text was matched by the earlier group named *name*.
255
256``(?#...)``
257 A comment; the contents of the parentheses are simply ignored.
258
259``(?=...)``
260 Matches if ``...`` matches next, but doesn't consume any of the string. This is
261 called a lookahead assertion. For example, ``Isaac (?=Asimov)`` will match
262 ``'Isaac '`` only if it's followed by ``'Asimov'``.
263
264``(?!...)``
265 Matches if ``...`` doesn't match next. This is a negative lookahead assertion.
266 For example, ``Isaac (?!Asimov)`` will match ``'Isaac '`` only if it's *not*
267 followed by ``'Asimov'``.
268
269``(?<=...)``
270 Matches if the current position in the string is preceded by a match for ``...``
271 that ends at the current position. This is called a :dfn:`positive lookbehind
272 assertion`. ``(?<=abc)def`` will find a match in ``abcdef``, since the
273 lookbehind will back up 3 characters and check if the contained pattern matches.
274 The contained pattern must only match strings of some fixed length, meaning that
275 ``abc`` or ``a|b`` are allowed, but ``a*`` and ``a{3,4}`` are not. Note that
276 patterns which start with positive lookbehind assertions will never match at the
277 beginning of the string being searched; you will most likely want to use the
Georg Brandl6199e322008-03-22 12:04:26 +0000278 :func:`search` function rather than the :func:`match` function:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000279
280 >>> import re
281 >>> m = re.search('(?<=abc)def', 'abcdef')
282 >>> m.group(0)
283 'def'
284
Georg Brandl6199e322008-03-22 12:04:26 +0000285 This example looks for a word following a hyphen:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000286
287 >>> m = re.search('(?<=-)\w+', 'spam-egg')
288 >>> m.group(0)
289 'egg'
290
291``(?<!...)``
292 Matches if the current position in the string is not preceded by a match for
293 ``...``. This is called a :dfn:`negative lookbehind assertion`. Similar to
294 positive lookbehind assertions, the contained pattern must only match strings of
295 some fixed length. Patterns which start with negative lookbehind assertions may
296 match at the beginning of the string being searched.
297
298``(?(id/name)yes-pattern|no-pattern)``
299 Will try to match with ``yes-pattern`` if the group with given *id* or *name*
300 exists, and with ``no-pattern`` if it doesn't. ``no-pattern`` is optional and
301 can be omitted. For example, ``(<)?(\w+@\w+(?:\.\w+)+)(?(1)>)`` is a poor email
302 matching pattern, which will match with ``'<user@host.com>'`` as well as
303 ``'user@host.com'``, but not with ``'<user@host.com'``.
304
305 .. versionadded:: 2.4
306
307The special sequences consist of ``'\'`` and a character from the list below.
308If the ordinary character is not on the list, then the resulting RE will match
309the second character. For example, ``\$`` matches the character ``'$'``.
310
Georg Brandl8ec7f652007-08-15 14:28:01 +0000311``\number``
312 Matches the contents of the group of the same number. Groups are numbered
313 starting from 1. For example, ``(.+) \1`` matches ``'the the'`` or ``'55 55'``,
314 but not ``'the end'`` (note the space after the group). This special sequence
315 can only be used to match one of the first 99 groups. If the first digit of
316 *number* is 0, or *number* is 3 octal digits long, it will not be interpreted as
317 a group match, but as the character with octal value *number*. Inside the
318 ``'['`` and ``']'`` of a character class, all numeric escapes are treated as
319 characters.
320
321``\A``
322 Matches only at the start of the string.
323
324``\b``
325 Matches the empty string, but only at the beginning or end of a word. A word is
326 defined as a sequence of alphanumeric or underscore characters, so the end of a
327 word is indicated by whitespace or a non-alphanumeric, non-underscore character.
Eric Smith368ede82010-05-09 14:04:59 +0000328 Note that ``\b`` is defined as the boundary between ``\w`` and ``\W``, so the
Georg Brandl8ec7f652007-08-15 14:28:01 +0000329 precise set of characters deemed to be alphanumeric depends on the values of the
330 ``UNICODE`` and ``LOCALE`` flags. Inside a character range, ``\b`` represents
331 the backspace character, for compatibility with Python's string literals.
332
333``\B``
334 Matches the empty string, but only when it is *not* at the beginning or end of a
335 word. This is just the opposite of ``\b``, so is also subject to the settings
336 of ``LOCALE`` and ``UNICODE``.
337
338``\d``
339 When the :const:`UNICODE` flag is not specified, matches any decimal digit; this
340 is equivalent to the set ``[0-9]``. With :const:`UNICODE`, it will match
Mark Dickinsonfe67bd92009-07-28 20:35:03 +0000341 whatever is classified as a decimal digit in the Unicode character properties
342 database.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000343
344``\D``
345 When the :const:`UNICODE` flag is not specified, matches any non-digit
346 character; this is equivalent to the set ``[^0-9]``. With :const:`UNICODE`, it
347 will match anything other than character marked as digits in the Unicode
348 character properties database.
349
350``\s``
351 When the :const:`LOCALE` and :const:`UNICODE` flags are not specified, matches
352 any whitespace character; this is equivalent to the set ``[ \t\n\r\f\v]``. With
353 :const:`LOCALE`, it will match this set plus whatever characters are defined as
354 space for the current locale. If :const:`UNICODE` is set, this will match the
355 characters ``[ \t\n\r\f\v]`` plus whatever is classified as space in the Unicode
356 character properties database.
357
358``\S``
359 When the :const:`LOCALE` and :const:`UNICODE` flags are not specified, matches
360 any non-whitespace character; this is equivalent to the set ``[^ \t\n\r\f\v]``
361 With :const:`LOCALE`, it will match any character not in this set, and not
362 defined as space in the current locale. If :const:`UNICODE` is set, this will
363 match anything other than ``[ \t\n\r\f\v]`` and characters marked as space in
364 the Unicode character properties database.
365
366``\w``
367 When the :const:`LOCALE` and :const:`UNICODE` flags are not specified, matches
368 any alphanumeric character and the underscore; this is equivalent to the set
369 ``[a-zA-Z0-9_]``. With :const:`LOCALE`, it will match the set ``[0-9_]`` plus
370 whatever characters are defined as alphanumeric for the current locale. If
371 :const:`UNICODE` is set, this will match the characters ``[0-9_]`` plus whatever
372 is classified as alphanumeric in the Unicode character properties database.
373
374``\W``
375 When the :const:`LOCALE` and :const:`UNICODE` flags are not specified, matches
376 any non-alphanumeric character; this is equivalent to the set ``[^a-zA-Z0-9_]``.
377 With :const:`LOCALE`, it will match any character not in the set ``[0-9_]``, and
378 not defined as alphanumeric for the current locale. If :const:`UNICODE` is set,
379 this will match anything other than ``[0-9_]`` and characters marked as
380 alphanumeric in the Unicode character properties database.
381
382``\Z``
383 Matches only at the end of the string.
384
385Most of the standard escapes supported by Python string literals are also
386accepted by the regular expression parser::
387
388 \a \b \f \n
389 \r \t \v \x
390 \\
391
392Octal escapes are included in a limited form: If the first digit is a 0, or if
393there are three octal digits, it is considered an octal escape. Otherwise, it is
394a group reference. As for string literals, octal escapes are always at most
395three digits in length.
396
Georg Brandl8ec7f652007-08-15 14:28:01 +0000397
398.. _matching-searching:
399
400Matching vs Searching
401---------------------
402
403.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
404
405
406Python offers two different primitive operations based on regular expressions:
Georg Brandl604c1212007-08-23 21:36:05 +0000407**match** checks for a match only at the beginning of the string, while
408**search** checks for a match anywhere in the string (this is what Perl does
409by default).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000410
Georg Brandl604c1212007-08-23 21:36:05 +0000411Note that match may differ from search even when using a regular expression
412beginning with ``'^'``: ``'^'`` matches only at the start of the string, or in
Georg Brandl8ec7f652007-08-15 14:28:01 +0000413:const:`MULTILINE` mode also immediately following a newline. The "match"
414operation succeeds only if the pattern matches at the start of the string
415regardless of mode, or at the starting position given by the optional *pos*
Georg Brandl6199e322008-03-22 12:04:26 +0000416argument regardless of whether a newline precedes it.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000417
Georg Brandl6199e322008-03-22 12:04:26 +0000418 >>> re.match("c", "abcdef") # No match
419 >>> re.search("c", "abcdef") # Match
420 <_sre.SRE_Match object at ...>
Georg Brandl8ec7f652007-08-15 14:28:01 +0000421
422
423.. _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
437 can be used for matching using its :func:`match` and :func:`search` methods,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000438 described below.
439
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
465.. data:: I
466 IGNORECASE
467
468 Perform case-insensitive matching; expressions like ``[A-Z]`` will match
469 lowercase letters, too. This is not affected by the current locale.
470
471
472.. data:: L
473 LOCALE
474
Georg Brandlba2e5192007-09-27 06:26:58 +0000475 Make ``\w``, ``\W``, ``\b``, ``\B``, ``\s`` and ``\S`` dependent on the
476 current locale.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000477
478
479.. data:: M
480 MULTILINE
481
482 When specified, the pattern character ``'^'`` matches at the beginning of the
483 string and at the beginning of each line (immediately following each newline);
484 and the pattern character ``'$'`` matches at the end of the string and at the
485 end of each line (immediately preceding each newline). By default, ``'^'``
486 matches only at the beginning of the string, and ``'$'`` only at the end of the
487 string and immediately before the newline (if any) at the end of the string.
488
489
490.. data:: S
491 DOTALL
492
493 Make the ``'.'`` special character match any character at all, including a
494 newline; without this flag, ``'.'`` will match anything *except* a newline.
495
496
497.. data:: U
498 UNICODE
499
500 Make ``\w``, ``\W``, ``\b``, ``\B``, ``\d``, ``\D``, ``\s`` and ``\S`` dependent
501 on the Unicode character properties database.
502
503 .. versionadded:: 2.0
504
505
506.. data:: X
507 VERBOSE
508
509 This flag allows you to write regular expressions that look nicer. Whitespace
510 within the pattern is ignored, except when in a character class or preceded by
511 an unescaped backslash, and, when a line contains a ``'#'`` neither in a
512 character class or preceded by an unescaped backslash, all characters from the
513 leftmost such ``'#'`` through the end of the line are ignored.
514
Georg Brandlb8df1562007-12-05 18:30:48 +0000515 That means that the two following regular expression objects that match a
516 decimal number are functionally equal::
517
518 a = re.compile(r"""\d + # the integral part
519 \. # the decimal point
520 \d * # some fractional digits""", re.X)
521 b = re.compile(r"\d+\.\d*")
Georg Brandl8ec7f652007-08-15 14:28:01 +0000522
523
Eli Benderskyeb711382011-11-14 01:02:20 +0200524.. function:: search(pattern, string, flags=0)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000525
526 Scan through *string* looking for a location where the regular expression
527 *pattern* produces a match, and return a corresponding :class:`MatchObject`
528 instance. Return ``None`` if no position in the string matches the pattern; note
529 that this is different from finding a zero-length match at some point in the
530 string.
531
532
Eli Benderskyeb711382011-11-14 01:02:20 +0200533.. function:: match(pattern, string, flags=0)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000534
535 If zero or more characters at the beginning of *string* match the regular
536 expression *pattern*, return a corresponding :class:`MatchObject` instance.
537 Return ``None`` if the string does not match the pattern; note that this is
538 different from a zero-length match.
539
540 .. note::
541
Georg Brandl74f8fc02009-07-26 13:36:39 +0000542 If you want to locate a match anywhere in *string*, use :func:`search`
Georg Brandlb8df1562007-12-05 18:30:48 +0000543 instead.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000544
545
Eli Benderskyeb711382011-11-14 01:02:20 +0200546.. function:: split(pattern, string, maxsplit=0, flags=0)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000547
548 Split *string* by the occurrences of *pattern*. If capturing parentheses are
549 used in *pattern*, then the text of all groups in the pattern are also returned
550 as part of the resulting list. If *maxsplit* is nonzero, at most *maxsplit*
551 splits occur, and the remainder of the string is returned as the final element
552 of the list. (Incompatibility note: in the original Python 1.5 release,
Georg Brandl6199e322008-03-22 12:04:26 +0000553 *maxsplit* was ignored. This has been fixed in later releases.)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000554
555 >>> re.split('\W+', 'Words, words, words.')
556 ['Words', 'words', 'words', '']
557 >>> re.split('(\W+)', 'Words, words, words.')
558 ['Words', ', ', 'words', ', ', 'words', '.', '']
559 >>> re.split('\W+', 'Words, words, words.', 1)
560 ['Words', 'words, words.']
Gregory P. Smithae91d092009-03-02 05:13:57 +0000561 >>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
562 ['0', '3', '9']
Georg Brandl8ec7f652007-08-15 14:28:01 +0000563
Georg Brandl70992c32008-03-06 07:19:15 +0000564 If there are capturing groups in the separator and it matches at the start of
565 the string, the result will start with an empty string. The same holds for
Georg Brandl6199e322008-03-22 12:04:26 +0000566 the end of the string:
Georg Brandl70992c32008-03-06 07:19:15 +0000567
568 >>> re.split('(\W+)', '...words, words...')
569 ['', '...', 'words', ', ', 'words', '...', '']
570
571 That way, separator components are always found at the same relative
572 indices within the result list (e.g., if there's one capturing group
573 in the separator, the 0th, the 2nd and so forth).
574
Skip Montanaro222907d2007-09-01 17:40:03 +0000575 Note that *split* will never split a string on an empty pattern match.
Georg Brandl6199e322008-03-22 12:04:26 +0000576 For example:
Skip Montanaro222907d2007-09-01 17:40:03 +0000577
578 >>> re.split('x*', 'foo')
579 ['foo']
580 >>> re.split("(?m)^$", "foo\n\nbar\n")
581 ['foo\n\nbar\n']
Georg Brandl8ec7f652007-08-15 14:28:01 +0000582
Ezio Melotti1e5d3182010-11-26 09:30:44 +0000583 .. versionchanged:: 2.7
Gregory P. Smithae91d092009-03-02 05:13:57 +0000584 Added the optional flags argument.
585
Georg Brandl70992c32008-03-06 07:19:15 +0000586
Eli Benderskyeb711382011-11-14 01:02:20 +0200587.. function:: findall(pattern, string, flags=0)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000588
Georg Brandlba2e5192007-09-27 06:26:58 +0000589 Return all non-overlapping matches of *pattern* in *string*, as a list of
Georg Brandlb46d6ff2008-07-19 13:48:44 +0000590 strings. The *string* is scanned left-to-right, and matches are returned in
591 the order found. If one or more groups are present in the pattern, return a
592 list of groups; this will be a list of tuples if the pattern has more than
593 one group. Empty matches are included in the result unless they touch the
594 beginning of another match.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000595
596 .. versionadded:: 1.5.2
597
598 .. versionchanged:: 2.4
599 Added the optional flags argument.
600
601
Eli Benderskyeb711382011-11-14 01:02:20 +0200602.. function:: finditer(pattern, string, flags=0)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000603
Georg Brandle7a09902007-10-21 12:10:28 +0000604 Return an :term:`iterator` yielding :class:`MatchObject` instances over all
Georg Brandlb46d6ff2008-07-19 13:48:44 +0000605 non-overlapping matches for the RE *pattern* in *string*. The *string* is
606 scanned left-to-right, and matches are returned in the order found. Empty
607 matches are included in the result unless they touch the beginning of another
608 match.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000609
610 .. versionadded:: 2.2
611
612 .. versionchanged:: 2.4
613 Added the optional flags argument.
614
615
Eli Benderskyeb711382011-11-14 01:02:20 +0200616.. function:: sub(pattern, repl, string, count=0, flags=0)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000617
618 Return the string obtained by replacing the leftmost non-overlapping occurrences
619 of *pattern* in *string* by the replacement *repl*. If the pattern isn't found,
620 *string* is returned unchanged. *repl* can be a string or a function; if it is
621 a string, any backslash escapes in it are processed. That is, ``\n`` is
Sandro Tosia7eb3c82011-08-19 22:54:33 +0200622 converted to a single newline character, ``\r`` is converted to a carriage return, and
Georg Brandl8ec7f652007-08-15 14:28:01 +0000623 so forth. Unknown escapes such as ``\j`` are left alone. Backreferences, such
624 as ``\6``, are replaced with the substring matched by group 6 in the pattern.
Georg Brandl6199e322008-03-22 12:04:26 +0000625 For example:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000626
627 >>> re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',
628 ... r'static PyObject*\npy_\1(void)\n{',
629 ... 'def myfunc():')
630 'static PyObject*\npy_myfunc(void)\n{'
631
632 If *repl* is a function, it is called for every non-overlapping occurrence of
633 *pattern*. The function takes a single match object argument, and returns the
Georg Brandl6199e322008-03-22 12:04:26 +0000634 replacement string. For example:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000635
636 >>> def dashrepl(matchobj):
637 ... if matchobj.group(0) == '-': return ' '
638 ... else: return '-'
639 >>> re.sub('-{1,2}', dashrepl, 'pro----gram-files')
640 'pro--gram files'
Gregory P. Smithae91d092009-03-02 05:13:57 +0000641 >>> re.sub(r'\sAND\s', ' & ', 'Baked Beans And Spam', flags=re.IGNORECASE)
642 'Baked Beans & Spam'
Georg Brandl8ec7f652007-08-15 14:28:01 +0000643
Georg Brandl04fd3242009-08-13 07:48:05 +0000644 The pattern may be a string or an RE object.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000645
646 The optional argument *count* is the maximum number of pattern occurrences to be
647 replaced; *count* must be a non-negative integer. If omitted or zero, all
648 occurrences will be replaced. Empty matches for the pattern are replaced only
649 when not adjacent to a previous match, so ``sub('x*', '-', 'abc')`` returns
650 ``'-a-b-c-'``.
651
652 In addition to character escapes and backreferences as described above,
653 ``\g<name>`` will use the substring matched by the group named ``name``, as
654 defined by the ``(?P<name>...)`` syntax. ``\g<number>`` uses the corresponding
655 group number; ``\g<2>`` is therefore equivalent to ``\2``, but isn't ambiguous
656 in a replacement such as ``\g<2>0``. ``\20`` would be interpreted as a
657 reference to group 20, not a reference to group 2 followed by the literal
658 character ``'0'``. The backreference ``\g<0>`` substitutes in the entire
659 substring matched by the RE.
660
Ezio Melotti1e5d3182010-11-26 09:30:44 +0000661 .. versionchanged:: 2.7
Gregory P. Smithae91d092009-03-02 05:13:57 +0000662 Added the optional flags argument.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000663
Gregory P. Smithae91d092009-03-02 05:13:57 +0000664
Eli Benderskyeb711382011-11-14 01:02:20 +0200665.. function:: subn(pattern, repl, string, count=0, flags=0)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000666
667 Perform the same operation as :func:`sub`, but return a tuple ``(new_string,
668 number_of_subs_made)``.
669
Ezio Melotti1e5d3182010-11-26 09:30:44 +0000670 .. versionchanged:: 2.7
Gregory P. Smithae91d092009-03-02 05:13:57 +0000671 Added the optional flags argument.
672
Georg Brandl8ec7f652007-08-15 14:28:01 +0000673
674.. function:: escape(string)
675
676 Return *string* with all non-alphanumerics backslashed; this is useful if you
677 want to match an arbitrary literal string that may have regular expression
678 metacharacters in it.
679
680
R. David Murraya63f9b62010-07-10 14:25:18 +0000681.. function:: purge()
682
683 Clear the regular expression cache.
684
685
Georg Brandl8ec7f652007-08-15 14:28:01 +0000686.. exception:: error
687
688 Exception raised when a string passed to one of the functions here is not a
689 valid regular expression (for example, it might contain unmatched parentheses)
690 or when some other error occurs during compilation or matching. It is never an
691 error if a string contains no match for a pattern.
692
693
694.. _re-objects:
695
696Regular Expression Objects
697--------------------------
698
Brian Curtinfbe51992010-03-25 23:48:54 +0000699.. class:: RegexObject
700
701 The :class:`RegexObject` class supports the following methods and attributes:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000702
Georg Brandlb1a14052010-06-01 07:25:23 +0000703 .. method:: RegexObject.search(string[, pos[, endpos]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000704
Georg Brandlb1a14052010-06-01 07:25:23 +0000705 Scan through *string* looking for a location where this regular expression
706 produces a match, and return a corresponding :class:`MatchObject` instance.
707 Return ``None`` if no position in the string matches the pattern; note that this
708 is different from finding a zero-length match at some point in the string.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000709
Brian Curtinfbe51992010-03-25 23:48:54 +0000710 The optional second parameter *pos* gives an index in the string where the
711 search is to start; it defaults to ``0``. This is not completely equivalent to
712 slicing the string; the ``'^'`` pattern character matches at the real beginning
713 of the string and at positions just after a newline, but not necessarily at the
714 index where the search is to start.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000715
Brian Curtinfbe51992010-03-25 23:48:54 +0000716 The optional parameter *endpos* limits how far the string will be searched; it
717 will be as if the string is *endpos* characters long, so only the characters
718 from *pos* to ``endpos - 1`` will be searched for a match. If *endpos* is less
719 than *pos*, no match will be found, otherwise, if *rx* is a compiled regular
Georg Brandlb1a14052010-06-01 07:25:23 +0000720 expression object, ``rx.search(string, 0, 50)`` is equivalent to
721 ``rx.search(string[:50], 0)``.
Georg Brandlb8df1562007-12-05 18:30:48 +0000722
Georg Brandlb1a14052010-06-01 07:25:23 +0000723 >>> pattern = re.compile("d")
724 >>> pattern.search("dog") # Match at index 0
725 <_sre.SRE_Match object at ...>
726 >>> pattern.search("dog", 1) # No match; search doesn't include the "d"
Georg Brandl8ec7f652007-08-15 14:28:01 +0000727
728
Georg Brandlb1a14052010-06-01 07:25:23 +0000729 .. method:: RegexObject.match(string[, pos[, endpos]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000730
Georg Brandlb1a14052010-06-01 07:25:23 +0000731 If zero or more characters at the *beginning* of *string* match this regular
732 expression, return a corresponding :class:`MatchObject` instance. Return
733 ``None`` if the string does not match the pattern; note that this is different
734 from a zero-length match.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000735
Brian Curtinfbe51992010-03-25 23:48:54 +0000736 The optional *pos* and *endpos* parameters have the same meaning as for the
Georg Brandlb1a14052010-06-01 07:25:23 +0000737 :meth:`~RegexObject.search` method.
738
739 .. note::
740
741 If you want to locate a match anywhere in *string*, use
742 :meth:`~RegexObject.search` instead.
743
744 >>> pattern = re.compile("o")
745 >>> pattern.match("dog") # No match as "o" is not at the start of "dog".
746 >>> pattern.match("dog", 1) # Match as "o" is the 2nd character of "dog".
747 <_sre.SRE_Match object at ...>
Georg Brandl8ec7f652007-08-15 14:28:01 +0000748
749
Eli Benderskyeb711382011-11-14 01:02:20 +0200750 .. method:: RegexObject.split(string, maxsplit=0)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000751
Brian Curtinfbe51992010-03-25 23:48:54 +0000752 Identical to the :func:`split` function, using the compiled pattern.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000753
754
Brian Curtinfbe51992010-03-25 23:48:54 +0000755 .. method:: RegexObject.findall(string[, pos[, endpos]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000756
Georg Brandlf93ce0c2010-05-22 08:17:23 +0000757 Similar to the :func:`findall` function, using the compiled pattern, but
758 also accepts optional *pos* and *endpos* parameters that limit the search
759 region like for :meth:`match`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000760
761
Brian Curtinfbe51992010-03-25 23:48:54 +0000762 .. method:: RegexObject.finditer(string[, pos[, endpos]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000763
Georg Brandlf93ce0c2010-05-22 08:17:23 +0000764 Similar to the :func:`finditer` function, using the compiled pattern, but
765 also accepts optional *pos* and *endpos* parameters that limit the search
766 region like for :meth:`match`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000767
768
Eli Benderskyeb711382011-11-14 01:02:20 +0200769 .. method:: RegexObject.sub(repl, string, count=0)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000770
Brian Curtinfbe51992010-03-25 23:48:54 +0000771 Identical to the :func:`sub` function, using the compiled pattern.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000772
773
Eli Benderskyeb711382011-11-14 01:02:20 +0200774 .. method:: RegexObject.subn(repl, string, count=0)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000775
Brian Curtinfbe51992010-03-25 23:48:54 +0000776 Identical to the :func:`subn` function, using the compiled pattern.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000777
778
Brian Curtinfbe51992010-03-25 23:48:54 +0000779 .. attribute:: RegexObject.flags
Georg Brandl8ec7f652007-08-15 14:28:01 +0000780
Brian Curtinfbe51992010-03-25 23:48:54 +0000781 The flags argument used when the RE object was compiled, or ``0`` if no flags
782 were provided.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000783
784
Brian Curtinfbe51992010-03-25 23:48:54 +0000785 .. attribute:: RegexObject.groups
Georg Brandlb46f0d72008-12-05 07:49:49 +0000786
Brian Curtinfbe51992010-03-25 23:48:54 +0000787 The number of capturing groups in the pattern.
Georg Brandlb46f0d72008-12-05 07:49:49 +0000788
789
Brian Curtinfbe51992010-03-25 23:48:54 +0000790 .. attribute:: RegexObject.groupindex
Georg Brandl8ec7f652007-08-15 14:28:01 +0000791
Brian Curtinfbe51992010-03-25 23:48:54 +0000792 A dictionary mapping any symbolic group names defined by ``(?P<id>)`` to group
793 numbers. The dictionary is empty if no symbolic groups were used in the
794 pattern.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000795
796
Brian Curtinfbe51992010-03-25 23:48:54 +0000797 .. attribute:: RegexObject.pattern
Georg Brandl8ec7f652007-08-15 14:28:01 +0000798
Brian Curtinfbe51992010-03-25 23:48:54 +0000799 The pattern string from which the RE object was compiled.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000800
801
802.. _match-objects:
803
804Match Objects
805-------------
806
Brian Curtinfbe51992010-03-25 23:48:54 +0000807.. class:: MatchObject
808
809 Match Objects always have a boolean value of :const:`True`, so that you can test
810 whether e.g. :func:`match` resulted in a match with a simple if statement. They
811 support the following methods and attributes:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000812
813
Brian Curtinfbe51992010-03-25 23:48:54 +0000814 .. method:: MatchObject.expand(template)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000815
Brian Curtinfbe51992010-03-25 23:48:54 +0000816 Return the string obtained by doing backslash substitution on the template
817 string *template*, as done by the :meth:`~RegexObject.sub` method. Escapes
818 such as ``\n`` are converted to the appropriate characters, and numeric
819 backreferences (``\1``, ``\2``) and named backreferences (``\g<1>``,
820 ``\g<name>``) are replaced by the contents of the corresponding group.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000821
822
Brian Curtinfbe51992010-03-25 23:48:54 +0000823 .. method:: MatchObject.group([group1, ...])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000824
Brian Curtinfbe51992010-03-25 23:48:54 +0000825 Returns one or more subgroups of the match. If there is a single argument, the
826 result is a single string; if there are multiple arguments, the result is a
827 tuple with one item per argument. Without arguments, *group1* defaults to zero
828 (the whole match is returned). If a *groupN* argument is zero, the corresponding
829 return value is the entire matching string; if it is in the inclusive range
830 [1..99], it is the string matching the corresponding parenthesized group. If a
831 group number is negative or larger than the number of groups defined in the
832 pattern, an :exc:`IndexError` exception is raised. If a group is contained in a
833 part of the pattern that did not match, the corresponding result is ``None``.
834 If a group is contained in a part of the pattern that matched multiple times,
835 the last match is returned.
Georg Brandlb8df1562007-12-05 18:30:48 +0000836
Brian Curtinfbe51992010-03-25 23:48:54 +0000837 >>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
838 >>> m.group(0) # The entire match
839 'Isaac Newton'
840 >>> m.group(1) # The first parenthesized subgroup.
841 'Isaac'
842 >>> m.group(2) # The second parenthesized subgroup.
843 'Newton'
844 >>> m.group(1, 2) # Multiple arguments give us a tuple.
845 ('Isaac', 'Newton')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000846
Brian Curtinfbe51992010-03-25 23:48:54 +0000847 If the regular expression uses the ``(?P<name>...)`` syntax, the *groupN*
848 arguments may also be strings identifying groups by their group name. If a
849 string argument is not used as a group name in the pattern, an :exc:`IndexError`
850 exception is raised.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000851
Brian Curtinfbe51992010-03-25 23:48:54 +0000852 A moderately complicated example:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000853
Brian Curtinfbe51992010-03-25 23:48:54 +0000854 >>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds")
855 >>> m.group('first_name')
856 'Malcolm'
857 >>> m.group('last_name')
858 'Reynolds'
Georg Brandl8ec7f652007-08-15 14:28:01 +0000859
Brian Curtinfbe51992010-03-25 23:48:54 +0000860 Named groups can also be referred to by their index:
Georg Brandlb8df1562007-12-05 18:30:48 +0000861
Brian Curtinfbe51992010-03-25 23:48:54 +0000862 >>> m.group(1)
863 'Malcolm'
864 >>> m.group(2)
865 'Reynolds'
Georg Brandlb8df1562007-12-05 18:30:48 +0000866
Brian Curtinfbe51992010-03-25 23:48:54 +0000867 If a group matches multiple times, only the last match is accessible:
Georg Brandl6199e322008-03-22 12:04:26 +0000868
Brian Curtinfbe51992010-03-25 23:48:54 +0000869 >>> m = re.match(r"(..)+", "a1b2c3") # Matches 3 times.
870 >>> m.group(1) # Returns only the last match.
871 'c3'
Georg Brandl8ec7f652007-08-15 14:28:01 +0000872
873
Brian Curtinfbe51992010-03-25 23:48:54 +0000874 .. method:: MatchObject.groups([default])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000875
Brian Curtinfbe51992010-03-25 23:48:54 +0000876 Return a tuple containing all the subgroups of the match, from 1 up to however
877 many groups are in the pattern. The *default* argument is used for groups that
878 did not participate in the match; it defaults to ``None``. (Incompatibility
879 note: in the original Python 1.5 release, if the tuple was one element long, a
880 string would be returned instead. In later versions (from 1.5.1 on), a
881 singleton tuple is returned in such cases.)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000882
Brian Curtinfbe51992010-03-25 23:48:54 +0000883 For example:
Georg Brandlb8df1562007-12-05 18:30:48 +0000884
Brian Curtinfbe51992010-03-25 23:48:54 +0000885 >>> m = re.match(r"(\d+)\.(\d+)", "24.1632")
886 >>> m.groups()
887 ('24', '1632')
Georg Brandlb8df1562007-12-05 18:30:48 +0000888
Brian Curtinfbe51992010-03-25 23:48:54 +0000889 If we make the decimal place and everything after it optional, not all groups
890 might participate in the match. These groups will default to ``None`` unless
891 the *default* argument is given:
Georg Brandlb8df1562007-12-05 18:30:48 +0000892
Brian Curtinfbe51992010-03-25 23:48:54 +0000893 >>> m = re.match(r"(\d+)\.?(\d+)?", "24")
894 >>> m.groups() # Second group defaults to None.
895 ('24', None)
896 >>> m.groups('0') # Now, the second group defaults to '0'.
897 ('24', '0')
Georg Brandlb8df1562007-12-05 18:30:48 +0000898
Georg Brandl8ec7f652007-08-15 14:28:01 +0000899
Brian Curtinfbe51992010-03-25 23:48:54 +0000900 .. method:: MatchObject.groupdict([default])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000901
Brian Curtinfbe51992010-03-25 23:48:54 +0000902 Return a dictionary containing all the *named* subgroups of the match, keyed by
903 the subgroup name. The *default* argument is used for groups that did not
904 participate in the match; it defaults to ``None``. For example:
Georg Brandlb8df1562007-12-05 18:30:48 +0000905
Brian Curtinfbe51992010-03-25 23:48:54 +0000906 >>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds")
907 >>> m.groupdict()
908 {'first_name': 'Malcolm', 'last_name': 'Reynolds'}
Georg Brandl8ec7f652007-08-15 14:28:01 +0000909
910
Brian Curtinfbe51992010-03-25 23:48:54 +0000911 .. method:: MatchObject.start([group])
912 MatchObject.end([group])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000913
Brian Curtinfbe51992010-03-25 23:48:54 +0000914 Return the indices of the start and end of the substring matched by *group*;
915 *group* defaults to zero (meaning the whole matched substring). Return ``-1`` if
916 *group* exists but did not contribute to the match. For a match object *m*, and
917 a group *g* that did contribute to the match, the substring matched by group *g*
918 (equivalent to ``m.group(g)``) is ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000919
Brian Curtinfbe51992010-03-25 23:48:54 +0000920 m.string[m.start(g):m.end(g)]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000921
Brian Curtinfbe51992010-03-25 23:48:54 +0000922 Note that ``m.start(group)`` will equal ``m.end(group)`` if *group* matched a
923 null string. For example, after ``m = re.search('b(c?)', 'cba')``,
924 ``m.start(0)`` is 1, ``m.end(0)`` is 2, ``m.start(1)`` and ``m.end(1)`` are both
925 2, and ``m.start(2)`` raises an :exc:`IndexError` exception.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000926
Brian Curtinfbe51992010-03-25 23:48:54 +0000927 An example that will remove *remove_this* from email addresses:
Georg Brandlb8df1562007-12-05 18:30:48 +0000928
Brian Curtinfbe51992010-03-25 23:48:54 +0000929 >>> email = "tony@tiremove_thisger.net"
930 >>> m = re.search("remove_this", email)
931 >>> email[:m.start()] + email[m.end():]
932 'tony@tiger.net'
Georg Brandlb8df1562007-12-05 18:30:48 +0000933
Georg Brandl8ec7f652007-08-15 14:28:01 +0000934
Brian Curtinfbe51992010-03-25 23:48:54 +0000935 .. method:: MatchObject.span([group])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000936
Brian Curtinfbe51992010-03-25 23:48:54 +0000937 For :class:`MatchObject` *m*, return the 2-tuple ``(m.start(group),
938 m.end(group))``. Note that if *group* did not contribute to the match, this is
939 ``(-1, -1)``. *group* defaults to zero, the entire match.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000940
941
Brian Curtinfbe51992010-03-25 23:48:54 +0000942 .. attribute:: MatchObject.pos
Georg Brandl8ec7f652007-08-15 14:28:01 +0000943
Brian Curtinfbe51992010-03-25 23:48:54 +0000944 The value of *pos* which was passed to the :meth:`~RegexObject.search` or
945 :meth:`~RegexObject.match` method of the :class:`RegexObject`. This is the
946 index into the string at which the RE engine started looking for a match.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000947
948
Brian Curtinfbe51992010-03-25 23:48:54 +0000949 .. attribute:: MatchObject.endpos
Georg Brandl8ec7f652007-08-15 14:28:01 +0000950
Brian Curtinfbe51992010-03-25 23:48:54 +0000951 The value of *endpos* which was passed to the :meth:`~RegexObject.search` or
952 :meth:`~RegexObject.match` method of the :class:`RegexObject`. This is the
953 index into the string beyond which the RE engine will not go.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000954
955
Brian Curtinfbe51992010-03-25 23:48:54 +0000956 .. attribute:: MatchObject.lastindex
Georg Brandl8ec7f652007-08-15 14:28:01 +0000957
Brian Curtinfbe51992010-03-25 23:48:54 +0000958 The integer index of the last matched capturing group, or ``None`` if no group
959 was matched at all. For example, the expressions ``(a)b``, ``((a)(b))``, and
960 ``((ab))`` will have ``lastindex == 1`` if applied to the string ``'ab'``, while
961 the expression ``(a)(b)`` will have ``lastindex == 2``, if applied to the same
962 string.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000963
964
Brian Curtinfbe51992010-03-25 23:48:54 +0000965 .. attribute:: MatchObject.lastgroup
Georg Brandl8ec7f652007-08-15 14:28:01 +0000966
Brian Curtinfbe51992010-03-25 23:48:54 +0000967 The name of the last matched capturing group, or ``None`` if the group didn't
968 have a name, or if no group was matched at all.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000969
970
Brian Curtinfbe51992010-03-25 23:48:54 +0000971 .. attribute:: MatchObject.re
Georg Brandl8ec7f652007-08-15 14:28:01 +0000972
Brian Curtinfbe51992010-03-25 23:48:54 +0000973 The regular expression object whose :meth:`~RegexObject.match` or
974 :meth:`~RegexObject.search` method produced this :class:`MatchObject`
975 instance.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000976
977
Brian Curtinfbe51992010-03-25 23:48:54 +0000978 .. attribute:: MatchObject.string
Georg Brandl8ec7f652007-08-15 14:28:01 +0000979
Brian Curtinfbe51992010-03-25 23:48:54 +0000980 The string passed to :meth:`~RegexObject.match` or
981 :meth:`~RegexObject.search`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000982
983
984Examples
985--------
986
Georg Brandlb8df1562007-12-05 18:30:48 +0000987
988Checking For a Pair
989^^^^^^^^^^^^^^^^^^^
990
991In this example, we'll use the following helper function to display match
Georg Brandl6199e322008-03-22 12:04:26 +0000992objects a little more gracefully:
993
Georg Brandl838b4b02008-03-22 13:07:06 +0000994.. testcode::
Georg Brandlb8df1562007-12-05 18:30:48 +0000995
996 def displaymatch(match):
997 if match is None:
998 return None
999 return '<Match: %r, groups=%r>' % (match.group(), match.groups())
1000
1001Suppose you are writing a poker program where a player's hand is represented as
1002a 5-character string with each character representing a card, "a" for ace, "k"
Ezio Melotti13c82d02011-12-17 01:17:17 +02001003for king, "q" for queen, "j" for jack, "t" for 10, and "2" through "9"
Georg Brandlb8df1562007-12-05 18:30:48 +00001004representing the card with that value.
1005
Georg Brandl6199e322008-03-22 12:04:26 +00001006To see if a given string is a valid hand, one could do the following:
Georg Brandlb8df1562007-12-05 18:30:48 +00001007
Ezio Melotti13c82d02011-12-17 01:17:17 +02001008 >>> valid = re.compile(r"^[a2-9tjqk]{5}$")
1009 >>> displaymatch(valid.match("akt5q")) # Valid.
1010 "<Match: 'akt5q', groups=()>"
1011 >>> displaymatch(valid.match("akt5e")) # Invalid.
1012 >>> displaymatch(valid.match("akt")) # Invalid.
Georg Brandlb8df1562007-12-05 18:30:48 +00001013 >>> displaymatch(valid.match("727ak")) # Valid.
Georg Brandl6199e322008-03-22 12:04:26 +00001014 "<Match: '727ak', groups=()>"
Georg Brandlb8df1562007-12-05 18:30:48 +00001015
1016That last hand, ``"727ak"``, contained a pair, or two of the same valued cards.
Georg Brandl6199e322008-03-22 12:04:26 +00001017To match this with a regular expression, one could use backreferences as such:
Georg Brandlb8df1562007-12-05 18:30:48 +00001018
1019 >>> pair = re.compile(r".*(.).*\1")
1020 >>> displaymatch(pair.match("717ak")) # Pair of 7s.
Georg Brandl6199e322008-03-22 12:04:26 +00001021 "<Match: '717', groups=('7',)>"
Georg Brandlb8df1562007-12-05 18:30:48 +00001022 >>> displaymatch(pair.match("718ak")) # No pairs.
1023 >>> displaymatch(pair.match("354aa")) # Pair of aces.
Georg Brandl6199e322008-03-22 12:04:26 +00001024 "<Match: '354aa', groups=('a',)>"
Georg Brandlb8df1562007-12-05 18:30:48 +00001025
Georg Brandl74f8fc02009-07-26 13:36:39 +00001026To find out what card the pair consists of, one could use the
1027:meth:`~MatchObject.group` method of :class:`MatchObject` in the following
1028manner:
Georg Brandl6199e322008-03-22 12:04:26 +00001029
Georg Brandl838b4b02008-03-22 13:07:06 +00001030.. doctest::
Georg Brandlb8df1562007-12-05 18:30:48 +00001031
1032 >>> pair.match("717ak").group(1)
1033 '7'
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001034
Georg Brandlb8df1562007-12-05 18:30:48 +00001035 # Error because re.match() returns None, which doesn't have a group() method:
1036 >>> pair.match("718ak").group(1)
1037 Traceback (most recent call last):
1038 File "<pyshell#23>", line 1, in <module>
1039 re.match(r".*(.).*\1", "718ak").group(1)
1040 AttributeError: 'NoneType' object has no attribute 'group'
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001041
Georg Brandlb8df1562007-12-05 18:30:48 +00001042 >>> pair.match("354aa").group(1)
1043 'a'
1044
1045
1046Simulating scanf()
1047^^^^^^^^^^^^^^^^^^
Georg Brandl8ec7f652007-08-15 14:28:01 +00001048
1049.. index:: single: scanf()
1050
1051Python does not currently have an equivalent to :cfunc:`scanf`. Regular
1052expressions are generally more powerful, though also more verbose, than
1053:cfunc:`scanf` format strings. The table below offers some more-or-less
1054equivalent mappings between :cfunc:`scanf` format tokens and regular
1055expressions.
1056
1057+--------------------------------+---------------------------------------------+
1058| :cfunc:`scanf` Token | Regular Expression |
1059+================================+=============================================+
1060| ``%c`` | ``.`` |
1061+--------------------------------+---------------------------------------------+
1062| ``%5c`` | ``.{5}`` |
1063+--------------------------------+---------------------------------------------+
1064| ``%d`` | ``[-+]?\d+`` |
1065+--------------------------------+---------------------------------------------+
1066| ``%e``, ``%E``, ``%f``, ``%g`` | ``[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?`` |
1067+--------------------------------+---------------------------------------------+
1068| ``%i`` | ``[-+]?(0[xX][\dA-Fa-f]+|0[0-7]*|\d+)`` |
1069+--------------------------------+---------------------------------------------+
1070| ``%o`` | ``0[0-7]*`` |
1071+--------------------------------+---------------------------------------------+
1072| ``%s`` | ``\S+`` |
1073+--------------------------------+---------------------------------------------+
1074| ``%u`` | ``\d+`` |
1075+--------------------------------+---------------------------------------------+
1076| ``%x``, ``%X`` | ``0[xX][\dA-Fa-f]+`` |
1077+--------------------------------+---------------------------------------------+
1078
1079To extract the filename and numbers from a string like ::
1080
1081 /usr/sbin/sendmail - 0 errors, 4 warnings
1082
1083you would use a :cfunc:`scanf` format like ::
1084
1085 %s - %d errors, %d warnings
1086
1087The equivalent regular expression would be ::
1088
1089 (\S+) - (\d+) errors, (\d+) warnings
1090
Georg Brandlb8df1562007-12-05 18:30:48 +00001091
1092Avoiding recursion
1093^^^^^^^^^^^^^^^^^^
Georg Brandl8ec7f652007-08-15 14:28:01 +00001094
1095If you create regular expressions that require the engine to perform a lot of
1096recursion, you may encounter a :exc:`RuntimeError` exception with the message
1097``maximum recursion limit`` exceeded. For example, ::
1098
Georg Brandl8ec7f652007-08-15 14:28:01 +00001099 >>> s = 'Begin ' + 1000*'a very long string ' + 'end'
1100 >>> re.match('Begin (\w| )*? end', s).end()
1101 Traceback (most recent call last):
1102 File "<stdin>", line 1, in ?
1103 File "/usr/local/lib/python2.5/re.py", line 132, in match
1104 return _compile(pattern, flags).match(string)
1105 RuntimeError: maximum recursion limit exceeded
1106
1107You can often restructure your regular expression to avoid recursion.
1108
1109Starting with Python 2.3, simple uses of the ``*?`` pattern are special-cased to
1110avoid recursion. Thus, the above regular expression can avoid recursion by
1111being recast as ``Begin [a-zA-Z0-9_ ]*?end``. As a further benefit, such
1112regular expressions will run faster than their recursive equivalents.
1113
Georg Brandlb8df1562007-12-05 18:30:48 +00001114
1115search() vs. match()
1116^^^^^^^^^^^^^^^^^^^^
1117
1118In a nutshell, :func:`match` only attempts to match a pattern at the beginning
1119of a string where :func:`search` will match a pattern anywhere in a string.
Georg Brandl6199e322008-03-22 12:04:26 +00001120For example:
Georg Brandlb8df1562007-12-05 18:30:48 +00001121
1122 >>> re.match("o", "dog") # No match as "o" is not the first letter of "dog".
1123 >>> re.search("o", "dog") # Match as search() looks everywhere in the string.
Georg Brandl6199e322008-03-22 12:04:26 +00001124 <_sre.SRE_Match object at ...>
Georg Brandlb8df1562007-12-05 18:30:48 +00001125
1126.. note::
1127
Georg Brandl6199e322008-03-22 12:04:26 +00001128 The following applies only to regular expression objects like those created
1129 with ``re.compile("pattern")``, not the primitives ``re.match(pattern,
1130 string)`` or ``re.search(pattern, string)``.
Georg Brandlb8df1562007-12-05 18:30:48 +00001131
1132:func:`match` has an optional second parameter that gives an index in the string
Georg Brandl545a1342009-03-15 21:59:37 +00001133where the search is to start::
Georg Brandlb8df1562007-12-05 18:30:48 +00001134
1135 >>> pattern = re.compile("o")
1136 >>> pattern.match("dog") # No match as "o" is not at the start of "dog."
Georg Brandl6199e322008-03-22 12:04:26 +00001137
Georg Brandlb8df1562007-12-05 18:30:48 +00001138 # Equivalent to the above expression as 0 is the default starting index:
1139 >>> pattern.match("dog", 0)
Georg Brandl6199e322008-03-22 12:04:26 +00001140
Georg Brandlb8df1562007-12-05 18:30:48 +00001141 # Match as "o" is the 2nd character of "dog" (index 0 is the first):
1142 >>> pattern.match("dog", 1)
Georg Brandl6199e322008-03-22 12:04:26 +00001143 <_sre.SRE_Match object at ...>
Georg Brandlb8df1562007-12-05 18:30:48 +00001144 >>> pattern.match("dog", 2) # No match as "o" is not the 3rd character of "dog."
1145
1146
1147Making a Phonebook
1148^^^^^^^^^^^^^^^^^^
1149
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001150:func:`split` splits a string into a list delimited by the passed pattern. The
Georg Brandlb8df1562007-12-05 18:30:48 +00001151method is invaluable for converting textual data into data structures that can be
1152easily read and modified by Python as demonstrated in the following example that
1153creates a phonebook.
1154
Georg Brandld6b20dc2007-12-06 09:45:39 +00001155First, here is the input. Normally it may come from a file, here we are using
Georg Brandl6199e322008-03-22 12:04:26 +00001156triple-quoted string syntax:
Georg Brandlb8df1562007-12-05 18:30:48 +00001157
Georg Brandld6b20dc2007-12-06 09:45:39 +00001158 >>> input = """Ross McFluff: 834.345.1254 155 Elm Street
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001159 ...
Georg Brandl6199e322008-03-22 12:04:26 +00001160 ... Ronald Heathmore: 892.345.3428 436 Finley Avenue
1161 ... Frank Burger: 925.541.7625 662 South Dogwood Way
1162 ...
1163 ...
1164 ... Heather Albrecht: 548.326.4584 919 Park Place"""
Georg Brandld6b20dc2007-12-06 09:45:39 +00001165
1166The entries are separated by one or more newlines. Now we convert the string
Georg Brandl6199e322008-03-22 12:04:26 +00001167into a list with each nonempty line having its own entry:
1168
Georg Brandl838b4b02008-03-22 13:07:06 +00001169.. doctest::
Georg Brandl6199e322008-03-22 12:04:26 +00001170 :options: +NORMALIZE_WHITESPACE
Georg Brandld6b20dc2007-12-06 09:45:39 +00001171
1172 >>> entries = re.split("\n+", input)
Georg Brandlb8df1562007-12-05 18:30:48 +00001173 >>> entries
Georg Brandl6199e322008-03-22 12:04:26 +00001174 ['Ross McFluff: 834.345.1254 155 Elm Street',
1175 'Ronald Heathmore: 892.345.3428 436 Finley Avenue',
1176 'Frank Burger: 925.541.7625 662 South Dogwood Way',
1177 'Heather Albrecht: 548.326.4584 919 Park Place']
Georg Brandlb8df1562007-12-05 18:30:48 +00001178
1179Finally, split each entry into a list with first name, last name, telephone
Georg Brandl907a7202008-02-22 12:31:45 +00001180number, and address. We use the ``maxsplit`` parameter of :func:`split`
Georg Brandl6199e322008-03-22 12:04:26 +00001181because the address has spaces, our splitting pattern, in it:
1182
Georg Brandl838b4b02008-03-22 13:07:06 +00001183.. doctest::
Georg Brandl6199e322008-03-22 12:04:26 +00001184 :options: +NORMALIZE_WHITESPACE
Georg Brandlb8df1562007-12-05 18:30:48 +00001185
Georg Brandld6b20dc2007-12-06 09:45:39 +00001186 >>> [re.split(":? ", entry, 3) for entry in entries]
Georg Brandlb8df1562007-12-05 18:30:48 +00001187 [['Ross', 'McFluff', '834.345.1254', '155 Elm Street'],
1188 ['Ronald', 'Heathmore', '892.345.3428', '436 Finley Avenue'],
1189 ['Frank', 'Burger', '925.541.7625', '662 South Dogwood Way'],
1190 ['Heather', 'Albrecht', '548.326.4584', '919 Park Place']]
1191
Georg Brandld6b20dc2007-12-06 09:45:39 +00001192The ``:?`` pattern matches the colon after the last name, so that it does not
Georg Brandl907a7202008-02-22 12:31:45 +00001193occur in the result list. With a ``maxsplit`` of ``4``, we could separate the
Georg Brandl6199e322008-03-22 12:04:26 +00001194house number from the street name:
1195
Georg Brandl838b4b02008-03-22 13:07:06 +00001196.. doctest::
Georg Brandl6199e322008-03-22 12:04:26 +00001197 :options: +NORMALIZE_WHITESPACE
Georg Brandlb8df1562007-12-05 18:30:48 +00001198
Georg Brandld6b20dc2007-12-06 09:45:39 +00001199 >>> [re.split(":? ", entry, 4) for entry in entries]
Georg Brandlb8df1562007-12-05 18:30:48 +00001200 [['Ross', 'McFluff', '834.345.1254', '155', 'Elm Street'],
1201 ['Ronald', 'Heathmore', '892.345.3428', '436', 'Finley Avenue'],
1202 ['Frank', 'Burger', '925.541.7625', '662', 'South Dogwood Way'],
1203 ['Heather', 'Albrecht', '548.326.4584', '919', 'Park Place']]
1204
1205
1206Text Munging
1207^^^^^^^^^^^^
1208
1209:func:`sub` replaces every occurrence of a pattern with a string or the
1210result of a function. This example demonstrates using :func:`sub` with
1211a function to "munge" text, or randomize the order of all the characters
1212in each word of a sentence except for the first and last characters::
1213
1214 >>> def repl(m):
1215 ... inner_word = list(m.group(2))
1216 ... random.shuffle(inner_word)
1217 ... return m.group(1) + "".join(inner_word) + m.group(3)
1218 >>> text = "Professor Abdolmalek, please report your absences promptly."
Georg Brandle0289a32010-08-01 21:44:38 +00001219 >>> re.sub(r"(\w)(\w+)(\w)", repl, text)
Georg Brandlb8df1562007-12-05 18:30:48 +00001220 'Poefsrosr Aealmlobdk, pslaee reorpt your abnseces plmrptoy.'
Georg Brandle0289a32010-08-01 21:44:38 +00001221 >>> re.sub(r"(\w)(\w+)(\w)", repl, text)
Georg Brandlb8df1562007-12-05 18:30:48 +00001222 'Pofsroser Aodlambelk, plasee reoprt yuor asnebces potlmrpy.'
1223
1224
1225Finding all Adverbs
1226^^^^^^^^^^^^^^^^^^^
1227
Georg Brandl907a7202008-02-22 12:31:45 +00001228:func:`findall` matches *all* occurrences of a pattern, not just the first
Georg Brandlb8df1562007-12-05 18:30:48 +00001229one as :func:`search` does. For example, if one was a writer and wanted to
1230find all of the adverbs in some text, he or she might use :func:`findall` in
Georg Brandl6199e322008-03-22 12:04:26 +00001231the following manner:
Georg Brandlb8df1562007-12-05 18:30:48 +00001232
1233 >>> text = "He was carefully disguised but captured quickly by police."
1234 >>> re.findall(r"\w+ly", text)
1235 ['carefully', 'quickly']
1236
1237
1238Finding all Adverbs and their Positions
1239^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1240
1241If one wants more information about all matches of a pattern than the matched
1242text, :func:`finditer` is useful as it provides instances of
1243:class:`MatchObject` instead of strings. Continuing with the previous example,
1244if one was a writer who wanted to find all of the adverbs *and their positions*
Georg Brandl6199e322008-03-22 12:04:26 +00001245in some text, he or she would use :func:`finditer` in the following manner:
Georg Brandlb8df1562007-12-05 18:30:48 +00001246
1247 >>> text = "He was carefully disguised but captured quickly by police."
1248 >>> for m in re.finditer(r"\w+ly", text):
Georg Brandl6199e322008-03-22 12:04:26 +00001249 ... print '%02d-%02d: %s' % (m.start(), m.end(), m.group(0))
Georg Brandlb8df1562007-12-05 18:30:48 +00001250 07-16: carefully
1251 40-47: quickly
1252
1253
1254Raw String Notation
1255^^^^^^^^^^^^^^^^^^^
1256
1257Raw string notation (``r"text"``) keeps regular expressions sane. Without it,
1258every backslash (``'\'``) in a regular expression would have to be prefixed with
1259another one to escape it. For example, the two following lines of code are
Georg Brandl6199e322008-03-22 12:04:26 +00001260functionally identical:
Georg Brandlb8df1562007-12-05 18:30:48 +00001261
1262 >>> re.match(r"\W(.)\1\W", " ff ")
Georg Brandl6199e322008-03-22 12:04:26 +00001263 <_sre.SRE_Match object at ...>
Georg Brandlb8df1562007-12-05 18:30:48 +00001264 >>> re.match("\\W(.)\\1\\W", " ff ")
Georg Brandl6199e322008-03-22 12:04:26 +00001265 <_sre.SRE_Match object at ...>
Georg Brandlb8df1562007-12-05 18:30:48 +00001266
1267When one wants to match a literal backslash, it must be escaped in the regular
1268expression. With raw string notation, this means ``r"\\"``. Without raw string
1269notation, one must use ``"\\\\"``, making the following lines of code
Georg Brandl6199e322008-03-22 12:04:26 +00001270functionally identical:
Georg Brandlb8df1562007-12-05 18:30:48 +00001271
1272 >>> re.match(r"\\", r"\\")
Georg Brandl6199e322008-03-22 12:04:26 +00001273 <_sre.SRE_Match object at ...>
Georg Brandlb8df1562007-12-05 18:30:48 +00001274 >>> re.match("\\\\", r"\\")
Georg Brandl6199e322008-03-22 12:04:26 +00001275 <_sre.SRE_Match object at ...>