blob: e6e20d62d2be79b0e5e4bd64d5f9a3dbbd42225c [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
Ezio Melotti11427732012-04-29 07:34:22 +0300276 patterns which start with positive lookbehind assertions will not match at the
Georg Brandl8ec7f652007-08-15 14:28:01 +0000277 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.
Ezio Melotti38ae5b22012-02-29 11:40:00 +0200328 Note that formally, ``\b`` is defined as the boundary between a ``\w`` and
329 a ``\W`` character (or vice versa), or between ``\w`` and the beginning/end
330 of the string, so the precise set of characters deemed to be alphanumeric
331 depends on the values of the ``UNICODE`` and ``LOCALE`` flags.
332 For example, ``r'\bfoo\b'`` matches ``'foo'``, ``'foo.'``, ``'(foo)'``,
333 ``'bar foo baz'`` but not ``'foobar'`` or ``'foo3'``.
334 Inside a character range, ``\b`` represents the backspace character, for compatibility with Python's string literals.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000335
336``\B``
337 Matches the empty string, but only when it is *not* at the beginning or end of a
Ezio Melotti38ae5b22012-02-29 11:40:00 +0200338 word. This means that ``r'py\B'`` matches ``'python'``, ``'py3'``, ``'py2'``,
339 but not ``'py'``, ``'py.'``, or ``'py!'``.
340 ``\B`` is just the opposite of ``\b``, so is also subject to the settings
Georg Brandl8ec7f652007-08-15 14:28:01 +0000341 of ``LOCALE`` and ``UNICODE``.
342
343``\d``
344 When the :const:`UNICODE` flag is not specified, matches any decimal digit; this
345 is equivalent to the set ``[0-9]``. With :const:`UNICODE`, it will match
Mark Dickinsonfe67bd92009-07-28 20:35:03 +0000346 whatever is classified as a decimal digit in the Unicode character properties
347 database.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000348
349``\D``
350 When the :const:`UNICODE` flag is not specified, matches any non-digit
351 character; this is equivalent to the set ``[^0-9]``. With :const:`UNICODE`, it
352 will match anything other than character marked as digits in the Unicode
353 character properties database.
354
355``\s``
Senthil Kumarandc0b3242012-04-11 03:22:58 +0800356 When the :const:`UNICODE` flag is not specified, it matches any whitespace
357 character, this is equivalent to the set ``[ \t\n\r\f\v]``. The
358 :const:`LOCALE` flag has no extra effect on matching of the space.
359 If :const:`UNICODE` is set, this will match the characters ``[ \t\n\r\f\v]``
360 plus whatever is classified as space in the Unicode character properties
361 database.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000362
363``\S``
Senthil Kumarandc0b3242012-04-11 03:22:58 +0800364 When the :const:`UNICODE` flags is not specified, matches any non-whitespace
365 character; this is equivalent to the set ``[^ \t\n\r\f\v]`` The
366 :const:`LOCALE` flag has no extra effect on non-whitespace match. If
367 :const:`UNICODE` is set, then any character not marked as space in the
368 Unicode character properties database is matched.
369
Georg Brandl8ec7f652007-08-15 14:28:01 +0000370
371``\w``
372 When the :const:`LOCALE` and :const:`UNICODE` flags are not specified, matches
373 any alphanumeric character and the underscore; this is equivalent to the set
374 ``[a-zA-Z0-9_]``. With :const:`LOCALE`, it will match the set ``[0-9_]`` plus
375 whatever characters are defined as alphanumeric for the current locale. If
376 :const:`UNICODE` is set, this will match the characters ``[0-9_]`` plus whatever
377 is classified as alphanumeric in the Unicode character properties database.
378
379``\W``
380 When the :const:`LOCALE` and :const:`UNICODE` flags are not specified, matches
381 any non-alphanumeric character; this is equivalent to the set ``[^a-zA-Z0-9_]``.
382 With :const:`LOCALE`, it will match any character not in the set ``[0-9_]``, and
383 not defined as alphanumeric for the current locale. If :const:`UNICODE` is set,
Senthil Kumaran15b6f3f2012-03-11 20:37:39 -0700384 this will match anything other than ``[0-9_]`` plus characters classied as
385 not alphanumeric in the Unicode character properties database.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000386
387``\Z``
388 Matches only at the end of the string.
389
Senthil Kumaran15b6f3f2012-03-11 20:37:39 -0700390If both :const:`LOCALE` and :const:`UNICODE` flags are included for a
391particular sequence, then :const:`LOCALE` flag takes effect first followed by
392the :const:`UNICODE`.
393
Georg Brandl8ec7f652007-08-15 14:28:01 +0000394Most of the standard escapes supported by Python string literals are also
395accepted by the regular expression parser::
396
397 \a \b \f \n
398 \r \t \v \x
399 \\
400
Ezio Melotti48d886b2012-04-29 04:46:34 +0300401(Note that ``\b`` is used to represent word boundaries, and means "backspace"
402only inside character classes.)
403
Georg Brandl8ec7f652007-08-15 14:28:01 +0000404Octal escapes are included in a limited form: If the first digit is a 0, or if
405there are three octal digits, it is considered an octal escape. Otherwise, it is
406a group reference. As for string literals, octal escapes are always at most
407three digits in length.
408
Georg Brandl8ec7f652007-08-15 14:28:01 +0000409
Georg Brandl8ec7f652007-08-15 14:28:01 +0000410.. _contents-of-module-re:
411
412Module Contents
413---------------
414
415The module defines several functions, constants, and an exception. Some of the
416functions are simplified versions of the full featured methods for compiled
417regular expressions. Most non-trivial applications always use the compiled
418form.
419
420
Eli Benderskyeb711382011-11-14 01:02:20 +0200421.. function:: compile(pattern, flags=0)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000422
Georg Brandlba2e5192007-09-27 06:26:58 +0000423 Compile a regular expression pattern into a regular expression object, which
424 can be used for matching using its :func:`match` and :func:`search` methods,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000425 described below.
426
427 The expression's behaviour can be modified by specifying a *flags* value.
428 Values can be any of the following variables, combined using bitwise OR (the
429 ``|`` operator).
430
431 The sequence ::
432
Gregory P. Smith0261e5d2009-03-02 04:53:24 +0000433 prog = re.compile(pattern)
434 result = prog.match(string)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000435
436 is equivalent to ::
437
Gregory P. Smith0261e5d2009-03-02 04:53:24 +0000438 result = re.match(pattern, string)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000439
Georg Brandl74f8fc02009-07-26 13:36:39 +0000440 but using :func:`re.compile` and saving the resulting regular expression
441 object for reuse is more efficient when the expression will be used several
442 times in a single program.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000443
Gregory P. Smith0261e5d2009-03-02 04:53:24 +0000444 .. note::
445
446 The compiled versions of the most recent patterns passed to
447 :func:`re.match`, :func:`re.search` or :func:`re.compile` are cached, so
448 programs that use only a few regular expressions at a time needn't worry
449 about compiling regular expressions.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000450
451
Sandro Tosie827c132012-01-01 12:52:24 +0100452.. data:: DEBUG
453
454 Display debug information about compiled expression.
455
456
Georg Brandl8ec7f652007-08-15 14:28:01 +0000457.. data:: I
458 IGNORECASE
459
460 Perform case-insensitive matching; expressions like ``[A-Z]`` will match
461 lowercase letters, too. This is not affected by the current locale.
462
463
464.. data:: L
465 LOCALE
466
Georg Brandlba2e5192007-09-27 06:26:58 +0000467 Make ``\w``, ``\W``, ``\b``, ``\B``, ``\s`` and ``\S`` dependent on the
468 current locale.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000469
470
471.. data:: M
472 MULTILINE
473
474 When specified, the pattern character ``'^'`` matches at the beginning of the
475 string and at the beginning of each line (immediately following each newline);
476 and the pattern character ``'$'`` matches at the end of the string and at the
477 end of each line (immediately preceding each newline). By default, ``'^'``
478 matches only at the beginning of the string, and ``'$'`` only at the end of the
479 string and immediately before the newline (if any) at the end of the string.
480
481
482.. data:: S
483 DOTALL
484
485 Make the ``'.'`` special character match any character at all, including a
486 newline; without this flag, ``'.'`` will match anything *except* a newline.
487
488
489.. data:: U
490 UNICODE
491
492 Make ``\w``, ``\W``, ``\b``, ``\B``, ``\d``, ``\D``, ``\s`` and ``\S`` dependent
493 on the Unicode character properties database.
494
495 .. versionadded:: 2.0
496
497
498.. data:: X
499 VERBOSE
500
501 This flag allows you to write regular expressions that look nicer. Whitespace
502 within the pattern is ignored, except when in a character class or preceded by
503 an unescaped backslash, and, when a line contains a ``'#'`` neither in a
504 character class or preceded by an unescaped backslash, all characters from the
505 leftmost such ``'#'`` through the end of the line are ignored.
506
Georg Brandlb8df1562007-12-05 18:30:48 +0000507 That means that the two following regular expression objects that match a
508 decimal number are functionally equal::
509
510 a = re.compile(r"""\d + # the integral part
511 \. # the decimal point
512 \d * # some fractional digits""", re.X)
513 b = re.compile(r"\d+\.\d*")
Georg Brandl8ec7f652007-08-15 14:28:01 +0000514
515
Eli Benderskyeb711382011-11-14 01:02:20 +0200516.. function:: search(pattern, string, flags=0)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000517
518 Scan through *string* looking for a location where the regular expression
519 *pattern* produces a match, and return a corresponding :class:`MatchObject`
520 instance. Return ``None`` if no position in the string matches the pattern; note
521 that this is different from finding a zero-length match at some point in the
522 string.
523
524
Eli Benderskyeb711382011-11-14 01:02:20 +0200525.. function:: match(pattern, string, flags=0)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000526
527 If zero or more characters at the beginning of *string* match the regular
528 expression *pattern*, return a corresponding :class:`MatchObject` instance.
529 Return ``None`` if the string does not match the pattern; note that this is
530 different from a zero-length match.
531
Ezio Melottid9de93e2012-02-29 13:37:07 +0200532 Note that even in :const:`MULTILINE` mode, :func:`re.match` will only match
533 at the beginning of the string and not at the beginning of each line.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000534
Ezio Melottid9de93e2012-02-29 13:37:07 +0200535 If you want to locate a match anywhere in *string*, use :func:`search`
536 instead (see also :ref:`search-vs-match`).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000537
538
Eli Benderskyeb711382011-11-14 01:02:20 +0200539.. function:: split(pattern, string, maxsplit=0, flags=0)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000540
541 Split *string* by the occurrences of *pattern*. If capturing parentheses are
542 used in *pattern*, then the text of all groups in the pattern are also returned
543 as part of the resulting list. If *maxsplit* is nonzero, at most *maxsplit*
544 splits occur, and the remainder of the string is returned as the final element
545 of the list. (Incompatibility note: in the original Python 1.5 release,
Georg Brandl6199e322008-03-22 12:04:26 +0000546 *maxsplit* was ignored. This has been fixed in later releases.)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000547
548 >>> re.split('\W+', 'Words, words, words.')
549 ['Words', 'words', 'words', '']
550 >>> re.split('(\W+)', 'Words, words, words.')
551 ['Words', ', ', 'words', ', ', 'words', '.', '']
552 >>> re.split('\W+', 'Words, words, words.', 1)
553 ['Words', 'words, words.']
Gregory P. Smithae91d092009-03-02 05:13:57 +0000554 >>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
555 ['0', '3', '9']
Georg Brandl8ec7f652007-08-15 14:28:01 +0000556
Georg Brandl70992c32008-03-06 07:19:15 +0000557 If there are capturing groups in the separator and it matches at the start of
558 the string, the result will start with an empty string. The same holds for
Georg Brandl6199e322008-03-22 12:04:26 +0000559 the end of the string:
Georg Brandl70992c32008-03-06 07:19:15 +0000560
561 >>> re.split('(\W+)', '...words, words...')
562 ['', '...', 'words', ', ', 'words', '...', '']
563
564 That way, separator components are always found at the same relative
565 indices within the result list (e.g., if there's one capturing group
566 in the separator, the 0th, the 2nd and so forth).
567
Skip Montanaro222907d2007-09-01 17:40:03 +0000568 Note that *split* will never split a string on an empty pattern match.
Georg Brandl6199e322008-03-22 12:04:26 +0000569 For example:
Skip Montanaro222907d2007-09-01 17:40:03 +0000570
571 >>> re.split('x*', 'foo')
572 ['foo']
573 >>> re.split("(?m)^$", "foo\n\nbar\n")
574 ['foo\n\nbar\n']
Georg Brandl8ec7f652007-08-15 14:28:01 +0000575
Ezio Melotti1e5d3182010-11-26 09:30:44 +0000576 .. versionchanged:: 2.7
Gregory P. Smithae91d092009-03-02 05:13:57 +0000577 Added the optional flags argument.
578
Georg Brandl70992c32008-03-06 07:19:15 +0000579
Eli Benderskyeb711382011-11-14 01:02:20 +0200580.. function:: findall(pattern, string, flags=0)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000581
Georg Brandlba2e5192007-09-27 06:26:58 +0000582 Return all non-overlapping matches of *pattern* in *string*, as a list of
Georg Brandlb46d6ff2008-07-19 13:48:44 +0000583 strings. The *string* is scanned left-to-right, and matches are returned in
584 the order found. If one or more groups are present in the pattern, return a
585 list of groups; this will be a list of tuples if the pattern has more than
586 one group. Empty matches are included in the result unless they touch the
587 beginning of another match.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000588
589 .. versionadded:: 1.5.2
590
591 .. versionchanged:: 2.4
592 Added the optional flags argument.
593
594
Eli Benderskyeb711382011-11-14 01:02:20 +0200595.. function:: finditer(pattern, string, flags=0)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000596
Georg Brandle7a09902007-10-21 12:10:28 +0000597 Return an :term:`iterator` yielding :class:`MatchObject` instances over all
Georg Brandlb46d6ff2008-07-19 13:48:44 +0000598 non-overlapping matches for the RE *pattern* in *string*. The *string* is
599 scanned left-to-right, and matches are returned in the order found. Empty
600 matches are included in the result unless they touch the beginning of another
601 match.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000602
603 .. versionadded:: 2.2
604
605 .. versionchanged:: 2.4
606 Added the optional flags argument.
607
608
Eli Benderskyeb711382011-11-14 01:02:20 +0200609.. function:: sub(pattern, repl, string, count=0, flags=0)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000610
611 Return the string obtained by replacing the leftmost non-overlapping occurrences
612 of *pattern* in *string* by the replacement *repl*. If the pattern isn't found,
613 *string* is returned unchanged. *repl* can be a string or a function; if it is
614 a string, any backslash escapes in it are processed. That is, ``\n`` is
Sandro Tosia7eb3c82011-08-19 22:54:33 +0200615 converted to a single newline character, ``\r`` is converted to a carriage return, and
Georg Brandl8ec7f652007-08-15 14:28:01 +0000616 so forth. Unknown escapes such as ``\j`` are left alone. Backreferences, such
617 as ``\6``, are replaced with the substring matched by group 6 in the pattern.
Georg Brandl6199e322008-03-22 12:04:26 +0000618 For example:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000619
620 >>> re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',
621 ... r'static PyObject*\npy_\1(void)\n{',
622 ... 'def myfunc():')
623 'static PyObject*\npy_myfunc(void)\n{'
624
625 If *repl* is a function, it is called for every non-overlapping occurrence of
626 *pattern*. The function takes a single match object argument, and returns the
Georg Brandl6199e322008-03-22 12:04:26 +0000627 replacement string. For example:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000628
629 >>> def dashrepl(matchobj):
630 ... if matchobj.group(0) == '-': return ' '
631 ... else: return '-'
632 >>> re.sub('-{1,2}', dashrepl, 'pro----gram-files')
633 'pro--gram files'
Gregory P. Smithae91d092009-03-02 05:13:57 +0000634 >>> re.sub(r'\sAND\s', ' & ', 'Baked Beans And Spam', flags=re.IGNORECASE)
635 'Baked Beans & Spam'
Georg Brandl8ec7f652007-08-15 14:28:01 +0000636
Georg Brandl04fd3242009-08-13 07:48:05 +0000637 The pattern may be a string or an RE object.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000638
639 The optional argument *count* is the maximum number of pattern occurrences to be
640 replaced; *count* must be a non-negative integer. If omitted or zero, all
641 occurrences will be replaced. Empty matches for the pattern are replaced only
642 when not adjacent to a previous match, so ``sub('x*', '-', 'abc')`` returns
643 ``'-a-b-c-'``.
644
645 In addition to character escapes and backreferences as described above,
646 ``\g<name>`` will use the substring matched by the group named ``name``, as
647 defined by the ``(?P<name>...)`` syntax. ``\g<number>`` uses the corresponding
648 group number; ``\g<2>`` is therefore equivalent to ``\2``, but isn't ambiguous
649 in a replacement such as ``\g<2>0``. ``\20`` would be interpreted as a
650 reference to group 20, not a reference to group 2 followed by the literal
651 character ``'0'``. The backreference ``\g<0>`` substitutes in the entire
652 substring matched by the RE.
653
Ezio Melotti1e5d3182010-11-26 09:30:44 +0000654 .. versionchanged:: 2.7
Gregory P. Smithae91d092009-03-02 05:13:57 +0000655 Added the optional flags argument.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000656
Gregory P. Smithae91d092009-03-02 05:13:57 +0000657
Eli Benderskyeb711382011-11-14 01:02:20 +0200658.. function:: subn(pattern, repl, string, count=0, flags=0)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000659
660 Perform the same operation as :func:`sub`, but return a tuple ``(new_string,
661 number_of_subs_made)``.
662
Ezio Melotti1e5d3182010-11-26 09:30:44 +0000663 .. versionchanged:: 2.7
Gregory P. Smithae91d092009-03-02 05:13:57 +0000664 Added the optional flags argument.
665
Georg Brandl8ec7f652007-08-15 14:28:01 +0000666
667.. function:: escape(string)
668
669 Return *string* with all non-alphanumerics backslashed; this is useful if you
670 want to match an arbitrary literal string that may have regular expression
671 metacharacters in it.
672
673
R. David Murraya63f9b62010-07-10 14:25:18 +0000674.. function:: purge()
675
676 Clear the regular expression cache.
677
678
Georg Brandl8ec7f652007-08-15 14:28:01 +0000679.. exception:: error
680
681 Exception raised when a string passed to one of the functions here is not a
682 valid regular expression (for example, it might contain unmatched parentheses)
683 or when some other error occurs during compilation or matching. It is never an
684 error if a string contains no match for a pattern.
685
686
687.. _re-objects:
688
689Regular Expression Objects
690--------------------------
691
Brian Curtinfbe51992010-03-25 23:48:54 +0000692.. class:: RegexObject
693
694 The :class:`RegexObject` class supports the following methods and attributes:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000695
Georg Brandlb1a14052010-06-01 07:25:23 +0000696 .. method:: RegexObject.search(string[, pos[, endpos]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000697
Georg Brandlb1a14052010-06-01 07:25:23 +0000698 Scan through *string* looking for a location where this regular expression
699 produces a match, and return a corresponding :class:`MatchObject` instance.
700 Return ``None`` if no position in the string matches the pattern; note that this
701 is different from finding a zero-length match at some point in the string.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000702
Brian Curtinfbe51992010-03-25 23:48:54 +0000703 The optional second parameter *pos* gives an index in the string where the
704 search is to start; it defaults to ``0``. This is not completely equivalent to
705 slicing the string; the ``'^'`` pattern character matches at the real beginning
706 of the string and at positions just after a newline, but not necessarily at the
707 index where the search is to start.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000708
Brian Curtinfbe51992010-03-25 23:48:54 +0000709 The optional parameter *endpos* limits how far the string will be searched; it
710 will be as if the string is *endpos* characters long, so only the characters
711 from *pos* to ``endpos - 1`` will be searched for a match. If *endpos* is less
712 than *pos*, no match will be found, otherwise, if *rx* is a compiled regular
Georg Brandlb1a14052010-06-01 07:25:23 +0000713 expression object, ``rx.search(string, 0, 50)`` is equivalent to
714 ``rx.search(string[:50], 0)``.
Georg Brandlb8df1562007-12-05 18:30:48 +0000715
Georg Brandlb1a14052010-06-01 07:25:23 +0000716 >>> pattern = re.compile("d")
717 >>> pattern.search("dog") # Match at index 0
718 <_sre.SRE_Match object at ...>
719 >>> pattern.search("dog", 1) # No match; search doesn't include the "d"
Georg Brandl8ec7f652007-08-15 14:28:01 +0000720
721
Georg Brandlb1a14052010-06-01 07:25:23 +0000722 .. method:: RegexObject.match(string[, pos[, endpos]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000723
Georg Brandlb1a14052010-06-01 07:25:23 +0000724 If zero or more characters at the *beginning* of *string* match this regular
725 expression, return a corresponding :class:`MatchObject` instance. Return
726 ``None`` if the string does not match the pattern; note that this is different
727 from a zero-length match.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000728
Brian Curtinfbe51992010-03-25 23:48:54 +0000729 The optional *pos* and *endpos* parameters have the same meaning as for the
Georg Brandlb1a14052010-06-01 07:25:23 +0000730 :meth:`~RegexObject.search` method.
731
Georg Brandlb1a14052010-06-01 07:25:23 +0000732 >>> pattern = re.compile("o")
733 >>> pattern.match("dog") # No match as "o" is not at the start of "dog".
734 >>> pattern.match("dog", 1) # Match as "o" is the 2nd character of "dog".
735 <_sre.SRE_Match object at ...>
Georg Brandl8ec7f652007-08-15 14:28:01 +0000736
Ezio Melottid9de93e2012-02-29 13:37:07 +0200737 If you want to locate a match anywhere in *string*, use
738 :meth:`~RegexObject.search` instead (see also :ref:`search-vs-match`).
739
Georg Brandl8ec7f652007-08-15 14:28:01 +0000740
Eli Benderskyeb711382011-11-14 01:02:20 +0200741 .. method:: RegexObject.split(string, maxsplit=0)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000742
Brian Curtinfbe51992010-03-25 23:48:54 +0000743 Identical to the :func:`split` function, using the compiled pattern.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000744
745
Brian Curtinfbe51992010-03-25 23:48:54 +0000746 .. method:: RegexObject.findall(string[, pos[, endpos]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000747
Georg Brandlf93ce0c2010-05-22 08:17:23 +0000748 Similar to the :func:`findall` function, using the compiled pattern, but
749 also accepts optional *pos* and *endpos* parameters that limit the search
750 region like for :meth:`match`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000751
752
Brian Curtinfbe51992010-03-25 23:48:54 +0000753 .. method:: RegexObject.finditer(string[, pos[, endpos]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000754
Georg Brandlf93ce0c2010-05-22 08:17:23 +0000755 Similar to the :func:`finditer` function, using the compiled pattern, but
756 also accepts optional *pos* and *endpos* parameters that limit the search
757 region like for :meth:`match`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000758
759
Eli Benderskyeb711382011-11-14 01:02:20 +0200760 .. method:: RegexObject.sub(repl, string, count=0)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000761
Brian Curtinfbe51992010-03-25 23:48:54 +0000762 Identical to the :func:`sub` function, using the compiled pattern.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000763
764
Eli Benderskyeb711382011-11-14 01:02:20 +0200765 .. method:: RegexObject.subn(repl, string, count=0)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000766
Brian Curtinfbe51992010-03-25 23:48:54 +0000767 Identical to the :func:`subn` function, using the compiled pattern.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000768
769
Brian Curtinfbe51992010-03-25 23:48:54 +0000770 .. attribute:: RegexObject.flags
Georg Brandl8ec7f652007-08-15 14:28:01 +0000771
Georg Brandl94a10572012-03-17 17:31:32 +0100772 The regex matching flags. This is a combination of the flags given to
773 :func:`.compile` and any ``(?...)`` inline flags in the pattern.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000774
775
Brian Curtinfbe51992010-03-25 23:48:54 +0000776 .. attribute:: RegexObject.groups
Georg Brandlb46f0d72008-12-05 07:49:49 +0000777
Brian Curtinfbe51992010-03-25 23:48:54 +0000778 The number of capturing groups in the pattern.
Georg Brandlb46f0d72008-12-05 07:49:49 +0000779
780
Brian Curtinfbe51992010-03-25 23:48:54 +0000781 .. attribute:: RegexObject.groupindex
Georg Brandl8ec7f652007-08-15 14:28:01 +0000782
Brian Curtinfbe51992010-03-25 23:48:54 +0000783 A dictionary mapping any symbolic group names defined by ``(?P<id>)`` to group
784 numbers. The dictionary is empty if no symbolic groups were used in the
785 pattern.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000786
787
Brian Curtinfbe51992010-03-25 23:48:54 +0000788 .. attribute:: RegexObject.pattern
Georg Brandl8ec7f652007-08-15 14:28:01 +0000789
Brian Curtinfbe51992010-03-25 23:48:54 +0000790 The pattern string from which the RE object was compiled.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000791
792
793.. _match-objects:
794
795Match Objects
796-------------
797
Brian Curtinfbe51992010-03-25 23:48:54 +0000798.. class:: MatchObject
799
800 Match Objects always have a boolean value of :const:`True`, so that you can test
801 whether e.g. :func:`match` resulted in a match with a simple if statement. They
802 support the following methods and attributes:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000803
804
Brian Curtinfbe51992010-03-25 23:48:54 +0000805 .. method:: MatchObject.expand(template)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000806
Brian Curtinfbe51992010-03-25 23:48:54 +0000807 Return the string obtained by doing backslash substitution on the template
808 string *template*, as done by the :meth:`~RegexObject.sub` method. Escapes
809 such as ``\n`` are converted to the appropriate characters, and numeric
810 backreferences (``\1``, ``\2``) and named backreferences (``\g<1>``,
811 ``\g<name>``) are replaced by the contents of the corresponding group.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000812
813
Brian Curtinfbe51992010-03-25 23:48:54 +0000814 .. method:: MatchObject.group([group1, ...])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000815
Brian Curtinfbe51992010-03-25 23:48:54 +0000816 Returns one or more subgroups of the match. If there is a single argument, the
817 result is a single string; if there are multiple arguments, the result is a
818 tuple with one item per argument. Without arguments, *group1* defaults to zero
819 (the whole match is returned). If a *groupN* argument is zero, the corresponding
820 return value is the entire matching string; if it is in the inclusive range
821 [1..99], it is the string matching the corresponding parenthesized group. If a
822 group number is negative or larger than the number of groups defined in the
823 pattern, an :exc:`IndexError` exception is raised. If a group is contained in a
824 part of the pattern that did not match, the corresponding result is ``None``.
825 If a group is contained in a part of the pattern that matched multiple times,
826 the last match is returned.
Georg Brandlb8df1562007-12-05 18:30:48 +0000827
Brian Curtinfbe51992010-03-25 23:48:54 +0000828 >>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
829 >>> m.group(0) # The entire match
830 'Isaac Newton'
831 >>> m.group(1) # The first parenthesized subgroup.
832 'Isaac'
833 >>> m.group(2) # The second parenthesized subgroup.
834 'Newton'
835 >>> m.group(1, 2) # Multiple arguments give us a tuple.
836 ('Isaac', 'Newton')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000837
Brian Curtinfbe51992010-03-25 23:48:54 +0000838 If the regular expression uses the ``(?P<name>...)`` syntax, the *groupN*
839 arguments may also be strings identifying groups by their group name. If a
840 string argument is not used as a group name in the pattern, an :exc:`IndexError`
841 exception is raised.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000842
Brian Curtinfbe51992010-03-25 23:48:54 +0000843 A moderately complicated example:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000844
Brian Curtinfbe51992010-03-25 23:48:54 +0000845 >>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds")
846 >>> m.group('first_name')
847 'Malcolm'
848 >>> m.group('last_name')
849 'Reynolds'
Georg Brandl8ec7f652007-08-15 14:28:01 +0000850
Brian Curtinfbe51992010-03-25 23:48:54 +0000851 Named groups can also be referred to by their index:
Georg Brandlb8df1562007-12-05 18:30:48 +0000852
Brian Curtinfbe51992010-03-25 23:48:54 +0000853 >>> m.group(1)
854 'Malcolm'
855 >>> m.group(2)
856 'Reynolds'
Georg Brandlb8df1562007-12-05 18:30:48 +0000857
Brian Curtinfbe51992010-03-25 23:48:54 +0000858 If a group matches multiple times, only the last match is accessible:
Georg Brandl6199e322008-03-22 12:04:26 +0000859
Brian Curtinfbe51992010-03-25 23:48:54 +0000860 >>> m = re.match(r"(..)+", "a1b2c3") # Matches 3 times.
861 >>> m.group(1) # Returns only the last match.
862 'c3'
Georg Brandl8ec7f652007-08-15 14:28:01 +0000863
864
Brian Curtinfbe51992010-03-25 23:48:54 +0000865 .. method:: MatchObject.groups([default])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000866
Brian Curtinfbe51992010-03-25 23:48:54 +0000867 Return a tuple containing all the subgroups of the match, from 1 up to however
868 many groups are in the pattern. The *default* argument is used for groups that
869 did not participate in the match; it defaults to ``None``. (Incompatibility
870 note: in the original Python 1.5 release, if the tuple was one element long, a
871 string would be returned instead. In later versions (from 1.5.1 on), a
872 singleton tuple is returned in such cases.)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000873
Brian Curtinfbe51992010-03-25 23:48:54 +0000874 For example:
Georg Brandlb8df1562007-12-05 18:30:48 +0000875
Brian Curtinfbe51992010-03-25 23:48:54 +0000876 >>> m = re.match(r"(\d+)\.(\d+)", "24.1632")
877 >>> m.groups()
878 ('24', '1632')
Georg Brandlb8df1562007-12-05 18:30:48 +0000879
Brian Curtinfbe51992010-03-25 23:48:54 +0000880 If we make the decimal place and everything after it optional, not all groups
881 might participate in the match. These groups will default to ``None`` unless
882 the *default* argument is given:
Georg Brandlb8df1562007-12-05 18:30:48 +0000883
Brian Curtinfbe51992010-03-25 23:48:54 +0000884 >>> m = re.match(r"(\d+)\.?(\d+)?", "24")
885 >>> m.groups() # Second group defaults to None.
886 ('24', None)
887 >>> m.groups('0') # Now, the second group defaults to '0'.
888 ('24', '0')
Georg Brandlb8df1562007-12-05 18:30:48 +0000889
Georg Brandl8ec7f652007-08-15 14:28:01 +0000890
Brian Curtinfbe51992010-03-25 23:48:54 +0000891 .. method:: MatchObject.groupdict([default])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000892
Brian Curtinfbe51992010-03-25 23:48:54 +0000893 Return a dictionary containing all the *named* subgroups of the match, keyed by
894 the subgroup name. The *default* argument is used for groups that did not
895 participate in the match; it defaults to ``None``. For example:
Georg Brandlb8df1562007-12-05 18:30:48 +0000896
Brian Curtinfbe51992010-03-25 23:48:54 +0000897 >>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds")
898 >>> m.groupdict()
899 {'first_name': 'Malcolm', 'last_name': 'Reynolds'}
Georg Brandl8ec7f652007-08-15 14:28:01 +0000900
901
Brian Curtinfbe51992010-03-25 23:48:54 +0000902 .. method:: MatchObject.start([group])
903 MatchObject.end([group])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000904
Brian Curtinfbe51992010-03-25 23:48:54 +0000905 Return the indices of the start and end of the substring matched by *group*;
906 *group* defaults to zero (meaning the whole matched substring). Return ``-1`` if
907 *group* exists but did not contribute to the match. For a match object *m*, and
908 a group *g* that did contribute to the match, the substring matched by group *g*
909 (equivalent to ``m.group(g)``) is ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000910
Brian Curtinfbe51992010-03-25 23:48:54 +0000911 m.string[m.start(g):m.end(g)]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000912
Brian Curtinfbe51992010-03-25 23:48:54 +0000913 Note that ``m.start(group)`` will equal ``m.end(group)`` if *group* matched a
914 null string. For example, after ``m = re.search('b(c?)', 'cba')``,
915 ``m.start(0)`` is 1, ``m.end(0)`` is 2, ``m.start(1)`` and ``m.end(1)`` are both
916 2, and ``m.start(2)`` raises an :exc:`IndexError` exception.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000917
Brian Curtinfbe51992010-03-25 23:48:54 +0000918 An example that will remove *remove_this* from email addresses:
Georg Brandlb8df1562007-12-05 18:30:48 +0000919
Brian Curtinfbe51992010-03-25 23:48:54 +0000920 >>> email = "tony@tiremove_thisger.net"
921 >>> m = re.search("remove_this", email)
922 >>> email[:m.start()] + email[m.end():]
923 'tony@tiger.net'
Georg Brandlb8df1562007-12-05 18:30:48 +0000924
Georg Brandl8ec7f652007-08-15 14:28:01 +0000925
Brian Curtinfbe51992010-03-25 23:48:54 +0000926 .. method:: MatchObject.span([group])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000927
Brian Curtinfbe51992010-03-25 23:48:54 +0000928 For :class:`MatchObject` *m*, return the 2-tuple ``(m.start(group),
929 m.end(group))``. Note that if *group* did not contribute to the match, this is
930 ``(-1, -1)``. *group* defaults to zero, the entire match.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000931
932
Brian Curtinfbe51992010-03-25 23:48:54 +0000933 .. attribute:: MatchObject.pos
Georg Brandl8ec7f652007-08-15 14:28:01 +0000934
Brian Curtinfbe51992010-03-25 23:48:54 +0000935 The value of *pos* which was passed to the :meth:`~RegexObject.search` or
936 :meth:`~RegexObject.match` method of the :class:`RegexObject`. This is the
937 index into the string at which the RE engine started looking for a match.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000938
939
Brian Curtinfbe51992010-03-25 23:48:54 +0000940 .. attribute:: MatchObject.endpos
Georg Brandl8ec7f652007-08-15 14:28:01 +0000941
Brian Curtinfbe51992010-03-25 23:48:54 +0000942 The value of *endpos* which was passed to the :meth:`~RegexObject.search` or
943 :meth:`~RegexObject.match` method of the :class:`RegexObject`. This is the
944 index into the string beyond which the RE engine will not go.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000945
946
Brian Curtinfbe51992010-03-25 23:48:54 +0000947 .. attribute:: MatchObject.lastindex
Georg Brandl8ec7f652007-08-15 14:28:01 +0000948
Brian Curtinfbe51992010-03-25 23:48:54 +0000949 The integer index of the last matched capturing group, or ``None`` if no group
950 was matched at all. For example, the expressions ``(a)b``, ``((a)(b))``, and
951 ``((ab))`` will have ``lastindex == 1`` if applied to the string ``'ab'``, while
952 the expression ``(a)(b)`` will have ``lastindex == 2``, if applied to the same
953 string.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000954
955
Brian Curtinfbe51992010-03-25 23:48:54 +0000956 .. attribute:: MatchObject.lastgroup
Georg Brandl8ec7f652007-08-15 14:28:01 +0000957
Brian Curtinfbe51992010-03-25 23:48:54 +0000958 The name of the last matched capturing group, or ``None`` if the group didn't
959 have a name, or if no group was matched at all.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000960
961
Brian Curtinfbe51992010-03-25 23:48:54 +0000962 .. attribute:: MatchObject.re
Georg Brandl8ec7f652007-08-15 14:28:01 +0000963
Brian Curtinfbe51992010-03-25 23:48:54 +0000964 The regular expression object whose :meth:`~RegexObject.match` or
965 :meth:`~RegexObject.search` method produced this :class:`MatchObject`
966 instance.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000967
968
Brian Curtinfbe51992010-03-25 23:48:54 +0000969 .. attribute:: MatchObject.string
Georg Brandl8ec7f652007-08-15 14:28:01 +0000970
Brian Curtinfbe51992010-03-25 23:48:54 +0000971 The string passed to :meth:`~RegexObject.match` or
972 :meth:`~RegexObject.search`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000973
974
975Examples
976--------
977
Georg Brandlb8df1562007-12-05 18:30:48 +0000978
979Checking For a Pair
980^^^^^^^^^^^^^^^^^^^
981
982In this example, we'll use the following helper function to display match
Georg Brandl6199e322008-03-22 12:04:26 +0000983objects a little more gracefully:
984
Georg Brandl838b4b02008-03-22 13:07:06 +0000985.. testcode::
Georg Brandlb8df1562007-12-05 18:30:48 +0000986
987 def displaymatch(match):
988 if match is None:
989 return None
990 return '<Match: %r, groups=%r>' % (match.group(), match.groups())
991
992Suppose you are writing a poker program where a player's hand is represented as
993a 5-character string with each character representing a card, "a" for ace, "k"
Ezio Melotti13c82d02011-12-17 01:17:17 +0200994for king, "q" for queen, "j" for jack, "t" for 10, and "2" through "9"
Georg Brandlb8df1562007-12-05 18:30:48 +0000995representing the card with that value.
996
Georg Brandl6199e322008-03-22 12:04:26 +0000997To see if a given string is a valid hand, one could do the following:
Georg Brandlb8df1562007-12-05 18:30:48 +0000998
Ezio Melotti13c82d02011-12-17 01:17:17 +0200999 >>> valid = re.compile(r"^[a2-9tjqk]{5}$")
1000 >>> displaymatch(valid.match("akt5q")) # Valid.
1001 "<Match: 'akt5q', groups=()>"
1002 >>> displaymatch(valid.match("akt5e")) # Invalid.
1003 >>> displaymatch(valid.match("akt")) # Invalid.
Georg Brandlb8df1562007-12-05 18:30:48 +00001004 >>> displaymatch(valid.match("727ak")) # Valid.
Georg Brandl6199e322008-03-22 12:04:26 +00001005 "<Match: '727ak', groups=()>"
Georg Brandlb8df1562007-12-05 18:30:48 +00001006
1007That last hand, ``"727ak"``, contained a pair, or two of the same valued cards.
Georg Brandl6199e322008-03-22 12:04:26 +00001008To match this with a regular expression, one could use backreferences as such:
Georg Brandlb8df1562007-12-05 18:30:48 +00001009
1010 >>> pair = re.compile(r".*(.).*\1")
1011 >>> displaymatch(pair.match("717ak")) # Pair of 7s.
Georg Brandl6199e322008-03-22 12:04:26 +00001012 "<Match: '717', groups=('7',)>"
Georg Brandlb8df1562007-12-05 18:30:48 +00001013 >>> displaymatch(pair.match("718ak")) # No pairs.
1014 >>> displaymatch(pair.match("354aa")) # Pair of aces.
Georg Brandl6199e322008-03-22 12:04:26 +00001015 "<Match: '354aa', groups=('a',)>"
Georg Brandlb8df1562007-12-05 18:30:48 +00001016
Georg Brandl74f8fc02009-07-26 13:36:39 +00001017To find out what card the pair consists of, one could use the
1018:meth:`~MatchObject.group` method of :class:`MatchObject` in the following
1019manner:
Georg Brandl6199e322008-03-22 12:04:26 +00001020
Georg Brandl838b4b02008-03-22 13:07:06 +00001021.. doctest::
Georg Brandlb8df1562007-12-05 18:30:48 +00001022
1023 >>> pair.match("717ak").group(1)
1024 '7'
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001025
Georg Brandlb8df1562007-12-05 18:30:48 +00001026 # Error because re.match() returns None, which doesn't have a group() method:
1027 >>> pair.match("718ak").group(1)
1028 Traceback (most recent call last):
1029 File "<pyshell#23>", line 1, in <module>
1030 re.match(r".*(.).*\1", "718ak").group(1)
1031 AttributeError: 'NoneType' object has no attribute 'group'
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001032
Georg Brandlb8df1562007-12-05 18:30:48 +00001033 >>> pair.match("354aa").group(1)
1034 'a'
1035
1036
1037Simulating scanf()
1038^^^^^^^^^^^^^^^^^^
Georg Brandl8ec7f652007-08-15 14:28:01 +00001039
1040.. index:: single: scanf()
1041
Sandro Tosi98ed08f2012-01-14 16:42:02 +01001042Python does not currently have an equivalent to :c:func:`scanf`. Regular
Georg Brandl8ec7f652007-08-15 14:28:01 +00001043expressions are generally more powerful, though also more verbose, than
Sandro Tosi98ed08f2012-01-14 16:42:02 +01001044:c:func:`scanf` format strings. The table below offers some more-or-less
1045equivalent mappings between :c:func:`scanf` format tokens and regular
Georg Brandl8ec7f652007-08-15 14:28:01 +00001046expressions.
1047
1048+--------------------------------+---------------------------------------------+
Sandro Tosi98ed08f2012-01-14 16:42:02 +01001049| :c:func:`scanf` Token | Regular Expression |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001050+================================+=============================================+
1051| ``%c`` | ``.`` |
1052+--------------------------------+---------------------------------------------+
1053| ``%5c`` | ``.{5}`` |
1054+--------------------------------+---------------------------------------------+
1055| ``%d`` | ``[-+]?\d+`` |
1056+--------------------------------+---------------------------------------------+
1057| ``%e``, ``%E``, ``%f``, ``%g`` | ``[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?`` |
1058+--------------------------------+---------------------------------------------+
1059| ``%i`` | ``[-+]?(0[xX][\dA-Fa-f]+|0[0-7]*|\d+)`` |
1060+--------------------------------+---------------------------------------------+
Ezio Melotti89500192012-04-29 11:47:28 +03001061| ``%o`` | ``[-+]?[0-7]+`` |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001062+--------------------------------+---------------------------------------------+
1063| ``%s`` | ``\S+`` |
1064+--------------------------------+---------------------------------------------+
1065| ``%u`` | ``\d+`` |
1066+--------------------------------+---------------------------------------------+
Ezio Melotti89500192012-04-29 11:47:28 +03001067| ``%x``, ``%X`` | ``[-+]?(0[xX])?[\dA-Fa-f]+`` |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001068+--------------------------------+---------------------------------------------+
1069
1070To extract the filename and numbers from a string like ::
1071
1072 /usr/sbin/sendmail - 0 errors, 4 warnings
1073
Sandro Tosi98ed08f2012-01-14 16:42:02 +01001074you would use a :c:func:`scanf` format like ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001075
1076 %s - %d errors, %d warnings
1077
1078The equivalent regular expression would be ::
1079
1080 (\S+) - (\d+) errors, (\d+) warnings
1081
Georg Brandlb8df1562007-12-05 18:30:48 +00001082
Ezio Melottid9de93e2012-02-29 13:37:07 +02001083.. _search-vs-match:
Georg Brandlb8df1562007-12-05 18:30:48 +00001084
1085search() vs. match()
1086^^^^^^^^^^^^^^^^^^^^
1087
Ezio Melottid9de93e2012-02-29 13:37:07 +02001088.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
Georg Brandlb8df1562007-12-05 18:30:48 +00001089
Ezio Melottid9de93e2012-02-29 13:37:07 +02001090Python offers two different primitive operations based on regular expressions:
1091:func:`re.match` checks for a match only at the beginning of the string, while
1092:func:`re.search` checks for a match anywhere in the string (this is what Perl
1093does by default).
1094
1095For example::
1096
1097 >>> re.match("c", "abcdef") # No match
1098 >>> re.search("c", "abcdef") # Match
Georg Brandl6199e322008-03-22 12:04:26 +00001099 <_sre.SRE_Match object at ...>
Georg Brandlb8df1562007-12-05 18:30:48 +00001100
Ezio Melottid9de93e2012-02-29 13:37:07 +02001101Regular expressions beginning with ``'^'`` can be used with :func:`search` to
1102restrict the match at the beginning of the string::
Georg Brandlb8df1562007-12-05 18:30:48 +00001103
Ezio Melottid9de93e2012-02-29 13:37:07 +02001104 >>> re.match("c", "abcdef") # No match
1105 >>> re.search("^c", "abcdef") # No match
1106 >>> re.search("^a", "abcdef") # Match
Georg Brandl6199e322008-03-22 12:04:26 +00001107 <_sre.SRE_Match object at ...>
Ezio Melottid9de93e2012-02-29 13:37:07 +02001108
1109Note however that in :const:`MULTILINE` mode :func:`match` only matches at the
1110beginning of the string, whereas using :func:`search` with a regular expression
1111beginning with ``'^'`` will match at the beginning of each line.
1112
1113 >>> re.match('X', 'A\nB\nX', re.MULTILINE) # No match
1114 >>> re.search('^X', 'A\nB\nX', re.MULTILINE) # Match
1115 <_sre.SRE_Match object at ...>
Georg Brandlb8df1562007-12-05 18:30:48 +00001116
1117
1118Making a Phonebook
1119^^^^^^^^^^^^^^^^^^
1120
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001121:func:`split` splits a string into a list delimited by the passed pattern. The
Georg Brandlb8df1562007-12-05 18:30:48 +00001122method is invaluable for converting textual data into data structures that can be
1123easily read and modified by Python as demonstrated in the following example that
1124creates a phonebook.
1125
Georg Brandld6b20dc2007-12-06 09:45:39 +00001126First, here is the input. Normally it may come from a file, here we are using
Georg Brandl6199e322008-03-22 12:04:26 +00001127triple-quoted string syntax:
Georg Brandlb8df1562007-12-05 18:30:48 +00001128
Georg Brandl5a607b02012-03-17 17:26:27 +01001129 >>> text = """Ross McFluff: 834.345.1254 155 Elm Street
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001130 ...
Georg Brandl6199e322008-03-22 12:04:26 +00001131 ... Ronald Heathmore: 892.345.3428 436 Finley Avenue
1132 ... Frank Burger: 925.541.7625 662 South Dogwood Way
1133 ...
1134 ...
1135 ... Heather Albrecht: 548.326.4584 919 Park Place"""
Georg Brandld6b20dc2007-12-06 09:45:39 +00001136
1137The entries are separated by one or more newlines. Now we convert the string
Georg Brandl6199e322008-03-22 12:04:26 +00001138into a list with each nonempty line having its own entry:
1139
Georg Brandl838b4b02008-03-22 13:07:06 +00001140.. doctest::
Georg Brandl6199e322008-03-22 12:04:26 +00001141 :options: +NORMALIZE_WHITESPACE
Georg Brandld6b20dc2007-12-06 09:45:39 +00001142
Georg Brandl5a607b02012-03-17 17:26:27 +01001143 >>> entries = re.split("\n+", text)
Georg Brandlb8df1562007-12-05 18:30:48 +00001144 >>> entries
Georg Brandl6199e322008-03-22 12:04:26 +00001145 ['Ross McFluff: 834.345.1254 155 Elm Street',
1146 'Ronald Heathmore: 892.345.3428 436 Finley Avenue',
1147 'Frank Burger: 925.541.7625 662 South Dogwood Way',
1148 'Heather Albrecht: 548.326.4584 919 Park Place']
Georg Brandlb8df1562007-12-05 18:30:48 +00001149
1150Finally, split each entry into a list with first name, last name, telephone
Georg Brandl907a7202008-02-22 12:31:45 +00001151number, and address. We use the ``maxsplit`` parameter of :func:`split`
Georg Brandl6199e322008-03-22 12:04:26 +00001152because the address has spaces, our splitting pattern, in it:
1153
Georg Brandl838b4b02008-03-22 13:07:06 +00001154.. doctest::
Georg Brandl6199e322008-03-22 12:04:26 +00001155 :options: +NORMALIZE_WHITESPACE
Georg Brandlb8df1562007-12-05 18:30:48 +00001156
Georg Brandld6b20dc2007-12-06 09:45:39 +00001157 >>> [re.split(":? ", entry, 3) for entry in entries]
Georg Brandlb8df1562007-12-05 18:30:48 +00001158 [['Ross', 'McFluff', '834.345.1254', '155 Elm Street'],
1159 ['Ronald', 'Heathmore', '892.345.3428', '436 Finley Avenue'],
1160 ['Frank', 'Burger', '925.541.7625', '662 South Dogwood Way'],
1161 ['Heather', 'Albrecht', '548.326.4584', '919 Park Place']]
1162
Georg Brandld6b20dc2007-12-06 09:45:39 +00001163The ``:?`` pattern matches the colon after the last name, so that it does not
Georg Brandl907a7202008-02-22 12:31:45 +00001164occur in the result list. With a ``maxsplit`` of ``4``, we could separate the
Georg Brandl6199e322008-03-22 12:04:26 +00001165house number from the street name:
1166
Georg Brandl838b4b02008-03-22 13:07:06 +00001167.. doctest::
Georg Brandl6199e322008-03-22 12:04:26 +00001168 :options: +NORMALIZE_WHITESPACE
Georg Brandlb8df1562007-12-05 18:30:48 +00001169
Georg Brandld6b20dc2007-12-06 09:45:39 +00001170 >>> [re.split(":? ", entry, 4) for entry in entries]
Georg Brandlb8df1562007-12-05 18:30:48 +00001171 [['Ross', 'McFluff', '834.345.1254', '155', 'Elm Street'],
1172 ['Ronald', 'Heathmore', '892.345.3428', '436', 'Finley Avenue'],
1173 ['Frank', 'Burger', '925.541.7625', '662', 'South Dogwood Way'],
1174 ['Heather', 'Albrecht', '548.326.4584', '919', 'Park Place']]
1175
1176
1177Text Munging
1178^^^^^^^^^^^^
1179
1180:func:`sub` replaces every occurrence of a pattern with a string or the
1181result of a function. This example demonstrates using :func:`sub` with
1182a function to "munge" text, or randomize the order of all the characters
1183in each word of a sentence except for the first and last characters::
1184
1185 >>> def repl(m):
1186 ... inner_word = list(m.group(2))
1187 ... random.shuffle(inner_word)
1188 ... return m.group(1) + "".join(inner_word) + m.group(3)
1189 >>> text = "Professor Abdolmalek, please report your absences promptly."
Georg Brandle0289a32010-08-01 21:44:38 +00001190 >>> re.sub(r"(\w)(\w+)(\w)", repl, text)
Georg Brandlb8df1562007-12-05 18:30:48 +00001191 'Poefsrosr Aealmlobdk, pslaee reorpt your abnseces plmrptoy.'
Georg Brandle0289a32010-08-01 21:44:38 +00001192 >>> re.sub(r"(\w)(\w+)(\w)", repl, text)
Georg Brandlb8df1562007-12-05 18:30:48 +00001193 'Pofsroser Aodlambelk, plasee reoprt yuor asnebces potlmrpy.'
1194
1195
1196Finding all Adverbs
1197^^^^^^^^^^^^^^^^^^^
1198
Georg Brandl907a7202008-02-22 12:31:45 +00001199:func:`findall` matches *all* occurrences of a pattern, not just the first
Georg Brandlb8df1562007-12-05 18:30:48 +00001200one as :func:`search` does. For example, if one was a writer and wanted to
1201find all of the adverbs in some text, he or she might use :func:`findall` in
Georg Brandl6199e322008-03-22 12:04:26 +00001202the following manner:
Georg Brandlb8df1562007-12-05 18:30:48 +00001203
1204 >>> text = "He was carefully disguised but captured quickly by police."
1205 >>> re.findall(r"\w+ly", text)
1206 ['carefully', 'quickly']
1207
1208
1209Finding all Adverbs and their Positions
1210^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1211
1212If one wants more information about all matches of a pattern than the matched
1213text, :func:`finditer` is useful as it provides instances of
1214:class:`MatchObject` instead of strings. Continuing with the previous example,
1215if one was a writer who wanted to find all of the adverbs *and their positions*
Georg Brandl6199e322008-03-22 12:04:26 +00001216in some text, he or she would use :func:`finditer` in the following manner:
Georg Brandlb8df1562007-12-05 18:30:48 +00001217
1218 >>> text = "He was carefully disguised but captured quickly by police."
1219 >>> for m in re.finditer(r"\w+ly", text):
Georg Brandl6199e322008-03-22 12:04:26 +00001220 ... print '%02d-%02d: %s' % (m.start(), m.end(), m.group(0))
Georg Brandlb8df1562007-12-05 18:30:48 +00001221 07-16: carefully
1222 40-47: quickly
1223
1224
1225Raw String Notation
1226^^^^^^^^^^^^^^^^^^^
1227
1228Raw string notation (``r"text"``) keeps regular expressions sane. Without it,
1229every backslash (``'\'``) in a regular expression would have to be prefixed with
1230another one to escape it. For example, the two following lines of code are
Georg Brandl6199e322008-03-22 12:04:26 +00001231functionally identical:
Georg Brandlb8df1562007-12-05 18:30:48 +00001232
1233 >>> re.match(r"\W(.)\1\W", " ff ")
Georg Brandl6199e322008-03-22 12:04:26 +00001234 <_sre.SRE_Match object at ...>
Georg Brandlb8df1562007-12-05 18:30:48 +00001235 >>> re.match("\\W(.)\\1\\W", " ff ")
Georg Brandl6199e322008-03-22 12:04:26 +00001236 <_sre.SRE_Match object at ...>
Georg Brandlb8df1562007-12-05 18:30:48 +00001237
1238When one wants to match a literal backslash, it must be escaped in the regular
1239expression. With raw string notation, this means ``r"\\"``. Without raw string
1240notation, one must use ``"\\\\"``, making the following lines of code
Georg Brandl6199e322008-03-22 12:04:26 +00001241functionally identical:
Georg Brandlb8df1562007-12-05 18:30:48 +00001242
1243 >>> re.match(r"\\", r"\\")
Georg Brandl6199e322008-03-22 12:04:26 +00001244 <_sre.SRE_Match object at ...>
Georg Brandlb8df1562007-12-05 18:30:48 +00001245 >>> re.match("\\\\", r"\\")
Georg Brandl6199e322008-03-22 12:04:26 +00001246 <_sre.SRE_Match object at ...>