Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1 | |
| 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 Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 11 | This module provides regular expression matching operations similar to |
| 12 | those found in Perl. Both patterns and strings to be searched can be |
Georg Brandl | 382edff | 2009-03-31 15:43:20 +0000 | [diff] [blame] | 13 | Unicode strings as well as 8-bit strings. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 14 | |
| 15 | Regular expressions use the backslash character (``'\'``) to indicate |
| 16 | special forms or to allow special characters to be used without invoking |
| 17 | their special meaning. This collides with Python's usage of the same |
| 18 | character for the same purpose in string literals; for example, to match |
| 19 | a literal backslash, one might have to write ``'\\\\'`` as the pattern |
| 20 | string, because the regular expression must be ``\\``, and each |
| 21 | backslash must be expressed as ``\\`` inside a regular Python string |
| 22 | literal. |
| 23 | |
| 24 | The solution is to use Python's raw string notation for regular expression |
| 25 | patterns; backslashes are not handled in any special way in a string literal |
| 26 | prefixed with ``'r'``. So ``r"\n"`` is a two-character string containing |
| 27 | ``'\'`` and ``'n'``, while ``"\n"`` is a one-character string containing a |
Georg Brandl | ba2e519 | 2007-09-27 06:26:58 +0000 | [diff] [blame] | 28 | newline. Usually patterns will be expressed in Python code using this raw |
| 29 | string notation. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 30 | |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 31 | It is important to note that most regular expression operations are available as |
| 32 | module-level functions and :class:`RegexObject` methods. The functions are |
| 33 | shortcuts that don't require you to compile a regex object first, but miss some |
| 34 | fine-tuning parameters. |
| 35 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 36 | .. seealso:: |
| 37 | |
| 38 | Mastering Regular Expressions |
| 39 | Book on regular expressions by Jeffrey Friedl, published by O'Reilly. The |
Georg Brandl | ba2e519 | 2007-09-27 06:26:58 +0000 | [diff] [blame] | 40 | second edition of the book no longer covers Python at all, but the first |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 41 | edition covered writing good regular expression patterns in great detail. |
| 42 | |
| 43 | |
| 44 | .. _re-syntax: |
| 45 | |
| 46 | Regular Expression Syntax |
| 47 | ------------------------- |
| 48 | |
| 49 | A regular expression (or RE) specifies a set of strings that matches it; the |
| 50 | functions in this module let you check if a particular string matches a given |
| 51 | regular expression (or if a given regular expression matches a particular |
| 52 | string, which comes down to the same thing). |
| 53 | |
| 54 | Regular expressions can be concatenated to form new regular expressions; if *A* |
| 55 | and *B* are both regular expressions, then *AB* is also a regular expression. |
| 56 | In general, if a string *p* matches *A* and another string *q* matches *B*, the |
| 57 | string *pq* will match AB. This holds unless *A* or *B* contain low precedence |
| 58 | operations; boundary conditions between *A* and *B*; or have numbered group |
| 59 | references. Thus, complex expressions can easily be constructed from simpler |
| 60 | primitive expressions like the ones described here. For details of the theory |
| 61 | and implementation of regular expressions, consult the Friedl book referenced |
| 62 | above, or almost any textbook about compiler construction. |
| 63 | |
| 64 | A brief explanation of the format of regular expressions follows. For further |
Georg Brandl | 1cf0522 | 2008-02-05 12:01:24 +0000 | [diff] [blame] | 65 | information and a gentler presentation, consult the :ref:`regex-howto`. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 66 | |
| 67 | Regular expressions can contain both special and ordinary characters. Most |
| 68 | ordinary characters, like ``'A'``, ``'a'``, or ``'0'``, are the simplest regular |
| 69 | expressions; they simply match themselves. You can concatenate ordinary |
| 70 | characters, so ``last`` matches the string ``'last'``. (In the rest of this |
| 71 | section, we'll write RE's in ``this special style``, usually without quotes, and |
| 72 | strings to be matched ``'in single quotes'``.) |
| 73 | |
| 74 | Some characters, like ``'|'`` or ``'('``, are special. Special |
| 75 | characters either stand for classes of ordinary characters, or affect |
| 76 | how the regular expressions around them are interpreted. Regular |
| 77 | expression pattern strings may not contain null bytes, but can specify |
| 78 | the null byte using the ``\number`` notation, e.g., ``'\x00'``. |
| 79 | |
| 80 | |
| 81 | The special characters are: |
| 82 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 83 | ``'.'`` |
| 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'Arc | d08a8eb | 2008-01-10 21:59:42 +0000 | [diff] [blame] | 97 | matches 'foo2' normally, but 'foo1' in :const:`MULTILINE` mode; searching for |
| 98 | a single ``$`` in ``'foo\n'`` will find two (empty) matches: one just before |
| 99 | the newline, and one at the end of the string. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 100 | |
| 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 Melotti | a195873 | 2011-10-20 19:31:08 +0300 | [diff] [blame] | 159 | Used to indicate a set of characters. In a set: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 160 | |
Ezio Melotti | a195873 | 2011-10-20 19:31:08 +0300 | [diff] [blame] | 161 | * Characters can be listed individually, e.g. ``[amk]`` will match ``'a'``, |
| 162 | ``'m'``, or ``'k'``. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 163 | |
Ezio Melotti | a195873 | 2011-10-20 19:31:08 +0300 | [diff] [blame] | 164 | * 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 Summerfield | 700a635 | 2008-05-31 13:05:34 +0000 | [diff] [blame] | 189 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 190 | ``'|'`` |
| 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 Brandl | 74f8fc0 | 2009-07-26 13:36:39 +0000 | [diff] [blame] | 225 | :func:`re.compile` function. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 226 | |
| 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 Brandl | 3b85b9b | 2010-11-26 08:20:18 +0000 | [diff] [blame] | 233 | A non-capturing version of regular parentheses. Matches whatever regular |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 234 | 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 Brandl | 5206086 | 2009-03-31 19:06:57 +0000 | [diff] [blame] | 240 | 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 Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 246 | |
| 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 Brandl | 5206086 | 2009-03-31 19:06:57 +0000 | [diff] [blame] | 249 | ``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 Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 252 | |
| 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 Brandl | 6199e32 | 2008-03-22 12:04:26 +0000 | [diff] [blame] | 278 | :func:`search` function rather than the :func:`match` function: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 279 | |
| 280 | >>> import re |
| 281 | >>> m = re.search('(?<=abc)def', 'abcdef') |
| 282 | >>> m.group(0) |
| 283 | 'def' |
| 284 | |
Georg Brandl | 6199e32 | 2008-03-22 12:04:26 +0000 | [diff] [blame] | 285 | This example looks for a word following a hyphen: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 286 | |
| 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 | |
| 307 | The special sequences consist of ``'\'`` and a character from the list below. |
| 308 | If the ordinary character is not on the list, then the resulting RE will match |
| 309 | the second character. For example, ``\$`` matches the character ``'$'``. |
| 310 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 311 | ``\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 Melotti | 38ae5b2 | 2012-02-29 11:40:00 +0200 | [diff] [blame] | 328 | 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 Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 335 | |
| 336 | ``\B`` |
| 337 | Matches the empty string, but only when it is *not* at the beginning or end of a |
Ezio Melotti | 38ae5b2 | 2012-02-29 11:40:00 +0200 | [diff] [blame] | 338 | 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 Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 341 | 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 Dickinson | fe67bd9 | 2009-07-28 20:35:03 +0000 | [diff] [blame] | 346 | whatever is classified as a decimal digit in the Unicode character properties |
| 347 | database. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 348 | |
| 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`` |
| 356 | When the :const:`LOCALE` and :const:`UNICODE` flags are not specified, matches |
| 357 | any whitespace character; this is equivalent to the set ``[ \t\n\r\f\v]``. With |
| 358 | :const:`LOCALE`, it will match this set plus whatever characters are defined as |
| 359 | space for the current locale. If :const:`UNICODE` is set, this will match the |
| 360 | characters ``[ \t\n\r\f\v]`` plus whatever is classified as space in the Unicode |
| 361 | character properties database. |
| 362 | |
| 363 | ``\S`` |
Senthil Kumaran | 15b6f3f | 2012-03-11 20:37:39 -0700 | [diff] [blame] | 364 | When the :const:`LOCALE` and :const:`UNICODE` flags are not specified, |
| 365 | matches any non-whitespace character; this is equivalent to the set ``[^ |
| 366 | \t\n\r\f\v]`` With :const:`LOCALE`, it will match the above set plus any |
| 367 | non-space character in the current locale. If :const:`UNICODE` is set, the |
| 368 | above set ``[^ \t\n\r\f\v]`` plus the characters not marked as space in the |
| 369 | Unicode character properties database. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 370 | |
| 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 Kumaran | 15b6f3f | 2012-03-11 20:37:39 -0700 | [diff] [blame] | 384 | this will match anything other than ``[0-9_]`` plus characters classied as |
| 385 | not alphanumeric in the Unicode character properties database. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 386 | |
| 387 | ``\Z`` |
| 388 | Matches only at the end of the string. |
| 389 | |
Senthil Kumaran | 15b6f3f | 2012-03-11 20:37:39 -0700 | [diff] [blame] | 390 | If both :const:`LOCALE` and :const:`UNICODE` flags are included for a |
| 391 | particular sequence, then :const:`LOCALE` flag takes effect first followed by |
| 392 | the :const:`UNICODE`. |
| 393 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 394 | Most of the standard escapes supported by Python string literals are also |
| 395 | accepted by the regular expression parser:: |
| 396 | |
| 397 | \a \b \f \n |
| 398 | \r \t \v \x |
| 399 | \\ |
| 400 | |
| 401 | Octal escapes are included in a limited form: If the first digit is a 0, or if |
| 402 | there are three octal digits, it is considered an octal escape. Otherwise, it is |
| 403 | a group reference. As for string literals, octal escapes are always at most |
| 404 | three digits in length. |
| 405 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 406 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 407 | .. _contents-of-module-re: |
| 408 | |
| 409 | Module Contents |
| 410 | --------------- |
| 411 | |
| 412 | The module defines several functions, constants, and an exception. Some of the |
| 413 | functions are simplified versions of the full featured methods for compiled |
| 414 | regular expressions. Most non-trivial applications always use the compiled |
| 415 | form. |
| 416 | |
| 417 | |
Eli Bendersky | eb71138 | 2011-11-14 01:02:20 +0200 | [diff] [blame] | 418 | .. function:: compile(pattern, flags=0) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 419 | |
Georg Brandl | ba2e519 | 2007-09-27 06:26:58 +0000 | [diff] [blame] | 420 | Compile a regular expression pattern into a regular expression object, which |
| 421 | can be used for matching using its :func:`match` and :func:`search` methods, |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 422 | described below. |
| 423 | |
| 424 | The expression's behaviour can be modified by specifying a *flags* value. |
| 425 | Values can be any of the following variables, combined using bitwise OR (the |
| 426 | ``|`` operator). |
| 427 | |
| 428 | The sequence :: |
| 429 | |
Gregory P. Smith | 0261e5d | 2009-03-02 04:53:24 +0000 | [diff] [blame] | 430 | prog = re.compile(pattern) |
| 431 | result = prog.match(string) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 432 | |
| 433 | is equivalent to :: |
| 434 | |
Gregory P. Smith | 0261e5d | 2009-03-02 04:53:24 +0000 | [diff] [blame] | 435 | result = re.match(pattern, string) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 436 | |
Georg Brandl | 74f8fc0 | 2009-07-26 13:36:39 +0000 | [diff] [blame] | 437 | but using :func:`re.compile` and saving the resulting regular expression |
| 438 | object for reuse is more efficient when the expression will be used several |
| 439 | times in a single program. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 440 | |
Gregory P. Smith | 0261e5d | 2009-03-02 04:53:24 +0000 | [diff] [blame] | 441 | .. note:: |
| 442 | |
| 443 | The compiled versions of the most recent patterns passed to |
| 444 | :func:`re.match`, :func:`re.search` or :func:`re.compile` are cached, so |
| 445 | programs that use only a few regular expressions at a time needn't worry |
| 446 | about compiling regular expressions. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 447 | |
| 448 | |
Sandro Tosi | e827c13 | 2012-01-01 12:52:24 +0100 | [diff] [blame] | 449 | .. data:: DEBUG |
| 450 | |
| 451 | Display debug information about compiled expression. |
| 452 | |
| 453 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 454 | .. data:: I |
| 455 | IGNORECASE |
| 456 | |
| 457 | Perform case-insensitive matching; expressions like ``[A-Z]`` will match |
| 458 | lowercase letters, too. This is not affected by the current locale. |
| 459 | |
| 460 | |
| 461 | .. data:: L |
| 462 | LOCALE |
| 463 | |
Georg Brandl | ba2e519 | 2007-09-27 06:26:58 +0000 | [diff] [blame] | 464 | Make ``\w``, ``\W``, ``\b``, ``\B``, ``\s`` and ``\S`` dependent on the |
| 465 | current locale. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 466 | |
| 467 | |
| 468 | .. data:: M |
| 469 | MULTILINE |
| 470 | |
| 471 | When specified, the pattern character ``'^'`` matches at the beginning of the |
| 472 | string and at the beginning of each line (immediately following each newline); |
| 473 | and the pattern character ``'$'`` matches at the end of the string and at the |
| 474 | end of each line (immediately preceding each newline). By default, ``'^'`` |
| 475 | matches only at the beginning of the string, and ``'$'`` only at the end of the |
| 476 | string and immediately before the newline (if any) at the end of the string. |
| 477 | |
| 478 | |
| 479 | .. data:: S |
| 480 | DOTALL |
| 481 | |
| 482 | Make the ``'.'`` special character match any character at all, including a |
| 483 | newline; without this flag, ``'.'`` will match anything *except* a newline. |
| 484 | |
| 485 | |
| 486 | .. data:: U |
| 487 | UNICODE |
| 488 | |
| 489 | Make ``\w``, ``\W``, ``\b``, ``\B``, ``\d``, ``\D``, ``\s`` and ``\S`` dependent |
| 490 | on the Unicode character properties database. |
| 491 | |
| 492 | .. versionadded:: 2.0 |
| 493 | |
| 494 | |
| 495 | .. data:: X |
| 496 | VERBOSE |
| 497 | |
| 498 | This flag allows you to write regular expressions that look nicer. Whitespace |
| 499 | within the pattern is ignored, except when in a character class or preceded by |
| 500 | an unescaped backslash, and, when a line contains a ``'#'`` neither in a |
| 501 | character class or preceded by an unescaped backslash, all characters from the |
| 502 | leftmost such ``'#'`` through the end of the line are ignored. |
| 503 | |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 504 | That means that the two following regular expression objects that match a |
| 505 | decimal number are functionally equal:: |
| 506 | |
| 507 | a = re.compile(r"""\d + # the integral part |
| 508 | \. # the decimal point |
| 509 | \d * # some fractional digits""", re.X) |
| 510 | b = re.compile(r"\d+\.\d*") |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 511 | |
| 512 | |
Eli Bendersky | eb71138 | 2011-11-14 01:02:20 +0200 | [diff] [blame] | 513 | .. function:: search(pattern, string, flags=0) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 514 | |
| 515 | Scan through *string* looking for a location where the regular expression |
| 516 | *pattern* produces a match, and return a corresponding :class:`MatchObject` |
| 517 | instance. Return ``None`` if no position in the string matches the pattern; note |
| 518 | that this is different from finding a zero-length match at some point in the |
| 519 | string. |
| 520 | |
| 521 | |
Eli Bendersky | eb71138 | 2011-11-14 01:02:20 +0200 | [diff] [blame] | 522 | .. function:: match(pattern, string, flags=0) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 523 | |
| 524 | If zero or more characters at the beginning of *string* match the regular |
| 525 | expression *pattern*, return a corresponding :class:`MatchObject` instance. |
| 526 | Return ``None`` if the string does not match the pattern; note that this is |
| 527 | different from a zero-length match. |
| 528 | |
Ezio Melotti | d9de93e | 2012-02-29 13:37:07 +0200 | [diff] [blame] | 529 | Note that even in :const:`MULTILINE` mode, :func:`re.match` will only match |
| 530 | at the beginning of the string and not at the beginning of each line. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 531 | |
Ezio Melotti | d9de93e | 2012-02-29 13:37:07 +0200 | [diff] [blame] | 532 | If you want to locate a match anywhere in *string*, use :func:`search` |
| 533 | instead (see also :ref:`search-vs-match`). |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 534 | |
| 535 | |
Eli Bendersky | eb71138 | 2011-11-14 01:02:20 +0200 | [diff] [blame] | 536 | .. function:: split(pattern, string, maxsplit=0, flags=0) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 537 | |
| 538 | Split *string* by the occurrences of *pattern*. If capturing parentheses are |
| 539 | used in *pattern*, then the text of all groups in the pattern are also returned |
| 540 | as part of the resulting list. If *maxsplit* is nonzero, at most *maxsplit* |
| 541 | splits occur, and the remainder of the string is returned as the final element |
| 542 | of the list. (Incompatibility note: in the original Python 1.5 release, |
Georg Brandl | 6199e32 | 2008-03-22 12:04:26 +0000 | [diff] [blame] | 543 | *maxsplit* was ignored. This has been fixed in later releases.) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 544 | |
| 545 | >>> re.split('\W+', 'Words, words, words.') |
| 546 | ['Words', 'words', 'words', ''] |
| 547 | >>> re.split('(\W+)', 'Words, words, words.') |
| 548 | ['Words', ', ', 'words', ', ', 'words', '.', ''] |
| 549 | >>> re.split('\W+', 'Words, words, words.', 1) |
| 550 | ['Words', 'words, words.'] |
Gregory P. Smith | ae91d09 | 2009-03-02 05:13:57 +0000 | [diff] [blame] | 551 | >>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE) |
| 552 | ['0', '3', '9'] |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 553 | |
Georg Brandl | 70992c3 | 2008-03-06 07:19:15 +0000 | [diff] [blame] | 554 | If there are capturing groups in the separator and it matches at the start of |
| 555 | the string, the result will start with an empty string. The same holds for |
Georg Brandl | 6199e32 | 2008-03-22 12:04:26 +0000 | [diff] [blame] | 556 | the end of the string: |
Georg Brandl | 70992c3 | 2008-03-06 07:19:15 +0000 | [diff] [blame] | 557 | |
| 558 | >>> re.split('(\W+)', '...words, words...') |
| 559 | ['', '...', 'words', ', ', 'words', '...', ''] |
| 560 | |
| 561 | That way, separator components are always found at the same relative |
| 562 | indices within the result list (e.g., if there's one capturing group |
| 563 | in the separator, the 0th, the 2nd and so forth). |
| 564 | |
Skip Montanaro | 222907d | 2007-09-01 17:40:03 +0000 | [diff] [blame] | 565 | Note that *split* will never split a string on an empty pattern match. |
Georg Brandl | 6199e32 | 2008-03-22 12:04:26 +0000 | [diff] [blame] | 566 | For example: |
Skip Montanaro | 222907d | 2007-09-01 17:40:03 +0000 | [diff] [blame] | 567 | |
| 568 | >>> re.split('x*', 'foo') |
| 569 | ['foo'] |
| 570 | >>> re.split("(?m)^$", "foo\n\nbar\n") |
| 571 | ['foo\n\nbar\n'] |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 572 | |
Ezio Melotti | 1e5d318 | 2010-11-26 09:30:44 +0000 | [diff] [blame] | 573 | .. versionchanged:: 2.7 |
Gregory P. Smith | ae91d09 | 2009-03-02 05:13:57 +0000 | [diff] [blame] | 574 | Added the optional flags argument. |
| 575 | |
Georg Brandl | 70992c3 | 2008-03-06 07:19:15 +0000 | [diff] [blame] | 576 | |
Eli Bendersky | eb71138 | 2011-11-14 01:02:20 +0200 | [diff] [blame] | 577 | .. function:: findall(pattern, string, flags=0) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 578 | |
Georg Brandl | ba2e519 | 2007-09-27 06:26:58 +0000 | [diff] [blame] | 579 | Return all non-overlapping matches of *pattern* in *string*, as a list of |
Georg Brandl | b46d6ff | 2008-07-19 13:48:44 +0000 | [diff] [blame] | 580 | strings. The *string* is scanned left-to-right, and matches are returned in |
| 581 | the order found. If one or more groups are present in the pattern, return a |
| 582 | list of groups; this will be a list of tuples if the pattern has more than |
| 583 | one group. Empty matches are included in the result unless they touch the |
| 584 | beginning of another match. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 585 | |
| 586 | .. versionadded:: 1.5.2 |
| 587 | |
| 588 | .. versionchanged:: 2.4 |
| 589 | Added the optional flags argument. |
| 590 | |
| 591 | |
Eli Bendersky | eb71138 | 2011-11-14 01:02:20 +0200 | [diff] [blame] | 592 | .. function:: finditer(pattern, string, flags=0) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 593 | |
Georg Brandl | e7a0990 | 2007-10-21 12:10:28 +0000 | [diff] [blame] | 594 | Return an :term:`iterator` yielding :class:`MatchObject` instances over all |
Georg Brandl | b46d6ff | 2008-07-19 13:48:44 +0000 | [diff] [blame] | 595 | non-overlapping matches for the RE *pattern* in *string*. The *string* is |
| 596 | scanned left-to-right, and matches are returned in the order found. Empty |
| 597 | matches are included in the result unless they touch the beginning of another |
| 598 | match. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 599 | |
| 600 | .. versionadded:: 2.2 |
| 601 | |
| 602 | .. versionchanged:: 2.4 |
| 603 | Added the optional flags argument. |
| 604 | |
| 605 | |
Eli Bendersky | eb71138 | 2011-11-14 01:02:20 +0200 | [diff] [blame] | 606 | .. function:: sub(pattern, repl, string, count=0, flags=0) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 607 | |
| 608 | Return the string obtained by replacing the leftmost non-overlapping occurrences |
| 609 | of *pattern* in *string* by the replacement *repl*. If the pattern isn't found, |
| 610 | *string* is returned unchanged. *repl* can be a string or a function; if it is |
| 611 | a string, any backslash escapes in it are processed. That is, ``\n`` is |
Sandro Tosi | a7eb3c8 | 2011-08-19 22:54:33 +0200 | [diff] [blame] | 612 | converted to a single newline character, ``\r`` is converted to a carriage return, and |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 613 | so forth. Unknown escapes such as ``\j`` are left alone. Backreferences, such |
| 614 | as ``\6``, are replaced with the substring matched by group 6 in the pattern. |
Georg Brandl | 6199e32 | 2008-03-22 12:04:26 +0000 | [diff] [blame] | 615 | For example: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 616 | |
| 617 | >>> re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):', |
| 618 | ... r'static PyObject*\npy_\1(void)\n{', |
| 619 | ... 'def myfunc():') |
| 620 | 'static PyObject*\npy_myfunc(void)\n{' |
| 621 | |
| 622 | If *repl* is a function, it is called for every non-overlapping occurrence of |
| 623 | *pattern*. The function takes a single match object argument, and returns the |
Georg Brandl | 6199e32 | 2008-03-22 12:04:26 +0000 | [diff] [blame] | 624 | replacement string. For example: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 625 | |
| 626 | >>> def dashrepl(matchobj): |
| 627 | ... if matchobj.group(0) == '-': return ' ' |
| 628 | ... else: return '-' |
| 629 | >>> re.sub('-{1,2}', dashrepl, 'pro----gram-files') |
| 630 | 'pro--gram files' |
Gregory P. Smith | ae91d09 | 2009-03-02 05:13:57 +0000 | [diff] [blame] | 631 | >>> re.sub(r'\sAND\s', ' & ', 'Baked Beans And Spam', flags=re.IGNORECASE) |
| 632 | 'Baked Beans & Spam' |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 633 | |
Georg Brandl | 04fd324 | 2009-08-13 07:48:05 +0000 | [diff] [blame] | 634 | The pattern may be a string or an RE object. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 635 | |
| 636 | The optional argument *count* is the maximum number of pattern occurrences to be |
| 637 | replaced; *count* must be a non-negative integer. If omitted or zero, all |
| 638 | occurrences will be replaced. Empty matches for the pattern are replaced only |
| 639 | when not adjacent to a previous match, so ``sub('x*', '-', 'abc')`` returns |
| 640 | ``'-a-b-c-'``. |
| 641 | |
| 642 | In addition to character escapes and backreferences as described above, |
| 643 | ``\g<name>`` will use the substring matched by the group named ``name``, as |
| 644 | defined by the ``(?P<name>...)`` syntax. ``\g<number>`` uses the corresponding |
| 645 | group number; ``\g<2>`` is therefore equivalent to ``\2``, but isn't ambiguous |
| 646 | in a replacement such as ``\g<2>0``. ``\20`` would be interpreted as a |
| 647 | reference to group 20, not a reference to group 2 followed by the literal |
| 648 | character ``'0'``. The backreference ``\g<0>`` substitutes in the entire |
| 649 | substring matched by the RE. |
| 650 | |
Ezio Melotti | 1e5d318 | 2010-11-26 09:30:44 +0000 | [diff] [blame] | 651 | .. versionchanged:: 2.7 |
Gregory P. Smith | ae91d09 | 2009-03-02 05:13:57 +0000 | [diff] [blame] | 652 | Added the optional flags argument. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 653 | |
Gregory P. Smith | ae91d09 | 2009-03-02 05:13:57 +0000 | [diff] [blame] | 654 | |
Eli Bendersky | eb71138 | 2011-11-14 01:02:20 +0200 | [diff] [blame] | 655 | .. function:: subn(pattern, repl, string, count=0, flags=0) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 656 | |
| 657 | Perform the same operation as :func:`sub`, but return a tuple ``(new_string, |
| 658 | number_of_subs_made)``. |
| 659 | |
Ezio Melotti | 1e5d318 | 2010-11-26 09:30:44 +0000 | [diff] [blame] | 660 | .. versionchanged:: 2.7 |
Gregory P. Smith | ae91d09 | 2009-03-02 05:13:57 +0000 | [diff] [blame] | 661 | Added the optional flags argument. |
| 662 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 663 | |
| 664 | .. function:: escape(string) |
| 665 | |
| 666 | Return *string* with all non-alphanumerics backslashed; this is useful if you |
| 667 | want to match an arbitrary literal string that may have regular expression |
| 668 | metacharacters in it. |
| 669 | |
| 670 | |
R. David Murray | a63f9b6 | 2010-07-10 14:25:18 +0000 | [diff] [blame] | 671 | .. function:: purge() |
| 672 | |
| 673 | Clear the regular expression cache. |
| 674 | |
| 675 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 676 | .. exception:: error |
| 677 | |
| 678 | Exception raised when a string passed to one of the functions here is not a |
| 679 | valid regular expression (for example, it might contain unmatched parentheses) |
| 680 | or when some other error occurs during compilation or matching. It is never an |
| 681 | error if a string contains no match for a pattern. |
| 682 | |
| 683 | |
| 684 | .. _re-objects: |
| 685 | |
| 686 | Regular Expression Objects |
| 687 | -------------------------- |
| 688 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 689 | .. class:: RegexObject |
| 690 | |
| 691 | The :class:`RegexObject` class supports the following methods and attributes: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 692 | |
Georg Brandl | b1a1405 | 2010-06-01 07:25:23 +0000 | [diff] [blame] | 693 | .. method:: RegexObject.search(string[, pos[, endpos]]) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 694 | |
Georg Brandl | b1a1405 | 2010-06-01 07:25:23 +0000 | [diff] [blame] | 695 | Scan through *string* looking for a location where this regular expression |
| 696 | produces a match, and return a corresponding :class:`MatchObject` instance. |
| 697 | Return ``None`` if no position in the string matches the pattern; note that this |
| 698 | is different from finding a zero-length match at some point in the string. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 699 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 700 | The optional second parameter *pos* gives an index in the string where the |
| 701 | search is to start; it defaults to ``0``. This is not completely equivalent to |
| 702 | slicing the string; the ``'^'`` pattern character matches at the real beginning |
| 703 | of the string and at positions just after a newline, but not necessarily at the |
| 704 | index where the search is to start. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 705 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 706 | The optional parameter *endpos* limits how far the string will be searched; it |
| 707 | will be as if the string is *endpos* characters long, so only the characters |
| 708 | from *pos* to ``endpos - 1`` will be searched for a match. If *endpos* is less |
| 709 | than *pos*, no match will be found, otherwise, if *rx* is a compiled regular |
Georg Brandl | b1a1405 | 2010-06-01 07:25:23 +0000 | [diff] [blame] | 710 | expression object, ``rx.search(string, 0, 50)`` is equivalent to |
| 711 | ``rx.search(string[:50], 0)``. |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 712 | |
Georg Brandl | b1a1405 | 2010-06-01 07:25:23 +0000 | [diff] [blame] | 713 | >>> pattern = re.compile("d") |
| 714 | >>> pattern.search("dog") # Match at index 0 |
| 715 | <_sre.SRE_Match object at ...> |
| 716 | >>> pattern.search("dog", 1) # No match; search doesn't include the "d" |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 717 | |
| 718 | |
Georg Brandl | b1a1405 | 2010-06-01 07:25:23 +0000 | [diff] [blame] | 719 | .. method:: RegexObject.match(string[, pos[, endpos]]) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 720 | |
Georg Brandl | b1a1405 | 2010-06-01 07:25:23 +0000 | [diff] [blame] | 721 | If zero or more characters at the *beginning* of *string* match this regular |
| 722 | expression, return a corresponding :class:`MatchObject` instance. Return |
| 723 | ``None`` if the string does not match the pattern; note that this is different |
| 724 | from a zero-length match. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 725 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 726 | The optional *pos* and *endpos* parameters have the same meaning as for the |
Georg Brandl | b1a1405 | 2010-06-01 07:25:23 +0000 | [diff] [blame] | 727 | :meth:`~RegexObject.search` method. |
| 728 | |
Georg Brandl | b1a1405 | 2010-06-01 07:25:23 +0000 | [diff] [blame] | 729 | >>> pattern = re.compile("o") |
| 730 | >>> pattern.match("dog") # No match as "o" is not at the start of "dog". |
| 731 | >>> pattern.match("dog", 1) # Match as "o" is the 2nd character of "dog". |
| 732 | <_sre.SRE_Match object at ...> |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 733 | |
Ezio Melotti | d9de93e | 2012-02-29 13:37:07 +0200 | [diff] [blame] | 734 | If you want to locate a match anywhere in *string*, use |
| 735 | :meth:`~RegexObject.search` instead (see also :ref:`search-vs-match`). |
| 736 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 737 | |
Eli Bendersky | eb71138 | 2011-11-14 01:02:20 +0200 | [diff] [blame] | 738 | .. method:: RegexObject.split(string, maxsplit=0) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 739 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 740 | Identical to the :func:`split` function, using the compiled pattern. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 741 | |
| 742 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 743 | .. method:: RegexObject.findall(string[, pos[, endpos]]) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 744 | |
Georg Brandl | f93ce0c | 2010-05-22 08:17:23 +0000 | [diff] [blame] | 745 | Similar to the :func:`findall` function, using the compiled pattern, but |
| 746 | also accepts optional *pos* and *endpos* parameters that limit the search |
| 747 | region like for :meth:`match`. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 748 | |
| 749 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 750 | .. method:: RegexObject.finditer(string[, pos[, endpos]]) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 751 | |
Georg Brandl | f93ce0c | 2010-05-22 08:17:23 +0000 | [diff] [blame] | 752 | Similar to the :func:`finditer` function, using the compiled pattern, but |
| 753 | also accepts optional *pos* and *endpos* parameters that limit the search |
| 754 | region like for :meth:`match`. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 755 | |
| 756 | |
Eli Bendersky | eb71138 | 2011-11-14 01:02:20 +0200 | [diff] [blame] | 757 | .. method:: RegexObject.sub(repl, string, count=0) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 758 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 759 | Identical to the :func:`sub` function, using the compiled pattern. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 760 | |
| 761 | |
Eli Bendersky | eb71138 | 2011-11-14 01:02:20 +0200 | [diff] [blame] | 762 | .. method:: RegexObject.subn(repl, string, count=0) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 763 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 764 | Identical to the :func:`subn` function, using the compiled pattern. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 765 | |
| 766 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 767 | .. attribute:: RegexObject.flags |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 768 | |
Georg Brandl | 94a1057 | 2012-03-17 17:31:32 +0100 | [diff] [blame] | 769 | The regex matching flags. This is a combination of the flags given to |
| 770 | :func:`.compile` and any ``(?...)`` inline flags in the pattern. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 771 | |
| 772 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 773 | .. attribute:: RegexObject.groups |
Georg Brandl | b46f0d7 | 2008-12-05 07:49:49 +0000 | [diff] [blame] | 774 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 775 | The number of capturing groups in the pattern. |
Georg Brandl | b46f0d7 | 2008-12-05 07:49:49 +0000 | [diff] [blame] | 776 | |
| 777 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 778 | .. attribute:: RegexObject.groupindex |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 779 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 780 | A dictionary mapping any symbolic group names defined by ``(?P<id>)`` to group |
| 781 | numbers. The dictionary is empty if no symbolic groups were used in the |
| 782 | pattern. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 783 | |
| 784 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 785 | .. attribute:: RegexObject.pattern |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 786 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 787 | The pattern string from which the RE object was compiled. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 788 | |
| 789 | |
| 790 | .. _match-objects: |
| 791 | |
| 792 | Match Objects |
| 793 | ------------- |
| 794 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 795 | .. class:: MatchObject |
| 796 | |
| 797 | Match Objects always have a boolean value of :const:`True`, so that you can test |
| 798 | whether e.g. :func:`match` resulted in a match with a simple if statement. They |
| 799 | support the following methods and attributes: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 800 | |
| 801 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 802 | .. method:: MatchObject.expand(template) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 803 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 804 | Return the string obtained by doing backslash substitution on the template |
| 805 | string *template*, as done by the :meth:`~RegexObject.sub` method. Escapes |
| 806 | such as ``\n`` are converted to the appropriate characters, and numeric |
| 807 | backreferences (``\1``, ``\2``) and named backreferences (``\g<1>``, |
| 808 | ``\g<name>``) are replaced by the contents of the corresponding group. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 809 | |
| 810 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 811 | .. method:: MatchObject.group([group1, ...]) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 812 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 813 | Returns one or more subgroups of the match. If there is a single argument, the |
| 814 | result is a single string; if there are multiple arguments, the result is a |
| 815 | tuple with one item per argument. Without arguments, *group1* defaults to zero |
| 816 | (the whole match is returned). If a *groupN* argument is zero, the corresponding |
| 817 | return value is the entire matching string; if it is in the inclusive range |
| 818 | [1..99], it is the string matching the corresponding parenthesized group. If a |
| 819 | group number is negative or larger than the number of groups defined in the |
| 820 | pattern, an :exc:`IndexError` exception is raised. If a group is contained in a |
| 821 | part of the pattern that did not match, the corresponding result is ``None``. |
| 822 | If a group is contained in a part of the pattern that matched multiple times, |
| 823 | the last match is returned. |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 824 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 825 | >>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist") |
| 826 | >>> m.group(0) # The entire match |
| 827 | 'Isaac Newton' |
| 828 | >>> m.group(1) # The first parenthesized subgroup. |
| 829 | 'Isaac' |
| 830 | >>> m.group(2) # The second parenthesized subgroup. |
| 831 | 'Newton' |
| 832 | >>> m.group(1, 2) # Multiple arguments give us a tuple. |
| 833 | ('Isaac', 'Newton') |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 834 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 835 | If the regular expression uses the ``(?P<name>...)`` syntax, the *groupN* |
| 836 | arguments may also be strings identifying groups by their group name. If a |
| 837 | string argument is not used as a group name in the pattern, an :exc:`IndexError` |
| 838 | exception is raised. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 839 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 840 | A moderately complicated example: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 841 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 842 | >>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds") |
| 843 | >>> m.group('first_name') |
| 844 | 'Malcolm' |
| 845 | >>> m.group('last_name') |
| 846 | 'Reynolds' |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 847 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 848 | Named groups can also be referred to by their index: |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 849 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 850 | >>> m.group(1) |
| 851 | 'Malcolm' |
| 852 | >>> m.group(2) |
| 853 | 'Reynolds' |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 854 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 855 | If a group matches multiple times, only the last match is accessible: |
Georg Brandl | 6199e32 | 2008-03-22 12:04:26 +0000 | [diff] [blame] | 856 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 857 | >>> m = re.match(r"(..)+", "a1b2c3") # Matches 3 times. |
| 858 | >>> m.group(1) # Returns only the last match. |
| 859 | 'c3' |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 860 | |
| 861 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 862 | .. method:: MatchObject.groups([default]) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 863 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 864 | Return a tuple containing all the subgroups of the match, from 1 up to however |
| 865 | many groups are in the pattern. The *default* argument is used for groups that |
| 866 | did not participate in the match; it defaults to ``None``. (Incompatibility |
| 867 | note: in the original Python 1.5 release, if the tuple was one element long, a |
| 868 | string would be returned instead. In later versions (from 1.5.1 on), a |
| 869 | singleton tuple is returned in such cases.) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 870 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 871 | For example: |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 872 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 873 | >>> m = re.match(r"(\d+)\.(\d+)", "24.1632") |
| 874 | >>> m.groups() |
| 875 | ('24', '1632') |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 876 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 877 | If we make the decimal place and everything after it optional, not all groups |
| 878 | might participate in the match. These groups will default to ``None`` unless |
| 879 | the *default* argument is given: |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 880 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 881 | >>> m = re.match(r"(\d+)\.?(\d+)?", "24") |
| 882 | >>> m.groups() # Second group defaults to None. |
| 883 | ('24', None) |
| 884 | >>> m.groups('0') # Now, the second group defaults to '0'. |
| 885 | ('24', '0') |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 886 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 887 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 888 | .. method:: MatchObject.groupdict([default]) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 889 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 890 | Return a dictionary containing all the *named* subgroups of the match, keyed by |
| 891 | the subgroup name. The *default* argument is used for groups that did not |
| 892 | participate in the match; it defaults to ``None``. For example: |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 893 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 894 | >>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds") |
| 895 | >>> m.groupdict() |
| 896 | {'first_name': 'Malcolm', 'last_name': 'Reynolds'} |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 897 | |
| 898 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 899 | .. method:: MatchObject.start([group]) |
| 900 | MatchObject.end([group]) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 901 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 902 | Return the indices of the start and end of the substring matched by *group*; |
| 903 | *group* defaults to zero (meaning the whole matched substring). Return ``-1`` if |
| 904 | *group* exists but did not contribute to the match. For a match object *m*, and |
| 905 | a group *g* that did contribute to the match, the substring matched by group *g* |
| 906 | (equivalent to ``m.group(g)``) is :: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 907 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 908 | m.string[m.start(g):m.end(g)] |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 909 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 910 | Note that ``m.start(group)`` will equal ``m.end(group)`` if *group* matched a |
| 911 | null string. For example, after ``m = re.search('b(c?)', 'cba')``, |
| 912 | ``m.start(0)`` is 1, ``m.end(0)`` is 2, ``m.start(1)`` and ``m.end(1)`` are both |
| 913 | 2, and ``m.start(2)`` raises an :exc:`IndexError` exception. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 914 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 915 | An example that will remove *remove_this* from email addresses: |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 916 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 917 | >>> email = "tony@tiremove_thisger.net" |
| 918 | >>> m = re.search("remove_this", email) |
| 919 | >>> email[:m.start()] + email[m.end():] |
| 920 | 'tony@tiger.net' |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 921 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 922 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 923 | .. method:: MatchObject.span([group]) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 924 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 925 | For :class:`MatchObject` *m*, return the 2-tuple ``(m.start(group), |
| 926 | m.end(group))``. Note that if *group* did not contribute to the match, this is |
| 927 | ``(-1, -1)``. *group* defaults to zero, the entire match. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 928 | |
| 929 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 930 | .. attribute:: MatchObject.pos |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 931 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 932 | The value of *pos* which was passed to the :meth:`~RegexObject.search` or |
| 933 | :meth:`~RegexObject.match` method of the :class:`RegexObject`. This is the |
| 934 | index into the string at which the RE engine started looking for a match. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 935 | |
| 936 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 937 | .. attribute:: MatchObject.endpos |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 938 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 939 | The value of *endpos* which was passed to the :meth:`~RegexObject.search` or |
| 940 | :meth:`~RegexObject.match` method of the :class:`RegexObject`. This is the |
| 941 | index into the string beyond which the RE engine will not go. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 942 | |
| 943 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 944 | .. attribute:: MatchObject.lastindex |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 945 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 946 | The integer index of the last matched capturing group, or ``None`` if no group |
| 947 | was matched at all. For example, the expressions ``(a)b``, ``((a)(b))``, and |
| 948 | ``((ab))`` will have ``lastindex == 1`` if applied to the string ``'ab'``, while |
| 949 | the expression ``(a)(b)`` will have ``lastindex == 2``, if applied to the same |
| 950 | string. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 951 | |
| 952 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 953 | .. attribute:: MatchObject.lastgroup |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 954 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 955 | The name of the last matched capturing group, or ``None`` if the group didn't |
| 956 | have a name, or if no group was matched at all. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 957 | |
| 958 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 959 | .. attribute:: MatchObject.re |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 960 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 961 | The regular expression object whose :meth:`~RegexObject.match` or |
| 962 | :meth:`~RegexObject.search` method produced this :class:`MatchObject` |
| 963 | instance. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 964 | |
| 965 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 966 | .. attribute:: MatchObject.string |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 967 | |
Brian Curtin | fbe5199 | 2010-03-25 23:48:54 +0000 | [diff] [blame] | 968 | The string passed to :meth:`~RegexObject.match` or |
| 969 | :meth:`~RegexObject.search`. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 970 | |
| 971 | |
| 972 | Examples |
| 973 | -------- |
| 974 | |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 975 | |
| 976 | Checking For a Pair |
| 977 | ^^^^^^^^^^^^^^^^^^^ |
| 978 | |
| 979 | In this example, we'll use the following helper function to display match |
Georg Brandl | 6199e32 | 2008-03-22 12:04:26 +0000 | [diff] [blame] | 980 | objects a little more gracefully: |
| 981 | |
Georg Brandl | 838b4b0 | 2008-03-22 13:07:06 +0000 | [diff] [blame] | 982 | .. testcode:: |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 983 | |
| 984 | def displaymatch(match): |
| 985 | if match is None: |
| 986 | return None |
| 987 | return '<Match: %r, groups=%r>' % (match.group(), match.groups()) |
| 988 | |
| 989 | Suppose you are writing a poker program where a player's hand is represented as |
| 990 | a 5-character string with each character representing a card, "a" for ace, "k" |
Ezio Melotti | 13c82d0 | 2011-12-17 01:17:17 +0200 | [diff] [blame] | 991 | for king, "q" for queen, "j" for jack, "t" for 10, and "2" through "9" |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 992 | representing the card with that value. |
| 993 | |
Georg Brandl | 6199e32 | 2008-03-22 12:04:26 +0000 | [diff] [blame] | 994 | To see if a given string is a valid hand, one could do the following: |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 995 | |
Ezio Melotti | 13c82d0 | 2011-12-17 01:17:17 +0200 | [diff] [blame] | 996 | >>> valid = re.compile(r"^[a2-9tjqk]{5}$") |
| 997 | >>> displaymatch(valid.match("akt5q")) # Valid. |
| 998 | "<Match: 'akt5q', groups=()>" |
| 999 | >>> displaymatch(valid.match("akt5e")) # Invalid. |
| 1000 | >>> displaymatch(valid.match("akt")) # Invalid. |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 1001 | >>> displaymatch(valid.match("727ak")) # Valid. |
Georg Brandl | 6199e32 | 2008-03-22 12:04:26 +0000 | [diff] [blame] | 1002 | "<Match: '727ak', groups=()>" |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 1003 | |
| 1004 | That last hand, ``"727ak"``, contained a pair, or two of the same valued cards. |
Georg Brandl | 6199e32 | 2008-03-22 12:04:26 +0000 | [diff] [blame] | 1005 | To match this with a regular expression, one could use backreferences as such: |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 1006 | |
| 1007 | >>> pair = re.compile(r".*(.).*\1") |
| 1008 | >>> displaymatch(pair.match("717ak")) # Pair of 7s. |
Georg Brandl | 6199e32 | 2008-03-22 12:04:26 +0000 | [diff] [blame] | 1009 | "<Match: '717', groups=('7',)>" |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 1010 | >>> displaymatch(pair.match("718ak")) # No pairs. |
| 1011 | >>> displaymatch(pair.match("354aa")) # Pair of aces. |
Georg Brandl | 6199e32 | 2008-03-22 12:04:26 +0000 | [diff] [blame] | 1012 | "<Match: '354aa', groups=('a',)>" |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 1013 | |
Georg Brandl | 74f8fc0 | 2009-07-26 13:36:39 +0000 | [diff] [blame] | 1014 | To find out what card the pair consists of, one could use the |
| 1015 | :meth:`~MatchObject.group` method of :class:`MatchObject` in the following |
| 1016 | manner: |
Georg Brandl | 6199e32 | 2008-03-22 12:04:26 +0000 | [diff] [blame] | 1017 | |
Georg Brandl | 838b4b0 | 2008-03-22 13:07:06 +0000 | [diff] [blame] | 1018 | .. doctest:: |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 1019 | |
| 1020 | >>> pair.match("717ak").group(1) |
| 1021 | '7' |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 1022 | |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 1023 | # Error because re.match() returns None, which doesn't have a group() method: |
| 1024 | >>> pair.match("718ak").group(1) |
| 1025 | Traceback (most recent call last): |
| 1026 | File "<pyshell#23>", line 1, in <module> |
| 1027 | re.match(r".*(.).*\1", "718ak").group(1) |
| 1028 | AttributeError: 'NoneType' object has no attribute 'group' |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 1029 | |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 1030 | >>> pair.match("354aa").group(1) |
| 1031 | 'a' |
| 1032 | |
| 1033 | |
| 1034 | Simulating scanf() |
| 1035 | ^^^^^^^^^^^^^^^^^^ |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1036 | |
| 1037 | .. index:: single: scanf() |
| 1038 | |
Sandro Tosi | 98ed08f | 2012-01-14 16:42:02 +0100 | [diff] [blame] | 1039 | Python does not currently have an equivalent to :c:func:`scanf`. Regular |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1040 | expressions are generally more powerful, though also more verbose, than |
Sandro Tosi | 98ed08f | 2012-01-14 16:42:02 +0100 | [diff] [blame] | 1041 | :c:func:`scanf` format strings. The table below offers some more-or-less |
| 1042 | equivalent mappings between :c:func:`scanf` format tokens and regular |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1043 | expressions. |
| 1044 | |
| 1045 | +--------------------------------+---------------------------------------------+ |
Sandro Tosi | 98ed08f | 2012-01-14 16:42:02 +0100 | [diff] [blame] | 1046 | | :c:func:`scanf` Token | Regular Expression | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1047 | +================================+=============================================+ |
| 1048 | | ``%c`` | ``.`` | |
| 1049 | +--------------------------------+---------------------------------------------+ |
| 1050 | | ``%5c`` | ``.{5}`` | |
| 1051 | +--------------------------------+---------------------------------------------+ |
| 1052 | | ``%d`` | ``[-+]?\d+`` | |
| 1053 | +--------------------------------+---------------------------------------------+ |
| 1054 | | ``%e``, ``%E``, ``%f``, ``%g`` | ``[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?`` | |
| 1055 | +--------------------------------+---------------------------------------------+ |
| 1056 | | ``%i`` | ``[-+]?(0[xX][\dA-Fa-f]+|0[0-7]*|\d+)`` | |
| 1057 | +--------------------------------+---------------------------------------------+ |
| 1058 | | ``%o`` | ``0[0-7]*`` | |
| 1059 | +--------------------------------+---------------------------------------------+ |
| 1060 | | ``%s`` | ``\S+`` | |
| 1061 | +--------------------------------+---------------------------------------------+ |
| 1062 | | ``%u`` | ``\d+`` | |
| 1063 | +--------------------------------+---------------------------------------------+ |
| 1064 | | ``%x``, ``%X`` | ``0[xX][\dA-Fa-f]+`` | |
| 1065 | +--------------------------------+---------------------------------------------+ |
| 1066 | |
| 1067 | To extract the filename and numbers from a string like :: |
| 1068 | |
| 1069 | /usr/sbin/sendmail - 0 errors, 4 warnings |
| 1070 | |
Sandro Tosi | 98ed08f | 2012-01-14 16:42:02 +0100 | [diff] [blame] | 1071 | you would use a :c:func:`scanf` format like :: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1072 | |
| 1073 | %s - %d errors, %d warnings |
| 1074 | |
| 1075 | The equivalent regular expression would be :: |
| 1076 | |
| 1077 | (\S+) - (\d+) errors, (\d+) warnings |
| 1078 | |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 1079 | |
Ezio Melotti | d9de93e | 2012-02-29 13:37:07 +0200 | [diff] [blame] | 1080 | .. _search-vs-match: |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 1081 | |
| 1082 | search() vs. match() |
| 1083 | ^^^^^^^^^^^^^^^^^^^^ |
| 1084 | |
Ezio Melotti | d9de93e | 2012-02-29 13:37:07 +0200 | [diff] [blame] | 1085 | .. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org> |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 1086 | |
Ezio Melotti | d9de93e | 2012-02-29 13:37:07 +0200 | [diff] [blame] | 1087 | Python offers two different primitive operations based on regular expressions: |
| 1088 | :func:`re.match` checks for a match only at the beginning of the string, while |
| 1089 | :func:`re.search` checks for a match anywhere in the string (this is what Perl |
| 1090 | does by default). |
| 1091 | |
| 1092 | For example:: |
| 1093 | |
| 1094 | >>> re.match("c", "abcdef") # No match |
| 1095 | >>> re.search("c", "abcdef") # Match |
Georg Brandl | 6199e32 | 2008-03-22 12:04:26 +0000 | [diff] [blame] | 1096 | <_sre.SRE_Match object at ...> |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 1097 | |
Ezio Melotti | d9de93e | 2012-02-29 13:37:07 +0200 | [diff] [blame] | 1098 | Regular expressions beginning with ``'^'`` can be used with :func:`search` to |
| 1099 | restrict the match at the beginning of the string:: |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 1100 | |
Ezio Melotti | d9de93e | 2012-02-29 13:37:07 +0200 | [diff] [blame] | 1101 | >>> re.match("c", "abcdef") # No match |
| 1102 | >>> re.search("^c", "abcdef") # No match |
| 1103 | >>> re.search("^a", "abcdef") # Match |
Georg Brandl | 6199e32 | 2008-03-22 12:04:26 +0000 | [diff] [blame] | 1104 | <_sre.SRE_Match object at ...> |
Ezio Melotti | d9de93e | 2012-02-29 13:37:07 +0200 | [diff] [blame] | 1105 | |
| 1106 | Note however that in :const:`MULTILINE` mode :func:`match` only matches at the |
| 1107 | beginning of the string, whereas using :func:`search` with a regular expression |
| 1108 | beginning with ``'^'`` will match at the beginning of each line. |
| 1109 | |
| 1110 | >>> re.match('X', 'A\nB\nX', re.MULTILINE) # No match |
| 1111 | >>> re.search('^X', 'A\nB\nX', re.MULTILINE) # Match |
| 1112 | <_sre.SRE_Match object at ...> |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 1113 | |
| 1114 | |
| 1115 | Making a Phonebook |
| 1116 | ^^^^^^^^^^^^^^^^^^ |
| 1117 | |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 1118 | :func:`split` splits a string into a list delimited by the passed pattern. The |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 1119 | method is invaluable for converting textual data into data structures that can be |
| 1120 | easily read and modified by Python as demonstrated in the following example that |
| 1121 | creates a phonebook. |
| 1122 | |
Georg Brandl | d6b20dc | 2007-12-06 09:45:39 +0000 | [diff] [blame] | 1123 | First, here is the input. Normally it may come from a file, here we are using |
Georg Brandl | 6199e32 | 2008-03-22 12:04:26 +0000 | [diff] [blame] | 1124 | triple-quoted string syntax: |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 1125 | |
Georg Brandl | 5a607b0 | 2012-03-17 17:26:27 +0100 | [diff] [blame] | 1126 | >>> text = """Ross McFluff: 834.345.1254 155 Elm Street |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 1127 | ... |
Georg Brandl | 6199e32 | 2008-03-22 12:04:26 +0000 | [diff] [blame] | 1128 | ... Ronald Heathmore: 892.345.3428 436 Finley Avenue |
| 1129 | ... Frank Burger: 925.541.7625 662 South Dogwood Way |
| 1130 | ... |
| 1131 | ... |
| 1132 | ... Heather Albrecht: 548.326.4584 919 Park Place""" |
Georg Brandl | d6b20dc | 2007-12-06 09:45:39 +0000 | [diff] [blame] | 1133 | |
| 1134 | The entries are separated by one or more newlines. Now we convert the string |
Georg Brandl | 6199e32 | 2008-03-22 12:04:26 +0000 | [diff] [blame] | 1135 | into a list with each nonempty line having its own entry: |
| 1136 | |
Georg Brandl | 838b4b0 | 2008-03-22 13:07:06 +0000 | [diff] [blame] | 1137 | .. doctest:: |
Georg Brandl | 6199e32 | 2008-03-22 12:04:26 +0000 | [diff] [blame] | 1138 | :options: +NORMALIZE_WHITESPACE |
Georg Brandl | d6b20dc | 2007-12-06 09:45:39 +0000 | [diff] [blame] | 1139 | |
Georg Brandl | 5a607b0 | 2012-03-17 17:26:27 +0100 | [diff] [blame] | 1140 | >>> entries = re.split("\n+", text) |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 1141 | >>> entries |
Georg Brandl | 6199e32 | 2008-03-22 12:04:26 +0000 | [diff] [blame] | 1142 | ['Ross McFluff: 834.345.1254 155 Elm Street', |
| 1143 | 'Ronald Heathmore: 892.345.3428 436 Finley Avenue', |
| 1144 | 'Frank Burger: 925.541.7625 662 South Dogwood Way', |
| 1145 | 'Heather Albrecht: 548.326.4584 919 Park Place'] |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 1146 | |
| 1147 | Finally, split each entry into a list with first name, last name, telephone |
Georg Brandl | 907a720 | 2008-02-22 12:31:45 +0000 | [diff] [blame] | 1148 | number, and address. We use the ``maxsplit`` parameter of :func:`split` |
Georg Brandl | 6199e32 | 2008-03-22 12:04:26 +0000 | [diff] [blame] | 1149 | because the address has spaces, our splitting pattern, in it: |
| 1150 | |
Georg Brandl | 838b4b0 | 2008-03-22 13:07:06 +0000 | [diff] [blame] | 1151 | .. doctest:: |
Georg Brandl | 6199e32 | 2008-03-22 12:04:26 +0000 | [diff] [blame] | 1152 | :options: +NORMALIZE_WHITESPACE |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 1153 | |
Georg Brandl | d6b20dc | 2007-12-06 09:45:39 +0000 | [diff] [blame] | 1154 | >>> [re.split(":? ", entry, 3) for entry in entries] |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 1155 | [['Ross', 'McFluff', '834.345.1254', '155 Elm Street'], |
| 1156 | ['Ronald', 'Heathmore', '892.345.3428', '436 Finley Avenue'], |
| 1157 | ['Frank', 'Burger', '925.541.7625', '662 South Dogwood Way'], |
| 1158 | ['Heather', 'Albrecht', '548.326.4584', '919 Park Place']] |
| 1159 | |
Georg Brandl | d6b20dc | 2007-12-06 09:45:39 +0000 | [diff] [blame] | 1160 | The ``:?`` pattern matches the colon after the last name, so that it does not |
Georg Brandl | 907a720 | 2008-02-22 12:31:45 +0000 | [diff] [blame] | 1161 | occur in the result list. With a ``maxsplit`` of ``4``, we could separate the |
Georg Brandl | 6199e32 | 2008-03-22 12:04:26 +0000 | [diff] [blame] | 1162 | house number from the street name: |
| 1163 | |
Georg Brandl | 838b4b0 | 2008-03-22 13:07:06 +0000 | [diff] [blame] | 1164 | .. doctest:: |
Georg Brandl | 6199e32 | 2008-03-22 12:04:26 +0000 | [diff] [blame] | 1165 | :options: +NORMALIZE_WHITESPACE |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 1166 | |
Georg Brandl | d6b20dc | 2007-12-06 09:45:39 +0000 | [diff] [blame] | 1167 | >>> [re.split(":? ", entry, 4) for entry in entries] |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 1168 | [['Ross', 'McFluff', '834.345.1254', '155', 'Elm Street'], |
| 1169 | ['Ronald', 'Heathmore', '892.345.3428', '436', 'Finley Avenue'], |
| 1170 | ['Frank', 'Burger', '925.541.7625', '662', 'South Dogwood Way'], |
| 1171 | ['Heather', 'Albrecht', '548.326.4584', '919', 'Park Place']] |
| 1172 | |
| 1173 | |
| 1174 | Text Munging |
| 1175 | ^^^^^^^^^^^^ |
| 1176 | |
| 1177 | :func:`sub` replaces every occurrence of a pattern with a string or the |
| 1178 | result of a function. This example demonstrates using :func:`sub` with |
| 1179 | a function to "munge" text, or randomize the order of all the characters |
| 1180 | in each word of a sentence except for the first and last characters:: |
| 1181 | |
| 1182 | >>> def repl(m): |
| 1183 | ... inner_word = list(m.group(2)) |
| 1184 | ... random.shuffle(inner_word) |
| 1185 | ... return m.group(1) + "".join(inner_word) + m.group(3) |
| 1186 | >>> text = "Professor Abdolmalek, please report your absences promptly." |
Georg Brandl | e0289a3 | 2010-08-01 21:44:38 +0000 | [diff] [blame] | 1187 | >>> re.sub(r"(\w)(\w+)(\w)", repl, text) |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 1188 | 'Poefsrosr Aealmlobdk, pslaee reorpt your abnseces plmrptoy.' |
Georg Brandl | e0289a3 | 2010-08-01 21:44:38 +0000 | [diff] [blame] | 1189 | >>> re.sub(r"(\w)(\w+)(\w)", repl, text) |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 1190 | 'Pofsroser Aodlambelk, plasee reoprt yuor asnebces potlmrpy.' |
| 1191 | |
| 1192 | |
| 1193 | Finding all Adverbs |
| 1194 | ^^^^^^^^^^^^^^^^^^^ |
| 1195 | |
Georg Brandl | 907a720 | 2008-02-22 12:31:45 +0000 | [diff] [blame] | 1196 | :func:`findall` matches *all* occurrences of a pattern, not just the first |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 1197 | one as :func:`search` does. For example, if one was a writer and wanted to |
| 1198 | find all of the adverbs in some text, he or she might use :func:`findall` in |
Georg Brandl | 6199e32 | 2008-03-22 12:04:26 +0000 | [diff] [blame] | 1199 | the following manner: |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 1200 | |
| 1201 | >>> text = "He was carefully disguised but captured quickly by police." |
| 1202 | >>> re.findall(r"\w+ly", text) |
| 1203 | ['carefully', 'quickly'] |
| 1204 | |
| 1205 | |
| 1206 | Finding all Adverbs and their Positions |
| 1207 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1208 | |
| 1209 | If one wants more information about all matches of a pattern than the matched |
| 1210 | text, :func:`finditer` is useful as it provides instances of |
| 1211 | :class:`MatchObject` instead of strings. Continuing with the previous example, |
| 1212 | if one was a writer who wanted to find all of the adverbs *and their positions* |
Georg Brandl | 6199e32 | 2008-03-22 12:04:26 +0000 | [diff] [blame] | 1213 | in some text, he or she would use :func:`finditer` in the following manner: |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 1214 | |
| 1215 | >>> text = "He was carefully disguised but captured quickly by police." |
| 1216 | >>> for m in re.finditer(r"\w+ly", text): |
Georg Brandl | 6199e32 | 2008-03-22 12:04:26 +0000 | [diff] [blame] | 1217 | ... print '%02d-%02d: %s' % (m.start(), m.end(), m.group(0)) |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 1218 | 07-16: carefully |
| 1219 | 40-47: quickly |
| 1220 | |
| 1221 | |
| 1222 | Raw String Notation |
| 1223 | ^^^^^^^^^^^^^^^^^^^ |
| 1224 | |
| 1225 | Raw string notation (``r"text"``) keeps regular expressions sane. Without it, |
| 1226 | every backslash (``'\'``) in a regular expression would have to be prefixed with |
| 1227 | another one to escape it. For example, the two following lines of code are |
Georg Brandl | 6199e32 | 2008-03-22 12:04:26 +0000 | [diff] [blame] | 1228 | functionally identical: |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 1229 | |
| 1230 | >>> re.match(r"\W(.)\1\W", " ff ") |
Georg Brandl | 6199e32 | 2008-03-22 12:04:26 +0000 | [diff] [blame] | 1231 | <_sre.SRE_Match object at ...> |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 1232 | >>> re.match("\\W(.)\\1\\W", " ff ") |
Georg Brandl | 6199e32 | 2008-03-22 12:04:26 +0000 | [diff] [blame] | 1233 | <_sre.SRE_Match object at ...> |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 1234 | |
| 1235 | When one wants to match a literal backslash, it must be escaped in the regular |
| 1236 | expression. With raw string notation, this means ``r"\\"``. Without raw string |
| 1237 | notation, one must use ``"\\\\"``, making the following lines of code |
Georg Brandl | 6199e32 | 2008-03-22 12:04:26 +0000 | [diff] [blame] | 1238 | functionally identical: |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 1239 | |
| 1240 | >>> re.match(r"\\", r"\\") |
Georg Brandl | 6199e32 | 2008-03-22 12:04:26 +0000 | [diff] [blame] | 1241 | <_sre.SRE_Match object at ...> |
Georg Brandl | b8df156 | 2007-12-05 18:30:48 +0000 | [diff] [blame] | 1242 | >>> re.match("\\\\", r"\\") |
Georg Brandl | 6199e32 | 2008-03-22 12:04:26 +0000 | [diff] [blame] | 1243 | <_sre.SRE_Match object at ...> |