Curso de Programación en Python/RegEx-50

De WikiCabal
Ir a la navegación Ir a la búsqueda

Some characters, like '|' or '(', are special. Special characters either stand for classes of ordinary characters, or affect how the regular expressions around them are interpreted. Regular expression pattern strings may not contain null bytes, but can specify the null byte using a \number notation such as '\x00'.

The special characters are:

'.'
(Dot.) In the default mode, this matches any character except a newline. If the <a class="reference internal" href="#re.DOTALL" title="re.DOTALL">DOTALL</a> flag has been specified, this matches any character including a newline.
'^'
(Caret.) Matches the start of the string, and in <a class="reference internal" href="#re.MULTILINE" title="re.MULTILINE">MULTILINE</a> mode also matches immediately after each newline.
'$'
Matches the end of the string or just before the newline at the end of the string, and in <a class="reference internal" href="#re.MULTILINE" title="re.MULTILINE">MULTILINE</a> mode also matches before a newline. foo matches both ‘foo’ and ‘foobar’, while the regular expression foo$ matches only ‘foo’. More interestingly, searching for foo.$ in 'foo1\nfoo2\n' matches ‘foo2’ normally, but ‘foo1’ in <a class="reference internal" href="#re.MULTILINE" title="re.MULTILINE">MULTILINE</a> mode; searching for a single $ in 'foo\n' will find two (empty) matches: one just before the newline, and one at the end of the string.
'*'
Causes the resulting RE to match 0 or more repetitions of the preceding RE, as many repetitions as are possible. ab* will match ‘a’, ‘ab’, or ‘a’ followed by any number of ‘b’s.
'+'
Causes the resulting RE to match 1 or more repetitions of the preceding RE. ab+ will match ‘a’ followed by any non-zero number of ‘b’s; it will not match just ‘a’.
'?'
Causes the resulting RE to match 0 or 1 repetitions of the preceding RE. ab? will match either ‘a’ or ‘ab’.
*?, +?, ??
The '*', '+', and '?' qualifiers are all greedy; they match as much text as possible. Sometimes this behaviour isn’t desired; if the RE <.*> is matched against '<H1>title</H1>', it will match the entire string, and not just '<H1>'. Adding '?' after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched. Using .*? in the previous expression will match only '<H1>'.
{m}
Specifies that exactly m copies of the previous RE should be matched; fewer matches cause the entire RE not to match. For example, a{6} will match exactly six 'a' characters, but not five.
{m,n}
Causes the resulting RE to match from m to n repetitions of the preceding RE, attempting to match as many repetitions as possible. For example, a{3,5} will match from 3 to 5 'a' characters. Omitting m specifies a lower bound of zero, and omitting n specifies an infinite upper bound. As an example, a{4,}b will match aaaab or a thousand 'a' characters followed by a b, but not aaab. The comma may not be omitted or the modifier would be confused with the previously described form.
{m,n}?
Causes the resulting RE to match from m to n repetitions of the preceding RE, attempting to match as few repetitions as possible. This is the non-greedy version of the previous qualifier. For example, on the 6-character string 'aaaaaa', a{3,5} will match 5 'a' characters, while a{3,5}? will only match 3 characters.
'\'

Either escapes special characters (permitting you to match characters like '*', '?', and so forth), or signals a special sequence; special sequences are discussed below.

If you’re not using a raw string to express the pattern, remember that Python also uses the backslash as an escape sequence in string literals; if the escape sequence isn’t recognized by Python’s parser, the backslash and subsequent character are included in the resulting string. However, if Python would recognize the resulting sequence, the backslash should be repeated twice. This is complicated and hard to understand, so it’s highly recommended that you use raw strings for all but the simplest expressions.

[]

Used to indicate a set of characters. In a set:

  • Characters can be listed individually, e.g. [amk] will match 'a', 'm', or 'k'.
  • Ranges of characters can be indicated by giving two characters and separating them by a '-', for example [a-z] will match any lowercase ASCII letter, [0-5][0-9] will match all the two-digits numbers from 00 to 59, and [0-9A-Fa-f] will match any hexadecimal digit. If - is escaped (e.g. [a\-z]) or if it’s placed as the first or last character (e.g. [a-]), it will match a literal '-'.
  • Special characters lose their special meaning inside sets. For example, [(+*)] will match any of the literal characters '(', '+', '*', or ')'.
  • Character classes such as \w or \S (defined below) are also accepted inside a set, although the characters they match depends on whether <a class="reference internal" href="#re.ASCII" title="re.ASCII">ASCII</a> or <a class="reference internal" href="#re.LOCALE" title="re.LOCALE">LOCALE</a> mode is in force.
  • Characters that are not within a range can be matched by complementing the set. If the first character of the set is '^', all the characters that are not in the set will be matched. For example, [^5] will match any character except '5', and [^^] will match any character except '^'. ^ has no special meaning if it’s not the first character in the set.
  • To match a literal ']' inside a set, precede it with a backslash, or place it at the beginning of the set. For example, both [()[\]{}] and []()[{}] will both match a parenthesis.
'|'
A|B, where A and B can be arbitrary REs, creates a regular expression that will match either A or B. An arbitrary number of REs can be separated by the '|' in this way. This can be used inside groups (see below) as well. As the target string is scanned, REs separated by '|' are tried from left to right. When one pattern completely matches, that branch is accepted. This means that once A matches, B will not be tested further, even if it would produce a longer overall match. In other words, the '|' operator is never greedy. To match a literal '|', use \|, or enclose it inside a character class, as in [|].
(...)
Matches whatever regular expression is inside the parentheses, and indicates the start and end of a group; the contents of a group can be retrieved after a match has been performed, and can be matched later in the string with the \number special sequence, described below. To match the literals '(' or ')', use \( or \), or enclose them inside a character class: [(] [)].
(?...)
This is an extension notation (a '?' following a '(' is not meaningful otherwise). The first character after the '?' determines what the meaning and further syntax of the construct is. Extensions usually do not create a new group; (?P<name>...) is the only exception to this rule. Following are the currently supported extensions.
(?aiLmsux)

(One or more letters from the set 'a', 'i', 'L', 'm', 's', 'u', 'x'.) The group matches the empty string; the letters set the corresponding flags: <a class="reference internal" href="#re.A" title="re.A">re.A</a> (ASCII-only matching), <a class="reference internal" href="#re.I" title="re.I">re.I</a> (ignore case), <a class="reference internal" href="#re.L" title="re.L">re.L</a> (locale dependent), <a class="reference internal" href="#re.M" title="re.M">re.M</a> (multi-line), <a class="reference internal" href="#re.S" title="re.S">re.S</a> (dot matches all), and <a class="reference internal" href="#re.X" title="re.X">re.X</a> (verbose), for the entire regular expression. (The flags are described in <a class="reference internal" href="#contents-of-module-re">Module Contents</a>.) This is useful if you wish to include the flags as part of the regular expression, instead of passing a flag argument to the <a class="reference internal" href="#re.compile" title="re.compile">re.compile()</a> function.

Note that the (?x) flag changes how the expression is parsed. It should be used first in the expression string, or after one or more whitespace characters. If there are non-whitespace characters before the flag, the results are undefined.

(?:...)
A non-capturing version of regular parentheses. Matches whatever regular expression is inside the parentheses, but the substring matched by the group cannot be retrieved after performing a match or referenced later in the pattern.
(?P<name>...)

Similar to regular parentheses, but the substring matched by the group is accessible via the symbolic group name name. Group names must be valid Python identifiers, and each group name must be defined only once within a regular expression. A symbolic group is also a numbered group, just as if the group were not named.

Named groups can be referenced in three contexts. If the pattern is (?P<quote>['"]).*?(?P=quote) (i.e. matching a string quoted with either single or double quotes):

<colgroup> <col width="53%" /> <col width="47%" /> </colgroup> <thead valign="bottom"> </thead> <tbody valign="top"> </tbody>
Context of reference to group “quote” Ways to reference it
in the same pattern itself
  • (?P=quote) (as shown)
  • \1
when processing match object m
  • m.group('quote')
  • m.end('quote') (etc.)
in a string passed to the repl argument of re.sub()
  • \g<quote>
  • \g<1>
  • \1
(?P=name)
A backreference to a named group; it matches whatever text was matched by the earlier group named name.
(?#...)
A comment; the contents of the parentheses are simply ignored.
(?=...)
Matches if ... matches next, but doesn’t consume any of the string. This is called a lookahead assertion. For example, Isaac (?=Asimov) will match 'Isaac ' only if it’s followed by 'Asimov'.
(?!...)
Matches if ... doesn’t match next. This is a negative lookahead assertion. For example, Isaac (?!Asimov) will match 'Isaac ' only if it’s not followed by 'Asimov'.
(?<=...)

Matches if the current position in the string is preceded by a match for ... that ends at the current position. This is called a positive lookbehind assertion. (?<=abc)def will find a match in abcdef, since the lookbehind will back up 3 characters and check if the contained pattern matches. The contained pattern must only match strings of some fixed length, meaning that abc or a|b are allowed, but a* and a{3,4} are not. Note that patterns which start with positive lookbehind assertions will not match at the beginning of the string being searched; you will most likely want to use the <a class="reference internal" href="#re.search" title="re.search">search()</a> function rather than the <a class="reference internal" href="#re.match" title="re.match">match()</a> function:

<span class="gp">>>> </span><span class="kn">import</span> <span class="nn">re</span>
<span class="gp">>>> </span><span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s">'(?<=abc)def'</span><span class="p">,</span> <span class="s">'abcdef'</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="go">'def'</span>

This example looks for a word following a hyphen:

<span class="gp">>>> </span><span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s">'(?<=-)\w+'</span><span class="p">,</span> <span class="s">'spam-egg'</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="go">'egg'</span>
(?<!...)
Matches if the current position in the string is not preceded by a match for .... This is called a negative lookbehind assertion. Similar to positive lookbehind assertions, the contained pattern must only match strings of some fixed length. Patterns which start with negative lookbehind assertions may match at the beginning of the string being searched.
(?(id/name)yes-pattern|no-pattern)
Will try to match with yes-pattern if the group with given id or name exists, and with no-pattern if it doesn’t. no-pattern is optional and can be omitted. For example, (<)?(\w+@\w+(?:\.\w+)+)(?(1)>|$) is a poor email matching pattern, which will match with '<user@host.com>' as well as 'user@host.com', but not with '<user@host.com' nor 'user@host.com>'.

The special sequences consist of '\' and a character from the list below. If the ordinary character is not on the list, then the resulting RE will match the second character. For example, \$ matches the character '$'.

\number
Matches the contents of the group of the same number. Groups are numbered starting from 1. For example, (.+) \1 matches 'the the' or '55 55', but not 'thethe' (note the space after the group). This special sequence can only be used to match one of the first 99 groups. If the first digit of number is 0, or number is 3 octal digits long, it will not be interpreted as a group match, but as the character with octal value number. Inside the '[' and ']' of a character class, all numeric escapes are treated as characters.
\A
Matches only at the start of the string.
\b

Matches the empty string, but only at the beginning or end of a word. A word is defined as a sequence of Unicode alphanumeric or underscore characters, so the end of a word is indicated by whitespace or a non-alphanumeric, non-underscore Unicode character. Note that formally, \b is defined as the boundary between a \w and a \W character (or vice versa), or between \w and the beginning/end of the string. This means that r'\bfoo\b' matches 'foo', 'foo.', '(foo)', 'bar foo baz' but not 'foobar' or 'foo3'.

By default Unicode alphanumerics are the ones used, but this can be changed by using the <a class="reference internal" href="#re.ASCII" title="re.ASCII">ASCII</a> flag. Inside a character range, \b represents the backspace character, for compatibility with Python’s string literals.

\B
Matches the empty string, but only when it is not at the beginning or end of a word. This means that r'py\B' matches 'python', 'py3', 'py2', but not 'py', 'py.', or 'py!'. \B is just the opposite of \b, so word characters are Unicode alphanumerics or the underscore, although this can be changed by using the <a class="reference internal" href="#re.ASCII" title="re.ASCII">ASCII</a> flag.
\d
For Unicode (str) patterns:
Matches any Unicode decimal digit (that is, any character in Unicode character category [Nd]). This includes [0-9], and also many other digit characters. If the <a class="reference internal" href="#re.ASCII" title="re.ASCII">ASCII</a> flag is used only [0-9] is matched (but the flag affects the entire regular expression, so in such cases using an explicit [0-9] may be a better choice).
For 8-bit (bytes) patterns:
Matches any decimal digit; this is equivalent to [0-9].
\D
Matches any character which is not a Unicode decimal digit. This is the opposite of \d. If the <a class="reference internal" href="#re.ASCII" title="re.ASCII">ASCII</a> flag is used this becomes the equivalent of [^0-9] (but the flag affects the entire regular expression, so in such cases using an explicit [^0-9] may be a better choice).
\s
For Unicode (str) patterns:
Matches Unicode whitespace characters (which includes [ \t\n\r\f\v], and also many other characters, for example the non-breaking spaces mandated by typography rules in many languages). If the <a class="reference internal" href="#re.ASCII" title="re.ASCII">ASCII</a> flag is used, only [ \t\n\r\f\v] is matched (but the flag affects the entire regular expression, so in such cases using an explicit [ \t\n\r\f\v] may be a better choice).
For 8-bit (bytes) patterns:
Matches characters considered whitespace in the ASCII character set; this is equivalent to [ \t\n\r\f\v].
\S
Matches any character which is not a Unicode whitespace character. This is the opposite of \s. If the <a class="reference internal" href="#re.ASCII" title="re.ASCII">ASCII</a> flag is used this becomes the equivalent of [^ \t\n\r\f\v] (but the flag affects the entire regular expression, so in such cases using an explicit [^ \t\n\r\f\v] may be a better choice).
\w
For Unicode (str) patterns:
Matches Unicode word characters; this includes most characters that can be part of a word in any language, as well as numbers and the underscore. If the <a class="reference internal" href="#re.ASCII" title="re.ASCII">ASCII</a> flag is used, only [a-zA-Z0-9_] is matched (but the flag affects the entire regular expression, so in such cases using an explicit [a-zA-Z0-9_] may be a better choice).
For 8-bit (bytes) patterns:
Matches characters considered alphanumeric in the ASCII character set; this is equivalent to [a-zA-Z0-9_].
\W
Matches any character which is not a Unicode word character. This is the opposite of \w. If the <a class="reference internal" href="#re.ASCII" title="re.ASCII">ASCII</a> flag is used this becomes the equivalent of [^a-zA-Z0-9_] (but the flag affects the entire regular expression, so in such cases using an explicit [^a-zA-Z0-9_] may be a better choice).
\Z
Matches only at the end of the string.

Most of the standard escapes supported by Python string literals are also accepted by the regular expression parser:

\<span class="n">a</span>      \<span class="n">b</span>      \<span class="n">f</span>      \<span class="n">n</span>
\<span class="n">r</span>      \<span class="n">t</span>      \<span class="n">u</span>      \<span class="n">U</span>
\<span class="n">v</span>      \<span class="n">x</span>      \\

(Note that \b is used to represent word boundaries, and means “backspace” only inside character classes.)

'\u' and '\U' escape sequences are only recognized in Unicode patterns. In bytes patterns they are not treated specially.

Octal escapes are included in a limited form. If the first digit is a 0, or if there are three octal digits, it is considered an octal escape. Otherwise, it is a group reference. As for string literals, octal escapes are always at most three digits in length.

Changed in version 3.3: The '\u' and '\U' escape sequences have been added.

Deprecated since version 3.5, will be removed in version 3.6: Unknown escapes consist of '\' and ASCII letter now raise a deprecation warning and will be forbidden in Python 3.6.

See also

Mastering Regular Expressions
Book on regular expressions by Jeffrey Friedl, published by O’Reilly. The second edition of the book no longer covers Python at all, but the first edition covered writing good regular expression patterns in great detail.

Sumario

6.2.2. Module Contents<a class="headerlink" href="#module-contents" title="Permalink to this headline">¶</a>

The module defines several functions, constants, and an exception. Some of the functions are simplified versions of the full featured methods for compiled regular expressions. Most non-trivial applications always use the compiled form.

re.compile(pattern, flags=0)<a class="headerlink" href="#re.compile" title="Permalink to this definition">¶</a>

Compile a regular expression pattern into a regular expression object, which can be used for matching using its <a class="reference internal" href="#re.regex.match" title="re.regex.match">match()</a> and <a class="reference internal" href="#re.regex.search" title="re.regex.search">search()</a> methods, described below.

The expression’s behaviour can be modified by specifying a flags value. Values can be any of the following variables, combined using bitwise OR (the | operator).

The sequence

<span class="n">prog</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="n">pattern</span><span class="p">)</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">prog</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="n">string</span><span class="p">)</span>

is equivalent to

<span class="n">result</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="n">pattern</span><span class="p">,</span> <span class="n">string</span><span class="p">)</span>

but using <a class="reference internal" href="#re.compile" title="re.compile">re.compile()</a> and saving the resulting regular expression object for reuse is more efficient when the expression will be used several times in a single program.

Note

The compiled versions of the most recent patterns passed to <a class="reference internal" href="#re.compile" title="re.compile">re.compile()</a> and the module-level matching functions are cached, so programs that use only a few regular expressions at a time needn’t worry about compiling regular expressions.

re.A<a class="headerlink" href="#re.A" title="Permalink to this definition">¶</a>
re.ASCII<a class="headerlink" href="#re.ASCII" title="Permalink to this definition">¶</a>

Make \w, \W, \b, \B, \d, \D, \s and \S perform ASCII-only matching instead of full Unicode matching. This is only meaningful for Unicode patterns, and is ignored for byte patterns.

Note that for backward compatibility, the re.U flag still exists (as well as its synonym re.UNICODE and its embedded counterpart (?u)), but these are redundant in Python 3 since matches are Unicode by default for strings (and Unicode matching isn’t allowed for bytes).

re.DEBUG<a class="headerlink" href="#re.DEBUG" title="Permalink to this definition">¶</a>

Display debug information about compiled expression.

re.I<a class="headerlink" href="#re.I" title="Permalink to this definition">¶</a>
re.IGNORECASE<a class="headerlink" href="#re.IGNORECASE" title="Permalink to this definition">¶</a>

Perform case-insensitive matching; expressions like [A-Z] will match lowercase letters, too. This is not affected by the current locale and works for Unicode characters as expected.

re.L<a class="headerlink" href="#re.L" title="Permalink to this definition">¶</a>
re.LOCALE<a class="headerlink" href="#re.LOCALE" title="Permalink to this definition">¶</a>

Make \w, \W, \b, \B, \s and \S dependent on the current locale. The use of this flag is discouraged as the locale mechanism is very unreliable, and it only handles one “culture” at a time anyway; you should use Unicode matching instead, which is the default in Python 3 for Unicode (str) patterns. This flag makes sense only with bytes patterns.

Deprecated since version 3.5, will be removed in version 3.6: Deprecated the use of <a class="reference internal" href="#re.LOCALE" title="re.LOCALE">re.LOCALE</a> with string patterns or <a class="reference internal" href="#re.ASCII" title="re.ASCII">re.ASCII</a>.

re.M<a class="headerlink" href="#re.M" title="Permalink to this definition">¶</a>
re.MULTILINE<a class="headerlink" href="#re.MULTILINE" title="Permalink to this definition">¶</a>

When specified, the pattern character '^' matches at the beginning of the string and at the beginning of each line (immediately following each newline); and the pattern character '$' matches at the end of the string and at the end of each line (immediately preceding each newline). By default, '^' matches only at the beginning of the string, and '$' only at the end of the string and immediately before the newline (if any) at the end of the string.

re.S<a class="headerlink" href="#re.S" title="Permalink to this definition">¶</a>
re.DOTALL<a class="headerlink" href="#re.DOTALL" title="Permalink to this definition">¶</a>

Make the '.' special character match any character at all, including a newline; without this flag, '.' will match anything except a newline.

re.X<a class="headerlink" href="#re.X" title="Permalink to this definition">¶</a>
re.VERBOSE<a class="headerlink" href="#re.VERBOSE" title="Permalink to this definition">¶</a>

This flag allows you to write regular expressions that look nicer and are more readable by allowing you to visually separate logical sections of the pattern and add comments. Whitespace within the pattern is ignored, except when in a character class or when preceded by an unescaped backslash. When a line contains a # that is not in a character class and is not preceded by an unescaped backslash, all characters from the leftmost such # through the end of the line are ignored.

This means that the two following regular expression objects that match a decimal number are functionally equal:

<span class="n">a</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s">r"""\d +  # the integral part</span>
<span class="s">                   \.    # the decimal point</span>
<span class="s">                   \d *  # some fractional digits"""</span><span class="p">,</span> <span class="n">re</span><span class="o">.</span><span class="n">X</span><span class="p">)</span>
<span class="n">b</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s">r"\d+\.\d*"</span><span class="p">)</span>
re.search(pattern, string, flags=0)<a class="headerlink" href="#re.search" title="Permalink to this definition">¶</a>

Scan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding <a class="reference internal" href="#match-objects">match object</a>. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.

re.match(pattern, string, flags=0)<a class="headerlink" href="#re.match" title="Permalink to this definition">¶</a>

If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding <a class="reference internal" href="#match-objects">match object</a>. Return None if the string does not match the pattern; note that this is different from a zero-length match.

Note that even in <a class="reference internal" href="#re.MULTILINE" title="re.MULTILINE">MULTILINE</a> mode, <a class="reference internal" href="#re.match" title="re.match">re.match()</a> will only match at the beginning of the string and not at the beginning of each line.

If you want to locate a match anywhere in string, use <a class="reference internal" href="#re.search" title="re.search">search()</a> instead (see also <a class="reference internal" href="#search-vs-match">search() vs. match()</a>).

re.fullmatch(pattern, string, flags=0)<a class="headerlink" href="#re.fullmatch" title="Permalink to this definition">¶</a>

If the whole string matches the regular expression pattern, return a corresponding <a class="reference internal" href="#match-objects">match object</a>. Return None if the string does not match the pattern; note that this is different from a zero-length match.

New in version 3.4.

re.split(pattern, string, maxsplit=0, flags=0)<a class="headerlink" href="#re.split" title="Permalink to this definition">¶</a>

Split string by the occurrences of pattern. If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list. If maxsplit is nonzero, at most maxsplit splits occur, and the remainder of the string is returned as the final element of the list.

<span class="gp">>>> </span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s">'\W+'</span><span class="p">,</span> <span class="s">'Words, words, words.'</span><span class="p">)</span>
<span class="go">['Words', 'words', 'words', '']</span>
<span class="gp">>>> </span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s">'(\W+)'</span><span class="p">,</span> <span class="s">'Words, words, words.'</span><span class="p">)</span>
<span class="go">['Words', ', ', 'words', ', ', 'words', '.', '']</span>
<span class="gp">>>> </span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s">'\W+'</span><span class="p">,</span> <span class="s">'Words, words, words.'</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="go">['Words', 'words, words.']</span>
<span class="gp">>>> </span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s">'[a-f]+'</span><span class="p">,</span> <span class="s">'0a3B9'</span><span class="p">,</span> <span class="n">flags</span><span class="o">=</span><span class="n">re</span><span class="o">.</span><span class="n">IGNORECASE</span><span class="p">)</span>
<span class="go">['0', '3', '9']</span>

If there are capturing groups in the separator and it matches at the start of the string, the result will start with an empty string. The same holds for the end of the string:

<span class="gp">>>> </span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s">'(\W+)'</span><span class="p">,</span> <span class="s">'...words, words...'</span><span class="p">)</span>
<span class="go">['', '...', 'words', ', ', 'words', '...', '']</span>

That way, separator components are always found at the same relative indices within the result list.

Note

<a class="reference internal" href="#re.split" title="re.split">split()</a> doesn’t currently split a string on an empty pattern match. For example:

<span class="gp">>>> </span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s">'x*'</span><span class="p">,</span> <span class="s">'axbc'</span><span class="p">)</span>
<span class="go">['a', 'bc']</span>

Even though 'x*' also matches 0 ‘x’ before ‘a’, between ‘b’ and ‘c’, and after ‘c’, currently these matches are ignored. The correct behavior (i.e. splitting on empty matches too and returning [, 'a', 'b', 'c', ]) will be implemented in future versions of Python, but since this is a backward incompatible change, a <a class="reference internal" href="exceptions.html#FutureWarning" title="FutureWarning">FutureWarning</a> will be raised in the meanwhile.

Patterns that can only match empty strings currently never split the string. Since this doesn’t match the expected behavior, a <a class="reference internal" href="exceptions.html#ValueError" title="ValueError">ValueError</a> will be raised starting from Python 3.5:

<span class="gp">>>> </span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s">"^$"</span><span class="p">,</span> <span class="s">"foo</span><span class="se">\n\n</span><span class="s">bar</span><span class="se">\n</span><span class="s">"</span><span class="p">,</span> <span class="n">flags</span><span class="o">=</span><span class="n">re</span><span class="o">.</span><span class="n">M</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">"<stdin>"</span>, line <span class="m">1</span>, in <span class="n"><module></span>
  <span class="c">...</span>
<span class="gr">ValueError</span>: <span class="n">split() requires a non-empty pattern match.</span>

Changed in version 3.1: Added the optional flags argument.

Changed in version 3.5: Splitting on a pattern that could match an empty string now raises a warning. Patterns that can only match empty strings are now rejected.

re.findall(pattern, string, flags=0)<a class="headerlink" href="#re.findall" title="Permalink to this definition">¶</a>

Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result unless they touch the beginning of another match.

re.finditer(pattern, string, flags=0)<a class="headerlink" href="#re.finditer" title="Permalink to this definition">¶</a>

Return an <a class="reference internal" href="../glossary.html#term-iterator">iterator</a> yielding <a class="reference internal" href="#match-objects">match objects</a> over all non-overlapping matches for the RE pattern in string. The string is scanned left-to-right, and matches are returned in the order found. Empty matches are included in the result unless they touch the beginning of another match.

re.sub(pattern, repl, string, count=0, flags=0)<a class="headerlink" href="#re.sub" title="Permalink to this definition">¶</a>

Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isn’t found, string is returned unchanged. repl can be a string or a function; if it is a string, any backslash escapes in it are processed. That is, \n is converted to a single newline character, \r is converted to a carriage return, and so forth. Unknown escapes such as \& are left alone. Backreferences, such as \6, are replaced with the substring matched by group 6 in the pattern. For example:

<span class="gp">>>> </span><span class="n">re</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="s">r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):'</span><span class="p">,</span>
<span class="gp">... </span>       <span class="s">r'static PyObject*\npy_\1(void)\n{'</span><span class="p">,</span>
<span class="gp">... </span>       <span class="s">'def myfunc():'</span><span class="p">)</span>
<span class="go">'static PyObject*\npy_myfunc(void)\n{'</span>

If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string. For example:

<span class="gp">>>> </span><span class="k">def</span> <span class="nf">dashrepl</span><span class="p">(</span><span class="n">matchobj</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">if</span> <span class="n">matchobj</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span> <span class="o">==</span> <span class="s">'-'</span><span class="p">:</span> <span class="k">return</span> <span class="s">' '</span>
<span class="gp">... </span>    <span class="k">else</span><span class="p">:</span> <span class="k">return</span> <span class="s">'-'</span>
<span class="gp">>>> </span><span class="n">re</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="s">'-{1,2}'</span><span class="p">,</span> <span class="n">dashrepl</span><span class="p">,</span> <span class="s">'pro----gram-files'</span><span class="p">)</span>
<span class="go">'pro--gram files'</span>
<span class="gp">>>> </span><span class="n">re</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="s">r'\sAND\s'</span><span class="p">,</span> <span class="s">' & '</span><span class="p">,</span> <span class="s">'Baked Beans And Spam'</span><span class="p">,</span> <span class="n">flags</span><span class="o">=</span><span class="n">re</span><span class="o">.</span><span class="n">IGNORECASE</span><span class="p">)</span>
<span class="go">'Baked Beans & Spam'</span>

The pattern may be a string or an RE object.

The optional argument count is the maximum number of pattern occurrences to be replaced; count must be a non-negative integer. If omitted or zero, all occurrences will be replaced. Empty matches for the pattern are replaced only when not adjacent to a previous match, so sub('x*', '-', 'abc') returns '-a-b-c-'.

In string-type repl arguments, in addition to the character escapes and backreferences described above, \g<name> will use the substring matched by the group named name, as defined by the (?P<name>...) syntax. \g<number> uses the corresponding group number; \g<2> is therefore equivalent to \2, but isn’t ambiguous in a replacement such as \g<2>0. \20 would be interpreted as a reference to group 20, not a reference to group 2 followed by the literal character '0'. The backreference \g<0> substitutes in the entire substring matched by the RE.

Changed in version 3.1: Added the optional flags argument.

Changed in version 3.5: Unmatched groups are replaced with an empty string.

Deprecated since version 3.5, will be removed in version 3.6: Unknown escapes consist of '\' and ASCII letter now raise a deprecation warning and will be forbidden in Python 3.6.

re.subn(pattern, repl, string, count=0, flags=0)<a class="headerlink" href="#re.subn" title="Permalink to this definition">¶</a>

Perform the same operation as <a class="reference internal" href="#re.sub" title="re.sub">sub()</a>, but return a tuple (new_string, number_of_subs_made).

Changed in version 3.1: Added the optional flags argument.

Changed in version 3.5: Unmatched groups are replaced with an empty string.

re.escape(string)<a class="headerlink" href="#re.escape" title="Permalink to this definition">¶</a>

Escape all the characters in pattern except ASCII letters, numbers and '_'. This is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.

Changed in version 3.3: The '_' character is no longer escaped.

re.purge()<a class="headerlink" href="#re.purge" title="Permalink to this definition">¶</a>

Clear the regular expression cache.

exception re.error(msg, pattern=None, pos=None)<a class="headerlink" href="#re.error" title="Permalink to this definition">¶</a>

Exception raised when a string passed to one of the functions here is not a valid regular expression (for example, it might contain unmatched parentheses) or when some other error occurs during compilation or matching. It is never an error if a string contains no match for a pattern. The error instance has the following additional attributes:

msg<a class="headerlink" href="#re.error.msg" title="Permalink to this definition">¶</a>

The unformatted error message.

pattern<a class="headerlink" href="#re.error.pattern" title="Permalink to this definition">¶</a>

The regular expression pattern.

pos<a class="headerlink" href="#re.error.pos" title="Permalink to this definition">¶</a>

The index of pattern where compilation failed.

lineno<a class="headerlink" href="#re.error.lineno" title="Permalink to this definition">¶</a>

The line corresponding to pos.

colno<a class="headerlink" href="#re.error.colno" title="Permalink to this definition">¶</a>

The column corresponding to pos.

Changed in version 3.5: Added additional attributes.

6.2.3. Regular Expression Objects<a class="headerlink" href="#regular-expression-objects" title="Permalink to this headline">¶</a>

Compiled regular expression objects support the following methods and attributes:

regex.search(string[, pos[, endpos]])<a class="headerlink" href="#re.regex.search" title="Permalink to this definition">¶</a>

Scan through string looking for a location where this regular expression produces a match, and return a corresponding <a class="reference internal" href="#match-objects">match object</a>. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.

The optional second parameter pos gives an index in the string where the search is to start; it defaults to 0. This is not completely equivalent to slicing the string; the '^' pattern character matches at the real beginning of the string and at positions just after a newline, but not necessarily at the index where the search is to start.

The optional parameter endpos limits how far the string will be searched; it will be as if the string is endpos characters long, so only the characters from pos to endpos - 1 will be searched for a match. If endpos is less than pos, no match will be found; otherwise, if rx is a compiled regular expression object, rx.search(string, 0, 50) is equivalent to rx.search(string[:50], 0).

<span class="gp">>>> </span><span class="n">pattern</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s">"d"</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">pattern</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s">"dog"</span><span class="p">)</span>     <span class="c"># Match at index 0</span>
<span class="go"><_sre.SRE_Match object; span=(0, 1), match='d'></span>
<span class="gp">>>> </span><span class="n">pattern</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s">"dog"</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>  <span class="c"># No match; search doesn't include the "d"</span>
regex.match(string[, pos[, endpos]])<a class="headerlink" href="#re.regex.match" title="Permalink to this definition">¶</a>

If zero or more characters at the beginning of string match this regular expression, return a corresponding <a class="reference internal" href="#match-objects">match object</a>. Return None if the string does not match the pattern; note that this is different from a zero-length match.

The optional pos and endpos parameters have the same meaning as for the <a class="reference internal" href="#re.regex.search" title="re.regex.search">search()</a> method.

<span class="gp">>>> </span><span class="n">pattern</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s">"o"</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">pattern</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">"dog"</span><span class="p">)</span>      <span class="c"># No match as "o" is not at the start of "dog".</span>
<span class="gp">>>> </span><span class="n">pattern</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">"dog"</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>   <span class="c"># Match as "o" is the 2nd character of "dog".</span>
<span class="go"><_sre.SRE_Match object; span=(1, 2), match='o'></span>

If you want to locate a match anywhere in string, use <a class="reference internal" href="#re.regex.search" title="re.regex.search">search()</a> instead (see also <a class="reference internal" href="#search-vs-match">search() vs. match()</a>).

regex.fullmatch(string[, pos[, endpos]])<a class="headerlink" href="#re.regex.fullmatch" title="Permalink to this definition">¶</a>

If the whole string matches this regular expression, return a corresponding <a class="reference internal" href="#match-objects">match object</a>. Return None if the string does not match the pattern; note that this is different from a zero-length match.

The optional pos and endpos parameters have the same meaning as for the <a class="reference internal" href="#re.regex.search" title="re.regex.search">search()</a> method.

<span class="gp">>>> </span><span class="n">pattern</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s">"o[gh]"</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">pattern</span><span class="o">.</span><span class="n">fullmatch</span><span class="p">(</span><span class="s">"dog"</span><span class="p">)</span>      <span class="c"># No match as "o" is not at the start of "dog".</span>
<span class="gp">>>> </span><span class="n">pattern</span><span class="o">.</span><span class="n">fullmatch</span><span class="p">(</span><span class="s">"ogre"</span><span class="p">)</span>     <span class="c"># No match as not the full string matches.</span>
<span class="gp">>>> </span><span class="n">pattern</span><span class="o">.</span><span class="n">fullmatch</span><span class="p">(</span><span class="s">"doggie"</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>   <span class="c"># Matches within given limits.</span>
<span class="go"><_sre.SRE_Match object; span=(1, 3), match='og'></span>

New in version 3.4.

regex.split(string, maxsplit=0)<a class="headerlink" href="#re.regex.split" title="Permalink to this definition">¶</a>

Identical to the <a class="reference internal" href="#re.split" title="re.split">split()</a> function, using the compiled pattern.

regex.findall(string[, pos[, endpos]])<a class="headerlink" href="#re.regex.findall" title="Permalink to this definition">¶</a>

Similar to the <a class="reference internal" href="#re.findall" title="re.findall">findall()</a> function, using the compiled pattern, but also accepts optional pos and endpos parameters that limit the search region like for <a class="reference internal" href="#re.match" title="re.match">match()</a>.

regex.finditer(string[, pos[, endpos]])<a class="headerlink" href="#re.regex.finditer" title="Permalink to this definition">¶</a>

Similar to the <a class="reference internal" href="#re.finditer" title="re.finditer">finditer()</a> function, using the compiled pattern, but also accepts optional pos and endpos parameters that limit the search region like for <a class="reference internal" href="#re.match" title="re.match">match()</a>.

regex.sub(repl, string, count=0)<a class="headerlink" href="#re.regex.sub" title="Permalink to this definition">¶</a>

Identical to the <a class="reference internal" href="#re.sub" title="re.sub">sub()</a> function, using the compiled pattern.

regex.subn(repl, string, count=0)<a class="headerlink" href="#re.regex.subn" title="Permalink to this definition">¶</a>

Identical to the <a class="reference internal" href="#re.subn" title="re.subn">subn()</a> function, using the compiled pattern.

regex.flags<a class="headerlink" href="#re.regex.flags" title="Permalink to this definition">¶</a>

The regex matching flags. This is a combination of the flags given to <a class="reference internal" href="#re.compile" title="re.compile">compile()</a>, any (?...) inline flags in the pattern, and implicit flags such as UNICODE if the pattern is a Unicode string.

regex.groups<a class="headerlink" href="#re.regex.groups" title="Permalink to this definition">¶</a>

The number of capturing groups in the pattern.

regex.groupindex<a class="headerlink" href="#re.regex.groupindex" title="Permalink to this definition">¶</a>

A dictionary mapping any symbolic group names defined by (?P<id>) to group numbers. The dictionary is empty if no symbolic groups were used in the pattern.

regex.pattern<a class="headerlink" href="#re.regex.pattern" title="Permalink to this definition">¶</a>

The pattern string from which the RE object was compiled.

6.2.4. Match Objects<a class="headerlink" href="#match-objects" title="Permalink to this headline">¶</a>

Match objects always have a boolean value of True. Since <a class="reference internal" href="#re.regex.match" title="re.regex.match">match()</a> and <a class="reference internal" href="#re.regex.search" title="re.regex.search">search()</a> return None when there is no match, you can test whether there was a match with a simple if statement:

<span class="n">match</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="n">pattern</span><span class="p">,</span> <span class="n">string</span><span class="p">)</span>
<span class="k">if</span> <span class="n">match</span><span class="p">:</span>
    <span class="n">process</span><span class="p">(</span><span class="n">match</span><span class="p">)</span>

Match objects support the following methods and attributes:

match.expand(template)<a class="headerlink" href="#re.match.expand" title="Permalink to this definition">¶</a>

Return the string obtained by doing backslash substitution on the template string template, as done by the <a class="reference internal" href="#re.regex.sub" title="re.regex.sub">sub()</a> method. Escapes such as \n are converted to the appropriate characters, and numeric backreferences (\1, \2) and named backreferences (\g<1>, \g<name>) are replaced by the contents of the corresponding group.

Changed in version 3.5: Unmatched groups are replaced with an empty string.

match.group([group1, ...])<a class="headerlink" href="#re.match.group" title="Permalink to this definition">¶</a>

Returns one or more subgroups of the match. If there is a single argument, the result is a single string; if there are multiple arguments, the result is a tuple with one item per argument. Without arguments, group1 defaults to zero (the whole match is returned). If a groupN argument is zero, the corresponding return value is the entire matching string; if it is in the inclusive range [1..99], it is the string matching the corresponding parenthesized group. If a group number is negative or larger than the number of groups defined in the pattern, an <a class="reference internal" href="exceptions.html#IndexError" title="IndexError">IndexError</a> exception is raised. If a group is contained in a part of the pattern that did not match, the corresponding result is None. If a group is contained in a part of the pattern that matched multiple times, the last match is returned.

<span class="gp">>>> </span><span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">r"(\w+) (\w+)"</span><span class="p">,</span> <span class="s">"Isaac Newton, physicist"</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>       <span class="c"># The entire match</span>
<span class="go">'Isaac Newton'</span>
<span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>       <span class="c"># The first parenthesized subgroup.</span>
<span class="go">'Isaac'</span>
<span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>       <span class="c"># The second parenthesized subgroup.</span>
<span class="go">'Newton'</span>
<span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>    <span class="c"># Multiple arguments give us a tuple.</span>
<span class="go">('Isaac', 'Newton')</span>

If the regular expression uses the (?P<name>...) syntax, the groupN arguments may also be strings identifying groups by their group name. If a string argument is not used as a group name in the pattern, an <a class="reference internal" href="exceptions.html#IndexError" title="IndexError">IndexError</a> exception is raised.

A moderately complicated example:

<span class="gp">>>> </span><span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">r"(?P<first_name>\w+) (?P<last_name>\w+)"</span><span class="p">,</span> <span class="s">"Malcolm Reynolds"</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="s">'first_name'</span><span class="p">)</span>
<span class="go">'Malcolm'</span>
<span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="s">'last_name'</span><span class="p">)</span>
<span class="go">'Reynolds'</span>

Named groups can also be referred to by their index:

<span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="go">'Malcolm'</span>
<span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>
<span class="go">'Reynolds'</span>

If a group matches multiple times, only the last match is accessible:

<span class="gp">>>> </span><span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">r"(..)+"</span><span class="p">,</span> <span class="s">"a1b2c3"</span><span class="p">)</span>  <span class="c"># Matches 3 times.</span>
<span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>                        <span class="c"># Returns only the last match.</span>
<span class="go">'c3'</span>
match.groups(default=None)<a class="headerlink" href="#re.match.groups" title="Permalink to this definition">¶</a>

Return a tuple containing all the subgroups of the match, from 1 up to however many groups are in the pattern. The default argument is used for groups that did not participate in the match; it defaults to None.

For example:

<span class="gp">>>> </span><span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">r"(\d+)\.(\d+)"</span><span class="p">,</span> <span class="s">"24.1632"</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">groups</span><span class="p">()</span>
<span class="go">('24', '1632')</span>

If we make the decimal place and everything after it optional, not all groups might participate in the match. These groups will default to None unless the default argument is given:

<span class="gp">>>> </span><span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">r"(\d+)\.?(\d+)?"</span><span class="p">,</span> <span class="s">"24"</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">groups</span><span class="p">()</span>      <span class="c"># Second group defaults to None.</span>
<span class="go">('24', None)</span>
<span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">groups</span><span class="p">(</span><span class="s">'0'</span><span class="p">)</span>   <span class="c"># Now, the second group defaults to '0'.</span>
<span class="go">('24', '0')</span>
match.groupdict(default=None)<a class="headerlink" href="#re.match.groupdict" title="Permalink to this definition">¶</a>

Return a dictionary containing all the named subgroups of the match, keyed by the subgroup name. The default argument is used for groups that did not participate in the match; it defaults to None. For example:

<span class="gp">>>> </span><span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">r"(?P<first_name>\w+) (?P<last_name>\w+)"</span><span class="p">,</span> <span class="s">"Malcolm Reynolds"</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">groupdict</span><span class="p">()</span>
<span class="go">{'first_name': 'Malcolm', 'last_name': 'Reynolds'}</span>
match.start([group])<a class="headerlink" href="#re.match.start" title="Permalink to this definition">¶</a>
match.end([group])<a class="headerlink" href="#re.match.end" title="Permalink to this definition">¶</a>

Return the indices of the start and end of the substring matched by group; group defaults to zero (meaning the whole matched substring). Return -1 if group exists but did not contribute to the match. For a match object m, and a group g that did contribute to the match, the substring matched by group g (equivalent to m.group(g)) is

<span class="n">m</span><span class="o">.</span><span class="n">string</span><span class="p">[</span><span class="n">m</span><span class="o">.</span><span class="n">start</span><span class="p">(</span><span class="n">g</span><span class="p">):</span><span class="n">m</span><span class="o">.</span><span class="n">end</span><span class="p">(</span><span class="n">g</span><span class="p">)]</span>

Note that m.start(group) will equal m.end(group) if group matched a null string. For example, after m = re.search('b(c?)', 'cba'), m.start(0) is 1, m.end(0) is 2, m.start(1) and m.end(1) are both 2, and m.start(2) raises an <a class="reference internal" href="exceptions.html#IndexError" title="IndexError">IndexError</a> exception.

An example that will remove remove_this from email addresses:

<span class="gp">>>> </span><span class="n">email</span> <span class="o">=</span> <span class="s">"tony@tiremove_thisger.net"</span>
<span class="gp">>>> </span><span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s">"remove_this"</span><span class="p">,</span> <span class="n">email</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">email</span><span class="p">[:</span><span class="n">m</span><span class="o">.</span><span class="n">start</span><span class="p">()]</span> <span class="o">+</span> <span class="n">email</span><span class="p">[</span><span class="n">m</span><span class="o">.</span><span class="n">end</span><span class="p">():]</span>
<span class="go">'tony@tiger.net'</span>
match.span([group])<a class="headerlink" href="#re.match.span" title="Permalink to this definition">¶</a>

For a match m, return the 2-tuple (m.start(group), m.end(group)). Note that if group did not contribute to the match, this is (-1, -1). group defaults to zero, the entire match.

match.pos<a class="headerlink" href="#re.match.pos" title="Permalink to this definition">¶</a>

The value of pos which was passed to the <a class="reference internal" href="#re.regex.search" title="re.regex.search">search()</a> or <a class="reference internal" href="#re.regex.match" title="re.regex.match">match()</a> method of a <a class="reference internal" href="#re-objects">regex object</a>. This is the index into the string at which the RE engine started looking for a match.

match.endpos<a class="headerlink" href="#re.match.endpos" title="Permalink to this definition">¶</a>

The value of endpos which was passed to the <a class="reference internal" href="#re.regex.search" title="re.regex.search">search()</a> or <a class="reference internal" href="#re.regex.match" title="re.regex.match">match()</a> method of a <a class="reference internal" href="#re-objects">regex object</a>. This is the index into the string beyond which the RE engine will not go.

match.lastindex<a class="headerlink" href="#re.match.lastindex" title="Permalink to this definition">¶</a>

The integer index of the last matched capturing group, or None if no group was matched at all. For example, the expressions (a)b, ((a)(b)), and ((ab)) will have lastindex == 1 if applied to the string 'ab', while the expression (a)(b) will have lastindex == 2, if applied to the same string.

match.lastgroup<a class="headerlink" href="#re.match.lastgroup" title="Permalink to this definition">¶</a>

The name of the last matched capturing group, or None if the group didn’t have a name, or if no group was matched at all.

match.re<a class="headerlink" href="#re.match.re" title="Permalink to this definition">¶</a>

The regular expression object whose <a class="reference internal" href="#re.regex.match" title="re.regex.match">match()</a> or <a class="reference internal" href="#re.regex.search" title="re.regex.search">search()</a> method produced this match instance.

match.string<a class="headerlink" href="#re.match.string" title="Permalink to this definition">¶</a>

The string passed to <a class="reference internal" href="#re.regex.match" title="re.regex.match">match()</a> or <a class="reference internal" href="#re.regex.search" title="re.regex.search">search()</a>.

6.2.5. Regular Expression Examples<a class="headerlink" href="#regular-expression-examples" title="Permalink to this headline">¶</a>

6.2.5.1. Checking for a Pair<a class="headerlink" href="#checking-for-a-pair" title="Permalink to this headline">¶</a>

In this example, we’ll use the following helper function to display match objects a little more gracefully:

<span class="k">def</span> <span class="nf">displaymatch</span><span class="p">(</span><span class="n">match</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">match</span> <span class="ow">is</span> <span class="k">None</span><span class="p">:</span>
        <span class="k">return</span> <span class="k">None</span>
    <span class="k">return</span> <span class="s">'<Match: %r, groups=%r>'</span> <span class="o">%</span> <span class="p">(</span><span class="n">match</span><span class="o">.</span><span class="n">group</span><span class="p">(),</span> <span class="n">match</span><span class="o">.</span><span class="n">groups</span><span class="p">())</span>

Suppose you are writing a poker program where a player’s hand is represented as a 5-character string with each character representing a card, “a” for ace, “k” for king, “q” for queen, “j” for jack, “t” for 10, and “2” through “9” representing the card with that value.

To see if a given string is a valid hand, one could do the following:

<span class="gp">>>> </span><span class="n">valid</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s">r"^[a2-9tjqk]{5}$"</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">displaymatch</span><span class="p">(</span><span class="n">valid</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">"akt5q"</span><span class="p">))</span>  <span class="c"># Valid.</span>
<span class="go">"<Match: 'akt5q', groups=()>"</span>
<span class="gp">>>> </span><span class="n">displaymatch</span><span class="p">(</span><span class="n">valid</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">"akt5e"</span><span class="p">))</span>  <span class="c"># Invalid.</span>
<span class="gp">>>> </span><span class="n">displaymatch</span><span class="p">(</span><span class="n">valid</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">"akt"</span><span class="p">))</span>    <span class="c"># Invalid.</span>
<span class="gp">>>> </span><span class="n">displaymatch</span><span class="p">(</span><span class="n">valid</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">"727ak"</span><span class="p">))</span>  <span class="c"># Valid.</span>
<span class="go">"<Match: '727ak', groups=()>"</span>

That last hand, "727ak", contained a pair, or two of the same valued cards. To match this with a regular expression, one could use backreferences as such:

<span class="gp">>>> </span><span class="n">pair</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s">r".*(.).*\1"</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">displaymatch</span><span class="p">(</span><span class="n">pair</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">"717ak"</span><span class="p">))</span>     <span class="c"># Pair of 7s.</span>
<span class="go">"<Match: '717', groups=('7',)>"</span>
<span class="gp">>>> </span><span class="n">displaymatch</span><span class="p">(</span><span class="n">pair</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">"718ak"</span><span class="p">))</span>     <span class="c"># No pairs.</span>
<span class="gp">>>> </span><span class="n">displaymatch</span><span class="p">(</span><span class="n">pair</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">"354aa"</span><span class="p">))</span>     <span class="c"># Pair of aces.</span>
<span class="go">"<Match: '354aa', groups=('a',)>"</span>

To find out what card the pair consists of, one could use the <a class="reference internal" href="#re.match.group" title="re.match.group">group()</a> method of the match object in the following manner:

<span class="gp">>>> </span><span class="n">pair</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">"717ak"</span><span class="p">)</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="go">'7'</span>

<span class="go"># Error because re.match() returns None, which doesn't have a group() method:</span>
<span class="gp">>>> </span><span class="n">pair</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">"718ak"</span><span class="p">)</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">"<pyshell#23>"</span>, line <span class="m">1</span>, in <span class="n"><module></span>
    <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">r".*(.).*\1"</span><span class="p">,</span> <span class="s">"718ak"</span><span class="p">)</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="gr">AttributeError</span>: <span class="n">'NoneType' object has no attribute 'group'</span>

<span class="gp">>>> </span><span class="n">pair</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">"354aa"</span><span class="p">)</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="go">'a'</span>

6.2.5.2. Simulating scanf()<a class="headerlink" href="#simulating-scanf" title="Permalink to this headline">¶</a>

Python does not currently have an equivalent to scanf(). Regular expressions are generally more powerful, though also more verbose, than scanf() format strings. The table below offers some more-or-less equivalent mappings between scanf() format tokens and regular expressions.

<colgroup> <col width="42%" /> <col width="58%" /> </colgroup> <thead valign="bottom"> </thead> <tbody valign="top"> </tbody>
scanf() Token Regular Expression
%c .
%5c .{5}
%d [-+]?\d+
%e, %E, %f, %g [-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?
%i [-+]?(0[xX][\dA-Fa-f]+|0[0-7]*|\d+)
%o [-+]?[0-7]+
%s \S+
%u \d+
%x, %X [-+]?(0[xX])?[\dA-Fa-f]+

To extract the filename and numbers from a string like

<span class="o">/</span><span class="n">usr</span><span class="o">/</span><span class="n">sbin</span><span class="o">/</span><span class="n">sendmail</span> <span class="o">-</span> <span class="mi">0</span> <span class="n">errors</span><span class="p">,</span> <span class="mi">4</span> <span class="n">warnings</span>

you would use a scanf() format like

<span class="o">%</span><span class="n">s</span> <span class="o">-</span> <span class="o">%</span><span class="n">d</span> <span class="n">errors</span><span class="p">,</span> <span class="o">%</span><span class="n">d</span> <span class="n">warnings</span>

The equivalent regular expression would be

<span class="p">(</span>\<span class="n">S</span><span class="o">+</span><span class="p">)</span> <span class="o">-</span> <span class="p">(</span>\<span class="n">d</span><span class="o">+</span><span class="p">)</span> <span class="n">errors</span><span class="p">,</span> <span class="p">(</span>\<span class="n">d</span><span class="o">+</span><span class="p">)</span> <span class="n">warnings</span>

6.2.5.3. search() vs. match()<a class="headerlink" href="#search-vs-match" title="Permalink to this headline">¶</a>

Python offers two different primitive operations based on regular expressions: <a class="reference internal" href="#re.match" title="re.match">re.match()</a> checks for a match only at the beginning of the string, while <a class="reference internal" href="#re.search" title="re.search">re.search()</a> checks for a match anywhere in the string (this is what Perl does by default).

For example:

<span class="gp">>>> </span><span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">"c"</span><span class="p">,</span> <span class="s">"abcdef"</span><span class="p">)</span>  <span class="c"># No match</span>
<span class="gp">>>> </span><span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s">"c"</span><span class="p">,</span> <span class="s">"abcdef"</span><span class="p">)</span> <span class="c"># Match</span>
<span class="go"><_sre.SRE_Match object; span=(2, 3), match='c'></span>

Regular expressions beginning with '^' can be used with <a class="reference internal" href="#re.search" title="re.search">search()</a> to restrict the match at the beginning of the string:

<span class="gp">>>> </span><span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">"c"</span><span class="p">,</span> <span class="s">"abcdef"</span><span class="p">)</span>  <span class="c"># No match</span>
<span class="gp">>>> </span><span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s">"^c"</span><span class="p">,</span> <span class="s">"abcdef"</span><span class="p">)</span> <span class="c"># No match</span>
<span class="gp">>>> </span><span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s">"^a"</span><span class="p">,</span> <span class="s">"abcdef"</span><span class="p">)</span>  <span class="c"># Match</span>
<span class="go"><_sre.SRE_Match object; span=(0, 1), match='a'></span>

Note however that in <a class="reference internal" href="#re.MULTILINE" title="re.MULTILINE">MULTILINE</a> mode <a class="reference internal" href="#re.match" title="re.match">match()</a> only matches at the beginning of the string, whereas using <a class="reference internal" href="#re.search" title="re.search">search()</a> with a regular expression beginning with '^' will match at the beginning of each line.

<span class="gp">>>> </span><span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">'X'</span><span class="p">,</span> <span class="s">'A</span><span class="se">\n</span><span class="s">B</span><span class="se">\n</span><span class="s">X'</span><span class="p">,</span> <span class="n">re</span><span class="o">.</span><span class="n">MULTILINE</span><span class="p">)</span>  <span class="c"># No match</span>
<span class="gp">>>> </span><span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s">'^X'</span><span class="p">,</span> <span class="s">'A</span><span class="se">\n</span><span class="s">B</span><span class="se">\n</span><span class="s">X'</span><span class="p">,</span> <span class="n">re</span><span class="o">.</span><span class="n">MULTILINE</span><span class="p">)</span>  <span class="c"># Match</span>
<span class="go"><_sre.SRE_Match object; span=(4, 5), match='X'></span>

6.2.5.4. Making a Phonebook<a class="headerlink" href="#making-a-phonebook" title="Permalink to this headline">¶</a>

<a class="reference internal" href="#re.split" title="re.split">split()</a> splits a string into a list delimited by the passed pattern. The method is invaluable for converting textual data into data structures that can be easily read and modified by Python as demonstrated in the following example that creates a phonebook.

First, here is the input. Normally it may come from a file, here we are using triple-quoted string syntax:

<span class="gp">>>> </span><span class="n">text</span> <span class="o">=</span> <span class="s">"""Ross McFluff: 834.345.1254 155 Elm Street</span>
<span class="gp">...</span><span class="s"></span>
<span class="gp">... </span><span class="s">Ronald Heathmore: 892.345.3428 436 Finley Avenue</span>
<span class="gp">... </span><span class="s">Frank Burger: 925.541.7625 662 South Dogwood Way</span>
<span class="gp">...</span><span class="s"></span>
<span class="gp">...</span><span class="s"></span>
<span class="gp">... </span><span class="s">Heather Albrecht: 548.326.4584 919 Park Place"""</span>

The entries are separated by one or more newlines. Now we convert the string into a list with each nonempty line having its own entry:

<span class="gp">>>> </span><span class="n">entries</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s">"</span><span class="se">\n</span><span class="s">+"</span><span class="p">,</span> <span class="n">text</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">entries</span>
<span class="go">['Ross McFluff: 834.345.1254 155 Elm Street',</span>
<span class="go">'Ronald Heathmore: 892.345.3428 436 Finley Avenue',</span>
<span class="go">'Frank Burger: 925.541.7625 662 South Dogwood Way',</span>
<span class="go">'Heather Albrecht: 548.326.4584 919 Park Place']</span>

Finally, split each entry into a list with first name, last name, telephone number, and address. We use the maxsplit parameter of <a class="reference internal" href="#re.split" title="re.split">split()</a> because the address has spaces, our splitting pattern, in it:

<span class="gp">>>> </span><span class="p">[</span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s">":? "</span><span class="p">,</span> <span class="n">entry</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span> <span class="k">for</span> <span class="n">entry</span> <span class="ow">in</span> <span class="n">entries</span><span class="p">]</span>
<span class="go">[['Ross', 'McFluff', '834.345.1254', '155 Elm Street'],</span>
<span class="go">['Ronald', 'Heathmore', '892.345.3428', '436 Finley Avenue'],</span>
<span class="go">['Frank', 'Burger', '925.541.7625', '662 South Dogwood Way'],</span>
<span class="go">['Heather', 'Albrecht', '548.326.4584', '919 Park Place']]</span>

The :? pattern matches the colon after the last name, so that it does not occur in the result list. With a maxsplit of 4, we could separate the house number from the street name:

<span class="gp">>>> </span><span class="p">[</span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s">":? "</span><span class="p">,</span> <span class="n">entry</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span> <span class="k">for</span> <span class="n">entry</span> <span class="ow">in</span> <span class="n">entries</span><span class="p">]</span>
<span class="go">[['Ross', 'McFluff', '834.345.1254', '155', 'Elm Street'],</span>
<span class="go">['Ronald', 'Heathmore', '892.345.3428', '436', 'Finley Avenue'],</span>
<span class="go">['Frank', 'Burger', '925.541.7625', '662', 'South Dogwood Way'],</span>
<span class="go">['Heather', 'Albrecht', '548.326.4584', '919', 'Park Place']]</span>

6.2.5.5. Text Munging<a class="headerlink" href="#text-munging" title="Permalink to this headline">¶</a>

<a class="reference internal" href="#re.sub" title="re.sub">sub()</a> replaces every occurrence of a pattern with a string or the result of a function. This example demonstrates using <a class="reference internal" href="#re.sub" title="re.sub">sub()</a> with a function to “munge” text, or randomize the order of all the characters in each word of a sentence except for the first and last characters:

<span class="gp">>>> </span><span class="k">def</span> <span class="nf">repl</span><span class="p">(</span><span class="n">m</span><span class="p">):</span>
<span class="gp">... </span>  <span class="n">inner_word</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">2</span><span class="p">))</span>
<span class="gp">... </span>  <span class="n">random</span><span class="o">.</span><span class="n">shuffle</span><span class="p">(</span><span class="n">inner_word</span><span class="p">)</span>
<span class="gp">... </span>  <span class="k">return</span> <span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="o">+</span> <span class="s">""</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">inner_word</span><span class="p">)</span> <span class="o">+</span> <span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">text</span> <span class="o">=</span> <span class="s">"Professor Abdolmalek, please report your absences promptly."</span>
<span class="gp">>>> </span><span class="n">re</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="s">r"(\w)(\w+)(\w)"</span><span class="p">,</span> <span class="n">repl</span><span class="p">,</span> <span class="n">text</span><span class="p">)</span>
<span class="go">'Poefsrosr Aealmlobdk, pslaee reorpt your abnseces plmrptoy.'</span>
<span class="gp">>>> </span><span class="n">re</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="s">r"(\w)(\w+)(\w)"</span><span class="p">,</span> <span class="n">repl</span><span class="p">,</span> <span class="n">text</span><span class="p">)</span>
<span class="go">'Pofsroser Aodlambelk, plasee reoprt yuor asnebces potlmrpy.'</span>

6.2.5.6. Finding all Adverbs<a class="headerlink" href="#finding-all-adverbs" title="Permalink to this headline">¶</a>

<a class="reference internal" href="#re.findall" title="re.findall">findall()</a> matches all occurrences of a pattern, not just the first one as <a class="reference internal" href="#re.search" title="re.search">search()</a> does. For example, if one was a writer and wanted to find all of the adverbs in some text, he or she might use <a class="reference internal" href="#re.findall" title="re.findall">findall()</a> in the following manner:

<span class="gp">>>> </span><span class="n">text</span> <span class="o">=</span> <span class="s">"He was carefully disguised but captured quickly by police."</span>
<span class="gp">>>> </span><span class="n">re</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="s">r"\w+ly"</span><span class="p">,</span> <span class="n">text</span><span class="p">)</span>
<span class="go">['carefully', 'quickly']</span>

6.2.5.7. Finding all Adverbs and their Positions<a class="headerlink" href="#finding-all-adverbs-and-their-positions" title="Permalink to this headline">¶</a>

If one wants more information about all matches of a pattern than the matched text, <a class="reference internal" href="#re.finditer" title="re.finditer">finditer()</a> is useful as it provides <a class="reference internal" href="#match-objects">match objects</a> instead of strings. Continuing with the previous example, if one was a writer who wanted to find all of the adverbs and their positions in some text, he or she would use <a class="reference internal" href="#re.finditer" title="re.finditer">finditer()</a> in the following manner:

<span class="gp">>>> </span><span class="n">text</span> <span class="o">=</span> <span class="s">"He was carefully disguised but captured quickly by police."</span>
<span class="gp">>>> </span><span class="k">for</span> <span class="n">m</span> <span class="ow">in</span> <span class="n">re</span><span class="o">.</span><span class="n">finditer</span><span class="p">(</span><span class="s">r"\w+ly"</span><span class="p">,</span> <span class="n">text</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="s">'%02d-%02d: %s'</span> <span class="o">%</span> <span class="p">(</span><span class="n">m</span><span class="o">.</span><span class="n">start</span><span class="p">(),</span> <span class="n">m</span><span class="o">.</span><span class="n">end</span><span class="p">(),</span> <span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">0</span><span class="p">)))</span>
<span class="go">07-16: carefully</span>
<span class="go">40-47: quickly</span>

6.2.5.8. Raw String Notation<a class="headerlink" href="#raw-string-notation" title="Permalink to this headline">¶</a>

Raw string notation (r"text") keeps regular expressions sane. Without it, every backslash ('\') in a regular expression would have to be prefixed with another one to escape it. For example, the two following lines of code are functionally identical:

<span class="gp">>>> </span><span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">r"\W(.)\1\W"</span><span class="p">,</span> <span class="s">" ff "</span><span class="p">)</span>
<span class="go"><_sre.SRE_Match object; span=(0, 4), match=' ff '></span>
<span class="gp">>>> </span><span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">"</span><span class="se">\\</span><span class="s">W(.)</span><span class="se">\\</span><span class="s">1</span><span class="se">\\</span><span class="s">W"</span><span class="p">,</span> <span class="s">" ff "</span><span class="p">)</span>
<span class="go"><_sre.SRE_Match object; span=(0, 4), match=' ff '></span>

When one wants to match a literal backslash, it must be escaped in the regular expression. With raw string notation, this means r"\\". Without raw string notation, one must use "\\\\", making the following lines of code functionally identical:

<span class="gp">>>> </span><span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">r"</span><span class="se">\\</span><span class="s">"</span><span class="p">,</span> <span class="s">r"</span><span class="se">\\</span><span class="s">"</span><span class="p">)</span>
<span class="go"><_sre.SRE_Match object; span=(0, 1), match='\\'></span>
<span class="gp">>>> </span><span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">"</span><span class="se">\\\\</span><span class="s">"</span><span class="p">,</span> <span class="s">r"</span><span class="se">\\</span><span class="s">"</span><span class="p">)</span>
<span class="go"><_sre.SRE_Match object; span=(0, 1), match='\\'></span>

6.2.5.9. Writing a Tokenizer<a class="headerlink" href="#writing-a-tokenizer" title="Permalink to this headline">¶</a>

A <a class="reference external" href="http://en.wikipedia.org/wiki/Lexical_analysis">tokenizer or scanner</a> analyzes a string to categorize groups of characters. This is a useful first step in writing a compiler or interpreter.

The text categories are specified with regular expressions. The technique is to combine those into a single master regular expression and to loop over successive matches:

<span class="kn">import</span> <span class="nn">collections</span>
<span class="kn">import</span> <span class="nn">re</span>

<span class="n">Token</span> <span class="o">=</span> <span class="n">collections</span><span class="o">.</span><span class="n">namedtuple</span><span class="p">(</span><span class="s">'Token'</span><span class="p">,</span> <span class="p">[</span><span class="s">'typ'</span><span class="p">,</span> <span class="s">'value'</span><span class="p">,</span> <span class="s">'line'</span><span class="p">,</span> <span class="s">'column'</span><span class="p">])</span>

<span class="k">def</span> <span class="nf">tokenize</span><span class="p">(</span><span class="n">code</span><span class="p">):</span>
    <span class="n">keywords</span> <span class="o">=</span> <span class="p">{</span><span class="s">'IF'</span><span class="p">,</span> <span class="s">'THEN'</span><span class="p">,</span> <span class="s">'ENDIF'</span><span class="p">,</span> <span class="s">'FOR'</span><span class="p">,</span> <span class="s">'NEXT'</span><span class="p">,</span> <span class="s">'GOSUB'</span><span class="p">,</span> <span class="s">'RETURN'</span><span class="p">}</span>
    <span class="n">token_specification</span> <span class="o">=</span> <span class="p">[</span>
        <span class="p">(</span><span class="s">'NUMBER'</span><span class="p">,</span>  <span class="s">r'\d+(\.\d*)?'</span><span class="p">),</span> <span class="c"># Integer or decimal number</span>
        <span class="p">(</span><span class="s">'ASSIGN'</span><span class="p">,</span>  <span class="s">r':='</span><span class="p">),</span>          <span class="c"># Assignment operator</span>
        <span class="p">(</span><span class="s">'END'</span><span class="p">,</span>     <span class="s">r';'</span><span class="p">),</span>           <span class="c"># Statement terminator</span>
        <span class="p">(</span><span class="s">'ID'</span><span class="p">,</span>      <span class="s">r'[A-Za-z]+'</span><span class="p">),</span>   <span class="c"># Identifiers</span>
        <span class="p">(</span><span class="s">'OP'</span><span class="p">,</span>      <span class="s">r'[+\-*/]'</span><span class="p">),</span>     <span class="c"># Arithmetic operators</span>
        <span class="p">(</span><span class="s">'NEWLINE'</span><span class="p">,</span> <span class="s">r'\n'</span><span class="p">),</span>          <span class="c"># Line endings</span>
        <span class="p">(</span><span class="s">'SKIP'</span><span class="p">,</span>    <span class="s">r'[ \t]+'</span><span class="p">),</span>      <span class="c"># Skip over spaces and tabs</span>
        <span class="p">(</span><span class="s">'MISMATCH'</span><span class="p">,</span><span class="s">r'.'</span><span class="p">),</span>           <span class="c"># Any other character</span>
    <span class="p">]</span>
    <span class="n">tok_regex</span> <span class="o">=</span> <span class="s">'|'</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="s">'(?P<%s>%s)'</span> <span class="o">%</span> <span class="n">pair</span> <span class="k">for</span> <span class="n">pair</span> <span class="ow">in</span> <span class="n">token_specification</span><span class="p">)</span>
    <span class="n">line_num</span> <span class="o">=</span> <span class="mi">1</span>
    <span class="n">line_start</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="k">for</span> <span class="n">mo</span> <span class="ow">in</span> <span class="n">re</span><span class="o">.</span><span class="n">finditer</span><span class="p">(</span><span class="n">tok_regex</span><span class="p">,</span> <span class="n">code</span><span class="p">):</span>
        <span class="n">kind</span> <span class="o">=</span> <span class="n">mo</span><span class="o">.</span><span class="n">lastgroup</span>
        <span class="n">value</span> <span class="o">=</span> <span class="n">mo</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="n">kind</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">kind</span> <span class="o">==</span> <span class="s">'NEWLINE'</span><span class="p">:</span>
            <span class="n">line_start</span> <span class="o">=</span> <span class="n">mo</span><span class="o">.</span><span class="n">end</span><span class="p">()</span>
            <span class="n">line_num</span> <span class="o">+=</span> <span class="mi">1</span>
        <span class="k">elif</span> <span class="n">kind</span> <span class="o">==</span> <span class="s">'SKIP'</span><span class="p">:</span>
            <span class="k">pass</span>
        <span class="k">elif</span> <span class="n">kind</span> <span class="o">==</span> <span class="s">'MISMATCH'</span><span class="p">:</span>
            <span class="k">raise</span> <span class="ne">RuntimeError</span><span class="p">(</span><span class="s">'%r unexpected on line %d'</span> <span class="o">%</span> <span class="p">(</span><span class="n">value</span><span class="p">,</span> <span class="n">line_num</span><span class="p">))</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">if</span> <span class="n">kind</span> <span class="o">==</span> <span class="s">'ID'</span> <span class="ow">and</span> <span class="n">value</span> <span class="ow">in</span> <span class="n">keywords</span><span class="p">:</span>
                <span class="n">kind</span> <span class="o">=</span> <span class="n">value</span>
            <span class="n">column</span> <span class="o">=</span> <span class="n">mo</span><span class="o">.</span><span class="n">start</span><span class="p">()</span> <span class="o">-</span> <span class="n">line_start</span>
            <span class="k">yield</span> <span class="n">Token</span><span class="p">(</span><span class="n">kind</span><span class="p">,</span> <span class="n">value</span><span class="p">,</span> <span class="n">line_num</span><span class="p">,</span> <span class="n">column</span><span class="p">)</span>

<span class="n">statements</span> <span class="o">=</span> <span class="s">'''</span>
<span class="s">    IF quantity THEN</span>
<span class="s">        total := total + price * quantity;</span>
<span class="s">        tax := price * 0.05;</span>
<span class="s">    ENDIF;</span>
<span class="s">'''</span>

<span class="k">for</span> <span class="n">token</span> <span class="ow">in</span> <span class="n">tokenize</span><span class="p">(</span><span class="n">statements</span><span class="p">):</span>
    <span class="nb">print</span><span class="p">(</span><span class="n">token</span><span class="p">)</span>

The tokenizer produces the following output:

<span class="n">Token</span><span class="p">(</span><span class="n">typ</span><span class="o">=</span><span class="s">'IF'</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="s">'IF'</span><span class="p">,</span> <span class="n">line</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">column</span><span class="o">=</span><span class="mi">4</span><span class="p">)</span>
<span class="n">Token</span><span class="p">(</span><span class="n">typ</span><span class="o">=</span><span class="s">'ID'</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="s">'quantity'</span><span class="p">,</span> <span class="n">line</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">column</span><span class="o">=</span><span class="mi">7</span><span class="p">)</span>
<span class="n">Token</span><span class="p">(</span><span class="n">typ</span><span class="o">=</span><span class="s">'THEN'</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="s">'THEN'</span><span class="p">,</span> <span class="n">line</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">column</span><span class="o">=</span><span class="mi">16</span><span class="p">)</span>
<span class="n">Token</span><span class="p">(</span><span class="n">typ</span><span class="o">=</span><span class="s">'ID'</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="s">'total'</span><span class="p">,</span> <span class="n">line</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">column</span><span class="o">=</span><span class="mi">8</span><span class="p">)</span>
<span class="n">Token</span><span class="p">(</span><span class="n">typ</span><span class="o">=</span><span class="s">'ASSIGN'</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="s">':='</span><span class="p">,</span> <span class="n">line</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">column</span><span class="o">=</span><span class="mi">14</span><span class="p">)</span>
<span class="n">Token</span><span class="p">(</span><span class="n">typ</span><span class="o">=</span><span class="s">'ID'</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="s">'total'</span><span class="p">,</span> <span class="n">line</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">column</span><span class="o">=</span><span class="mi">17</span><span class="p">)</span>
<span class="n">Token</span><span class="p">(</span><span class="n">typ</span><span class="o">=</span><span class="s">'OP'</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="s">'+'</span><span class="p">,</span> <span class="n">line</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">column</span><span class="o">=</span><span class="mi">23</span><span class="p">)</span>
<span class="n">Token</span><span class="p">(</span><span class="n">typ</span><span class="o">=</span><span class="s">'ID'</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="s">'price'</span><span class="p">,</span> <span class="n">line</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">column</span><span class="o">=</span><span class="mi">25</span><span class="p">)</span>
<span class="n">Token</span><span class="p">(</span><span class="n">typ</span><span class="o">=</span><span class="s">'OP'</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="s">'*'</span><span class="p">,</span> <span class="n">line</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">column</span><span class="o">=</span><span class="mi">31</span><span class="p">)</span>
<span class="n">Token</span><span class="p">(</span><span class="n">typ</span><span class="o">=</span><span class="s">'ID'</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="s">'quantity'</span><span class="p">,</span> <span class="n">line</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">column</span><span class="o">=</span><span class="mi">33</span><span class="p">)</span>
<span class="n">Token</span><span class="p">(</span><span class="n">typ</span><span class="o">=</span><span class="s">'END'</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="s">';'</span><span class="p">,</span> <span class="n">line</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">column</span><span class="o">=</span><span class="mi">41</span><span class="p">)</span>
<span class="n">Token</span><span class="p">(</span><span class="n">typ</span><span class="o">=</span><span class="s">'ID'</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="s">'tax'</span><span class="p">,</span> <span class="n">line</span><span class="o">=</span><span class="mi">4</span><span class="p">,</span> <span class="n">column</span><span class="o">=</span><span class="mi">8</span><span class="p">)</span>
<span class="n">Token</span><span class="p">(</span><span class="n">typ</span><span class="o">=</span><span class="s">'ASSIGN'</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="s">':='</span><span class="p">,</span> <span class="n">line</span><span class="o">=</span><span class="mi">4</span><span class="p">,</span> <span class="n">column</span><span class="o">=</span><span class="mi">12</span><span class="p">)</span>
<span class="n">Token</span><span class="p">(</span><span class="n">typ</span><span class="o">=</span><span class="s">'ID'</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="s">'price'</span><span class="p">,</span> <span class="n">line</span><span class="o">=</span><span class="mi">4</span><span class="p">,</span> <span class="n">column</span><span class="o">=</span><span class="mi">15</span><span class="p">)</span>
<span class="n">Token</span><span class="p">(</span><span class="n">typ</span><span class="o">=</span><span class="s">'OP'</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="s">'*'</span><span class="p">,</span> <span class="n">line</span><span class="o">=</span><span class="mi">4</span><span class="p">,</span> <span class="n">column</span><span class="o">=</span><span class="mi">21</span><span class="p">)</span>
<span class="n">Token</span><span class="p">(</span><span class="n">typ</span><span class="o">=</span><span class="s">'NUMBER'</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="s">'0.05'</span><span class="p">,</span> <span class="n">line</span><span class="o">=</span><span class="mi">4</span><span class="p">,</span> <span class="n">column</span><span class="o">=</span><span class="mi">23</span><span class="p">)</span>
<span class="n">Token</span><span class="p">(</span><span class="n">typ</span><span class="o">=</span><span class="s">'END'</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="s">';'</span><span class="p">,</span> <span class="n">line</span><span class="o">=</span><span class="mi">4</span><span class="p">,</span> <span class="n">column</span><span class="o">=</span><span class="mi">27</span><span class="p">)</span>
<span class="n">Token</span><span class="p">(</span><span class="n">typ</span><span class="o">=</span><span class="s">'ENDIF'</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="s">'ENDIF'</span><span class="p">,</span> <span class="n">line</span><span class="o">=</span><span class="mi">5</span><span class="p">,</span> <span class="n">column</span><span class="o">=</span><span class="mi">4</span><span class="p">)</span>
<span class="n">Token</span><span class="p">(</span><span class="n">typ</span><span class="o">=</span><span class="s">'END'</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="s">';'</span><span class="p">,</span> <span class="n">line</span><span class="o">=</span><span class="mi">5</span><span class="p">,</span> <span class="n">column</span><span class="o">=</span><span class="mi">9</span><span class="p">)</span>