GIF89a; Mini Shell

Mini Shell

Direktori : /usr/share/doc/python-docs-2.7.5/html/howto/
Upload File :
Current File : //usr/share/doc/python-docs-2.7.5/html/howto/regex.html


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Regular Expression HOWTO &mdash; Python 2.7.5 documentation</title>
    
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '2.7.5',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.5 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="Python 2.7.5 documentation" href="../index.html" />
    <link rel="up" title="Python HOWTOs" href="index.html" />
    <link rel="next" title="Socket Programming HOWTO" href="sockets.html" />
    <link rel="prev" title="Logging Cookbook" href="logging-cookbook.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 

  </head>
  <body>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="sockets.html" title="Socket Programming HOWTO"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="logging-cookbook.html" title="Logging Cookbook"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="http://www.python.org/">Python</a> &raquo;</li>
        <li>
          <a href="../index.html">Python 2.7.5 documentation</a> &raquo;
        </li>

          <li><a href="index.html" accesskey="U">Python HOWTOs</a> &raquo;</li> 
      </ul>
    </div>  

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="regular-expression-howto">
<span id="regex-howto"></span><h1>Regular Expression HOWTO<a class="headerlink" href="#regular-expression-howto" title="Permalink to this headline">¶</a></h1>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Author:</th><td class="field-body">A.M. Kuchling &lt;<a class="reference external" href="mailto:amk&#37;&#52;&#48;amk&#46;ca">amk<span>&#64;</span>amk<span>&#46;</span>ca</a>&gt;</td>
</tr>
</tbody>
</table>
<div class="topic">
<p class="topic-title first">Abstract</p>
<p>This document is an introductory tutorial to using regular expressions in Python
with the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><tt class="xref py py-mod docutils literal"><span class="pre">re</span></tt></a> module.  It provides a gentler introduction than the
corresponding section in the Library Reference.</p>
</div>
<div class="section" id="introduction">
<h2>Introduction<a class="headerlink" href="#introduction" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><tt class="xref py py-mod docutils literal"><span class="pre">re</span></tt></a> module was added in Python 1.5, and provides Perl-style regular
expression patterns.  Earlier versions of Python came with the <tt class="xref py py-mod docutils literal"><span class="pre">regex</span></tt>
module, which provided Emacs-style patterns.  The <tt class="xref py py-mod docutils literal"><span class="pre">regex</span></tt> module was
removed completely in Python 2.5.</p>
<p>Regular expressions (called REs, or regexes, or regex patterns) are essentially
a tiny, highly specialized programming language embedded inside Python and made
available through the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><tt class="xref py py-mod docutils literal"><span class="pre">re</span></tt></a> module. Using this little language, you specify
the rules for the set of possible strings that you want to match; this set might
contain English sentences, or e-mail addresses, or TeX commands, or anything you
like.  You can then ask questions such as &#8220;Does this string match the pattern?&#8221;,
or &#8220;Is there a match for the pattern anywhere in this string?&#8221;.  You can also
use REs to modify a string or to split it apart in various ways.</p>
<p>Regular expression patterns are compiled into a series of bytecodes which are
then executed by a matching engine written in C.  For advanced use, it may be
necessary to pay careful attention to how the engine will execute a given RE,
and write the RE in a certain way in order to produce bytecode that runs faster.
Optimization isn&#8217;t covered in this document, because it requires that you have a
good understanding of the matching engine&#8217;s internals.</p>
<p>The regular expression language is relatively small and restricted, so not all
possible string processing tasks can be done using regular expressions.  There
are also tasks that <em>can</em> be done with regular expressions, but the expressions
turn out to be very complicated.  In these cases, you may be better off writing
Python code to do the processing; while Python code will be slower than an
elaborate regular expression, it will also probably be more understandable.</p>
</div>
<div class="section" id="simple-patterns">
<h2>Simple Patterns<a class="headerlink" href="#simple-patterns" title="Permalink to this headline">¶</a></h2>
<p>We&#8217;ll start by learning about the simplest possible regular expressions.  Since
regular expressions are used to operate on strings, we&#8217;ll begin with the most
common task: matching characters.</p>
<p>For a detailed explanation of the computer science underlying regular
expressions (deterministic and non-deterministic finite automata), you can refer
to almost any textbook on writing compilers.</p>
<div class="section" id="matching-characters">
<h3>Matching Characters<a class="headerlink" href="#matching-characters" title="Permalink to this headline">¶</a></h3>
<p>Most letters and characters will simply match themselves.  For example, the
regular expression <tt class="docutils literal"><span class="pre">test</span></tt> will match the string <tt class="docutils literal"><span class="pre">test</span></tt> exactly.  (You can
enable a case-insensitive mode that would let this RE match <tt class="docutils literal"><span class="pre">Test</span></tt> or <tt class="docutils literal"><span class="pre">TEST</span></tt>
as well; more about this later.)</p>
<p>There are exceptions to this rule; some characters are special
<em class="dfn">metacharacters</em>, and don&#8217;t match themselves.  Instead, they signal that
some out-of-the-ordinary thing should be matched, or they affect other portions
of the RE by repeating them or changing their meaning.  Much of this document is
devoted to discussing various metacharacters and what they do.</p>
<p>Here&#8217;s a complete list of the metacharacters; their meanings will be discussed
in the rest of this HOWTO.</p>
<div class="highlight-python"><pre>. ^ $ * + ? { } [ ] \ | ( )</pre>
</div>
<p>The first metacharacters we&#8217;ll look at are <tt class="docutils literal"><span class="pre">[</span></tt> and <tt class="docutils literal"><span class="pre">]</span></tt>. They&#8217;re used for
specifying a character class, which is a set of characters that you wish to
match.  Characters can be listed individually, or a range of characters can be
indicated by giving two characters and separating them by a <tt class="docutils literal"><span class="pre">'-'</span></tt>.  For
example, <tt class="docutils literal"><span class="pre">[abc]</span></tt> will match any of the characters <tt class="docutils literal"><span class="pre">a</span></tt>, <tt class="docutils literal"><span class="pre">b</span></tt>, or <tt class="docutils literal"><span class="pre">c</span></tt>; this
is the same as <tt class="docutils literal"><span class="pre">[a-c]</span></tt>, which uses a range to express the same set of
characters.  If you wanted to match only lowercase letters, your RE would be
<tt class="docutils literal"><span class="pre">[a-z]</span></tt>.</p>
<p>Metacharacters are not active inside classes.  For example, <tt class="docutils literal"><span class="pre">[akm$]</span></tt> will
match any of the characters <tt class="docutils literal"><span class="pre">'a'</span></tt>, <tt class="docutils literal"><span class="pre">'k'</span></tt>, <tt class="docutils literal"><span class="pre">'m'</span></tt>, or <tt class="docutils literal"><span class="pre">'$'</span></tt>; <tt class="docutils literal"><span class="pre">'$'</span></tt> is
usually a metacharacter, but inside a character class it&#8217;s stripped of its
special nature.</p>
<p>You can match the characters not listed within the class by <em class="dfn">complementing</em>
the set.  This is indicated by including a <tt class="docutils literal"><span class="pre">'^'</span></tt> as the first character of the
class; <tt class="docutils literal"><span class="pre">'^'</span></tt> outside a character class will simply match the <tt class="docutils literal"><span class="pre">'^'</span></tt>
character.  For example, <tt class="docutils literal"><span class="pre">[^5]</span></tt> will match any character except <tt class="docutils literal"><span class="pre">'5'</span></tt>.</p>
<p>Perhaps the most important metacharacter is the backslash, <tt class="docutils literal"><span class="pre">\</span></tt>.   As in Python
string literals, the backslash can be followed by various characters to signal
various special sequences.  It&#8217;s also used to escape all the metacharacters so
you can still match them in patterns; for example, if you need to match a <tt class="docutils literal"><span class="pre">[</span></tt>
or  <tt class="docutils literal"><span class="pre">\</span></tt>, you can precede them with a backslash to remove their special
meaning: <tt class="docutils literal"><span class="pre">\[</span></tt> or <tt class="docutils literal"><span class="pre">\\</span></tt>.</p>
<p>Some of the special sequences beginning with <tt class="docutils literal"><span class="pre">'\'</span></tt> represent predefined sets
of characters that are often useful, such as the set of digits, the set of
letters, or the set of anything that isn&#8217;t whitespace.  The following predefined
special sequences are a subset of those available. The equivalent classes are
for byte string patterns. For a complete list of sequences and expanded class
definitions for Unicode string patterns, see the last part of
<a class="reference internal" href="../library/re.html#re-syntax"><em>Regular Expression Syntax</em></a>.</p>
<dl class="docutils">
<dt><tt class="docutils literal"><span class="pre">\d</span></tt></dt>
<dd>Matches any decimal digit; this is equivalent to the class <tt class="docutils literal"><span class="pre">[0-9]</span></tt>.</dd>
<dt><tt class="docutils literal"><span class="pre">\D</span></tt></dt>
<dd>Matches any non-digit character; this is equivalent to the class <tt class="docutils literal"><span class="pre">[^0-9]</span></tt>.</dd>
<dt><tt class="docutils literal"><span class="pre">\s</span></tt></dt>
<dd>Matches any whitespace character; this is equivalent to the class <tt class="docutils literal"><span class="pre">[</span>
<span class="pre">\t\n\r\f\v]</span></tt>.</dd>
<dt><tt class="docutils literal"><span class="pre">\S</span></tt></dt>
<dd>Matches any non-whitespace character; this is equivalent to the class <tt class="docutils literal"><span class="pre">[^</span>
<span class="pre">\t\n\r\f\v]</span></tt>.</dd>
<dt><tt class="docutils literal"><span class="pre">\w</span></tt></dt>
<dd>Matches any alphanumeric character; this is equivalent to the class
<tt class="docutils literal"><span class="pre">[a-zA-Z0-9_]</span></tt>.</dd>
<dt><tt class="docutils literal"><span class="pre">\W</span></tt></dt>
<dd>Matches any non-alphanumeric character; this is equivalent to the class
<tt class="docutils literal"><span class="pre">[^a-zA-Z0-9_]</span></tt>.</dd>
</dl>
<p>These sequences can be included inside a character class.  For example,
<tt class="docutils literal"><span class="pre">[\s,.]</span></tt> is a character class that will match any whitespace character, or
<tt class="docutils literal"><span class="pre">','</span></tt> or <tt class="docutils literal"><span class="pre">'.'</span></tt>.</p>
<p>The final metacharacter in this section is <tt class="docutils literal"><span class="pre">.</span></tt>.  It matches anything except a
newline character, and there&#8217;s an alternate mode (<tt class="docutils literal"><span class="pre">re.DOTALL</span></tt>) where it will
match even a newline.  <tt class="docutils literal"><span class="pre">'.'</span></tt> is often used where you want to match &#8220;any
character&#8221;.</p>
</div>
<div class="section" id="repeating-things">
<h3>Repeating Things<a class="headerlink" href="#repeating-things" title="Permalink to this headline">¶</a></h3>
<p>Being able to match varying sets of characters is the first thing regular
expressions can do that isn&#8217;t already possible with the methods available on
strings.  However, if that was the only additional capability of regexes, they
wouldn&#8217;t be much of an advance. Another capability is that you can specify that
portions of the RE must be repeated a certain number of times.</p>
<p>The first metacharacter for repeating things that we&#8217;ll look at is <tt class="docutils literal"><span class="pre">*</span></tt>.  <tt class="docutils literal"><span class="pre">*</span></tt>
doesn&#8217;t match the literal character <tt class="docutils literal"><span class="pre">*</span></tt>; instead, it specifies that the
previous character can be matched zero or more times, instead of exactly once.</p>
<p>For example, <tt class="docutils literal"><span class="pre">ca*t</span></tt> will match <tt class="docutils literal"><span class="pre">ct</span></tt> (0 <tt class="docutils literal"><span class="pre">a</span></tt> characters), <tt class="docutils literal"><span class="pre">cat</span></tt> (1 <tt class="docutils literal"><span class="pre">a</span></tt>),
<tt class="docutils literal"><span class="pre">caaat</span></tt> (3 <tt class="docutils literal"><span class="pre">a</span></tt> characters), and so forth.  The RE engine has various
internal limitations stemming from the size of C&#8217;s <tt class="docutils literal"><span class="pre">int</span></tt> type that will
prevent it from matching over 2 billion <tt class="docutils literal"><span class="pre">a</span></tt> characters; you probably don&#8217;t
have enough memory to construct a string that large, so you shouldn&#8217;t run into
that limit.</p>
<p>Repetitions such as <tt class="docutils literal"><span class="pre">*</span></tt> are <em class="dfn">greedy</em>; when repeating a RE, the matching
engine will try to repeat it as many times as possible. If later portions of the
pattern don&#8217;t match, the matching engine will then back up and try again with
few repetitions.</p>
<p>A step-by-step example will make this more obvious.  Let&#8217;s consider the
expression <tt class="docutils literal"><span class="pre">a[bcd]*b</span></tt>.  This matches the letter <tt class="docutils literal"><span class="pre">'a'</span></tt>, zero or more letters
from the class <tt class="docutils literal"><span class="pre">[bcd]</span></tt>, and finally ends with a <tt class="docutils literal"><span class="pre">'b'</span></tt>.  Now imagine matching
this RE against the string <tt class="docutils literal"><span class="pre">abcbd</span></tt>.</p>
<table border="1" class="docutils">
<colgroup>
<col width="12%" />
<col width="22%" />
<col width="66%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Step</th>
<th class="head">Matched</th>
<th class="head">Explanation</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>1</td>
<td><tt class="docutils literal"><span class="pre">a</span></tt></td>
<td>The <tt class="docutils literal"><span class="pre">a</span></tt> in the RE matches.</td>
</tr>
<tr class="row-odd"><td>2</td>
<td><tt class="docutils literal"><span class="pre">abcbd</span></tt></td>
<td>The engine matches <tt class="docutils literal"><span class="pre">[bcd]*</span></tt>,
going as far as it can, which
is to the end of the string.</td>
</tr>
<tr class="row-even"><td>3</td>
<td><em>Failure</em></td>
<td>The engine tries to match
<tt class="docutils literal"><span class="pre">b</span></tt>, but the current position
is at the end of the string, so
it fails.</td>
</tr>
<tr class="row-odd"><td>4</td>
<td><tt class="docutils literal"><span class="pre">abcb</span></tt></td>
<td>Back up, so that  <tt class="docutils literal"><span class="pre">[bcd]*</span></tt>
matches one less character.</td>
</tr>
<tr class="row-even"><td>5</td>
<td><em>Failure</em></td>
<td>Try <tt class="docutils literal"><span class="pre">b</span></tt> again, but the
current position is at the last
character, which is a <tt class="docutils literal"><span class="pre">'d'</span></tt>.</td>
</tr>
<tr class="row-odd"><td>6</td>
<td><tt class="docutils literal"><span class="pre">abc</span></tt></td>
<td>Back up again, so that
<tt class="docutils literal"><span class="pre">[bcd]*</span></tt> is only matching
<tt class="docutils literal"><span class="pre">bc</span></tt>.</td>
</tr>
<tr class="row-even"><td>6</td>
<td><tt class="docutils literal"><span class="pre">abcb</span></tt></td>
<td>Try <tt class="docutils literal"><span class="pre">b</span></tt> again.  This time
the character at the
current position is <tt class="docutils literal"><span class="pre">'b'</span></tt>, so
it succeeds.</td>
</tr>
</tbody>
</table>
<p>The end of the RE has now been reached, and it has matched <tt class="docutils literal"><span class="pre">abcb</span></tt>.  This
demonstrates how the matching engine goes as far as it can at first, and if no
match is found it will then progressively back up and retry the rest of the RE
again and again.  It will back up until it has tried zero matches for
<tt class="docutils literal"><span class="pre">[bcd]*</span></tt>, and if that subsequently fails, the engine will conclude that the
string doesn&#8217;t match the RE at all.</p>
<p>Another repeating metacharacter is <tt class="docutils literal"><span class="pre">+</span></tt>, which matches one or more times.  Pay
careful attention to the difference between <tt class="docutils literal"><span class="pre">*</span></tt> and <tt class="docutils literal"><span class="pre">+</span></tt>; <tt class="docutils literal"><span class="pre">*</span></tt> matches
<em>zero</em> or more times, so whatever&#8217;s being repeated may not be present at all,
while <tt class="docutils literal"><span class="pre">+</span></tt> requires at least <em>one</em> occurrence.  To use a similar example,
<tt class="docutils literal"><span class="pre">ca+t</span></tt> will match <tt class="docutils literal"><span class="pre">cat</span></tt> (1 <tt class="docutils literal"><span class="pre">a</span></tt>), <tt class="docutils literal"><span class="pre">caaat</span></tt> (3 <tt class="docutils literal"><span class="pre">a</span></tt>&#8216;s), but won&#8217;t match
<tt class="docutils literal"><span class="pre">ct</span></tt>.</p>
<p>There are two more repeating qualifiers.  The question mark character, <tt class="docutils literal"><span class="pre">?</span></tt>,
matches either once or zero times; you can think of it as marking something as
being optional.  For example, <tt class="docutils literal"><span class="pre">home-?brew</span></tt> matches either <tt class="docutils literal"><span class="pre">homebrew</span></tt> or
<tt class="docutils literal"><span class="pre">home-brew</span></tt>.</p>
<p>The most complicated repeated qualifier is <tt class="docutils literal"><span class="pre">{m,n}</span></tt>, where <em>m</em> and <em>n</em> are
decimal integers.  This qualifier means there must be at least <em>m</em> repetitions,
and at most <em>n</em>.  For example, <tt class="docutils literal"><span class="pre">a/{1,3}b</span></tt> will match <tt class="docutils literal"><span class="pre">a/b</span></tt>, <tt class="docutils literal"><span class="pre">a//b</span></tt>, and
<tt class="docutils literal"><span class="pre">a///b</span></tt>.  It won&#8217;t match <tt class="docutils literal"><span class="pre">ab</span></tt>, which has no slashes, or <tt class="docutils literal"><span class="pre">a////b</span></tt>, which
has four.</p>
<p>You can omit either <em>m</em> or <em>n</em>; in that case, a reasonable value is assumed for
the missing value.  Omitting <em>m</em> is interpreted as a lower limit of 0, while
omitting <em>n</em> results in an upper bound of infinity &#8212; actually, the upper bound
is the 2-billion limit mentioned earlier, but that might as well be infinity.</p>
<p>Readers of a reductionist bent may notice that the three other qualifiers can
all be expressed using this notation.  <tt class="docutils literal"><span class="pre">{0,}</span></tt> is the same as <tt class="docutils literal"><span class="pre">*</span></tt>, <tt class="docutils literal"><span class="pre">{1,}</span></tt>
is equivalent to <tt class="docutils literal"><span class="pre">+</span></tt>, and <tt class="docutils literal"><span class="pre">{0,1}</span></tt> is the same as <tt class="docutils literal"><span class="pre">?</span></tt>.  It&#8217;s better to use
<tt class="docutils literal"><span class="pre">*</span></tt>, <tt class="docutils literal"><span class="pre">+</span></tt>, or <tt class="docutils literal"><span class="pre">?</span></tt> when you can, simply because they&#8217;re shorter and easier
to read.</p>
</div>
</div>
<div class="section" id="using-regular-expressions">
<h2>Using Regular Expressions<a class="headerlink" href="#using-regular-expressions" title="Permalink to this headline">¶</a></h2>
<p>Now that we&#8217;ve looked at some simple regular expressions, how do we actually use
them in Python?  The <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><tt class="xref py py-mod docutils literal"><span class="pre">re</span></tt></a> module provides an interface to the regular
expression engine, allowing you to compile REs into objects and then perform
matches with them.</p>
<div class="section" id="compiling-regular-expressions">
<h3>Compiling Regular Expressions<a class="headerlink" href="#compiling-regular-expressions" title="Permalink to this headline">¶</a></h3>
<p>Regular expressions are compiled into pattern objects, which have
methods for various operations such as searching for pattern matches or
performing string substitutions.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">re</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</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">&#39;ab*&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span>  
<span class="go">&lt;_sre.SRE_Pattern object at 0x...&gt;</span>
</pre></div>
</div>
<p><a class="reference internal" href="../library/re.html#re.compile" title="re.compile"><tt class="xref py py-func docutils literal"><span class="pre">re.compile()</span></tt></a> also accepts an optional <em>flags</em> argument, used to enable
various special features and syntax variations.  We&#8217;ll go over the available
settings later, but for now a single example will do:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">p</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">&#39;ab*&#39;</span><span class="p">,</span> <span class="n">re</span><span class="o">.</span><span class="n">IGNORECASE</span><span class="p">)</span>
</pre></div>
</div>
<p>The RE is passed to <a class="reference internal" href="../library/re.html#re.compile" title="re.compile"><tt class="xref py py-func docutils literal"><span class="pre">re.compile()</span></tt></a> as a string.  REs are handled as strings
because regular expressions aren&#8217;t part of the core Python language, and no
special syntax was created for expressing them.  (There are applications that
don&#8217;t need REs at all, so there&#8217;s no need to bloat the language specification by
including them.) Instead, the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><tt class="xref py py-mod docutils literal"><span class="pre">re</span></tt></a> module is simply a C extension module
included with Python, just like the <a class="reference internal" href="../library/socket.html#module-socket" title="socket: Low-level networking interface."><tt class="xref py py-mod docutils literal"><span class="pre">socket</span></tt></a> or <a class="reference internal" href="../library/zlib.html#module-zlib" title="zlib: Low-level interface to compression and decompression routines compatible with gzip."><tt class="xref py py-mod docutils literal"><span class="pre">zlib</span></tt></a> modules.</p>
<p>Putting REs in strings keeps the Python language simpler, but has one
disadvantage which is the topic of the next section.</p>
</div>
<div class="section" id="the-backslash-plague">
<h3>The Backslash Plague<a class="headerlink" href="#the-backslash-plague" title="Permalink to this headline">¶</a></h3>
<p>As stated earlier, regular expressions use the backslash character (<tt class="docutils literal"><span class="pre">'\'</span></tt>) to
indicate special forms or to allow special characters to be used without
invoking their special meaning. This conflicts with Python&#8217;s usage of the same
character for the same purpose in string literals.</p>
<p>Let&#8217;s say you want to write a RE that matches the string <tt class="docutils literal"><span class="pre">\section</span></tt>, which
might be found in a LaTeX file.  To figure out what to write in the program
code, start with the desired string to be matched.  Next, you must escape any
backslashes and other metacharacters by preceding them with a backslash,
resulting in the string <tt class="docutils literal"><span class="pre">\\section</span></tt>.  The resulting string that must be passed
to <a class="reference internal" href="../library/re.html#re.compile" title="re.compile"><tt class="xref py py-func docutils literal"><span class="pre">re.compile()</span></tt></a> must be <tt class="docutils literal"><span class="pre">\\section</span></tt>.  However, to express this as a
Python string literal, both backslashes must be escaped <em>again</em>.</p>
<table border="1" class="docutils">
<colgroup>
<col width="31%" />
<col width="69%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Characters</th>
<th class="head">Stage</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><tt class="docutils literal"><span class="pre">\section</span></tt></td>
<td>Text string to be matched</td>
</tr>
<tr class="row-odd"><td><tt class="docutils literal"><span class="pre">\\section</span></tt></td>
<td>Escaped backslash for <a class="reference internal" href="../library/re.html#re.compile" title="re.compile"><tt class="xref py py-func docutils literal"><span class="pre">re.compile()</span></tt></a></td>
</tr>
<tr class="row-even"><td><tt class="docutils literal"><span class="pre">&quot;\\\\section&quot;</span></tt></td>
<td>Escaped backslashes for a string literal</td>
</tr>
</tbody>
</table>
<p>In short, to match a literal backslash, one has to write <tt class="docutils literal"><span class="pre">'\\\\'</span></tt> as the RE
string, because the regular expression must be <tt class="docutils literal"><span class="pre">\\</span></tt>, and each backslash must
be expressed as <tt class="docutils literal"><span class="pre">\\</span></tt> inside a regular Python string literal.  In REs that
feature backslashes repeatedly, this leads to lots of repeated backslashes and
makes the resulting strings difficult to understand.</p>
<p>The solution is to use Python&#8217;s raw string notation for regular expressions;
backslashes are not handled in any special way in a string literal prefixed with
<tt class="docutils literal"><span class="pre">'r'</span></tt>, so <tt class="docutils literal"><span class="pre">r&quot;\n&quot;</span></tt> is a two-character string containing <tt class="docutils literal"><span class="pre">'\'</span></tt> and <tt class="docutils literal"><span class="pre">'n'</span></tt>,
while <tt class="docutils literal"><span class="pre">&quot;\n&quot;</span></tt> is a one-character string containing a newline. Regular
expressions will often be written in Python code using this raw string notation.</p>
<table border="1" class="docutils">
<colgroup>
<col width="51%" />
<col width="49%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Regular String</th>
<th class="head">Raw string</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><tt class="docutils literal"><span class="pre">&quot;ab*&quot;</span></tt></td>
<td><tt class="docutils literal"><span class="pre">r&quot;ab*&quot;</span></tt></td>
</tr>
<tr class="row-odd"><td><tt class="docutils literal"><span class="pre">&quot;\\\\section&quot;</span></tt></td>
<td><tt class="docutils literal"><span class="pre">r&quot;\\section&quot;</span></tt></td>
</tr>
<tr class="row-even"><td><tt class="docutils literal"><span class="pre">&quot;\\w+\\s+\\1&quot;</span></tt></td>
<td><tt class="docutils literal"><span class="pre">r&quot;\w+\s+\1&quot;</span></tt></td>
</tr>
</tbody>
</table>
</div>
<div class="section" id="performing-matches">
<h3>Performing Matches<a class="headerlink" href="#performing-matches" title="Permalink to this headline">¶</a></h3>
<p>Once you have an object representing a compiled regular expression, what do you
do with it?  Pattern objects have several methods and attributes.
Only the most significant ones will be covered here; consult the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><tt class="xref py py-mod docutils literal"><span class="pre">re</span></tt></a> docs
for a complete listing.</p>
<table border="1" class="docutils">
<colgroup>
<col width="28%" />
<col width="72%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Method/Attribute</th>
<th class="head">Purpose</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><tt class="docutils literal"><span class="pre">match()</span></tt></td>
<td>Determine if the RE matches at the beginning
of the string.</td>
</tr>
<tr class="row-odd"><td><tt class="docutils literal"><span class="pre">search()</span></tt></td>
<td>Scan through a string, looking for any
location where this RE matches.</td>
</tr>
<tr class="row-even"><td><tt class="docutils literal"><span class="pre">findall()</span></tt></td>
<td>Find all substrings where the RE matches, and
returns them as a list.</td>
</tr>
<tr class="row-odd"><td><tt class="docutils literal"><span class="pre">finditer()</span></tt></td>
<td>Find all substrings where the RE matches, and
returns them as an <a class="reference internal" href="../glossary.html#term-iterator"><em class="xref std std-term">iterator</em></a>.</td>
</tr>
</tbody>
</table>
<p><tt class="xref py py-meth docutils literal"><span class="pre">match()</span></tt> and <tt class="xref py py-meth docutils literal"><span class="pre">search()</span></tt> return <tt class="docutils literal"><span class="pre">None</span></tt> if no match can be found.  If
they&#8217;re successful, a <a class="reference internal" href="../library/re.html#match-objects"><em>match object</em></a> instance is returned,
containing information about the match: where it starts and ends, the substring
it matched, and more.</p>
<p>You can learn about this by interactively experimenting with the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><tt class="xref py py-mod docutils literal"><span class="pre">re</span></tt></a>
module.  If you have Tkinter available, you may also want to look at
<a class="reference external" href="http://hg.python.org/cpython/file/2.7/Tools/scripts/redemo.py">Tools/scripts/redemo.py</a>, a demonstration program included with the
Python distribution.  It allows you to enter REs and strings, and displays
whether the RE matches or fails. <tt class="file docutils literal"><span class="pre">redemo.py</span></tt> can be quite useful when
trying to debug a complicated RE.  Phil Schwartz&#8217;s <a class="reference external" href="http://kodos.sourceforge.net/">Kodos</a> is also an interactive tool for developing and
testing RE patterns.</p>
<p>This HOWTO uses the standard Python interpreter for its examples. First, run the
Python interpreter, import the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><tt class="xref py py-mod docutils literal"><span class="pre">re</span></tt></a> module, and compile a RE:</p>
<div class="highlight-python"><pre>Python 2.2.2 (#1, Feb 10 2003, 12:57:01)
&gt;&gt;&gt; import re
&gt;&gt;&gt; p = re.compile('[a-z]+')
&gt;&gt;&gt; p  #doctest: +ELLIPSIS
&lt;_sre.SRE_Pattern object at 0x...&gt;</pre>
</div>
<p>Now, you can try matching various strings against the RE <tt class="docutils literal"><span class="pre">[a-z]+</span></tt>.  An empty
string shouldn&#8217;t match at all, since <tt class="docutils literal"><span class="pre">+</span></tt> means &#8216;one or more repetitions&#8217;.
<tt class="xref py py-meth docutils literal"><span class="pre">match()</span></tt> should return <tt class="docutils literal"><span class="pre">None</span></tt> in this case, which will cause the
interpreter to print no output.  You can explicitly print the result of
<tt class="xref py py-meth docutils literal"><span class="pre">match()</span></tt> to make this clear.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">&quot;&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">p</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">&quot;&quot;</span><span class="p">)</span>
<span class="go">None</span>
</pre></div>
</div>
<p>Now, let&#8217;s try it on a string that it should match, such as <tt class="docutils literal"><span class="pre">tempo</span></tt>.  In this
case, <tt class="xref py py-meth docutils literal"><span class="pre">match()</span></tt> will return a <a class="reference internal" href="../library/re.html#match-objects"><em>match object</em></a>, so you
should store the result in a variable for later use.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">&#39;tempo&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span>  
<span class="go">&lt;_sre.SRE_Match object at 0x...&gt;</span>
</pre></div>
</div>
<p>Now you can query the <a class="reference internal" href="../library/re.html#match-objects"><em>match object</em></a> for information
about the matching string.  <a class="reference internal" href="../library/re.html#match-objects"><em>match object</em></a> instances
also have several methods and attributes; the most important ones are:</p>
<table border="1" class="docutils">
<colgroup>
<col width="29%" />
<col width="71%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Method/Attribute</th>
<th class="head">Purpose</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><tt class="docutils literal"><span class="pre">group()</span></tt></td>
<td>Return the string matched by the RE</td>
</tr>
<tr class="row-odd"><td><tt class="docutils literal"><span class="pre">start()</span></tt></td>
<td>Return the starting position of the match</td>
</tr>
<tr class="row-even"><td><tt class="docutils literal"><span class="pre">end()</span></tt></td>
<td>Return the ending position of the match</td>
</tr>
<tr class="row-odd"><td><tt class="docutils literal"><span class="pre">span()</span></tt></td>
<td>Return a tuple containing the (start, end)
positions  of the match</td>
</tr>
</tbody>
</table>
<p>Trying these methods will soon clarify their meaning:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">()</span>
<span class="go">&#39;tempo&#39;</span>
<span class="gp">&gt;&gt;&gt; </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="go">(0, 5)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">span</span><span class="p">()</span>
<span class="go">(0, 5)</span>
</pre></div>
</div>
<p><tt class="xref py py-meth docutils literal"><span class="pre">group()</span></tt> returns the substring that was matched by the RE.  <tt class="xref py py-meth docutils literal"><span class="pre">start()</span></tt>
and <tt class="xref py py-meth docutils literal"><span class="pre">end()</span></tt> return the starting and ending index of the match. <tt class="xref py py-meth docutils literal"><span class="pre">span()</span></tt>
returns both start and end indexes in a single tuple.  Since the <tt class="xref py py-meth docutils literal"><span class="pre">match()</span></tt>
method only checks if the RE matches at the start of a string, <tt class="xref py py-meth docutils literal"><span class="pre">start()</span></tt>
will always be zero.  However, the <tt class="xref py py-meth docutils literal"><span class="pre">search()</span></tt> method of patterns
scans through the string, so  the match may not start at zero in that
case.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">p</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">&#39;::: message&#39;</span><span class="p">)</span>
<span class="go">None</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s">&#39;::: message&#39;</span><span class="p">);</span> <span class="k">print</span> <span class="n">m</span>  
<span class="go">&lt;_sre.SRE_Match object at 0x...&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">()</span>
<span class="go">&#39;message&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">span</span><span class="p">()</span>
<span class="go">(4, 11)</span>
</pre></div>
</div>
<p>In actual programs, the most common style is to store the
<a class="reference internal" href="../library/re.html#match-objects"><em>match object</em></a> in a variable, and then check if it was
<tt class="docutils literal"><span class="pre">None</span></tt>.  This usually looks like:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">p</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="o">...</span> <span class="p">)</span>
<span class="n">m</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">match</span><span class="p">(</span> <span class="s">&#39;string goes here&#39;</span> <span class="p">)</span>
<span class="k">if</span> <span class="n">m</span><span class="p">:</span>
    <span class="k">print</span> <span class="s">&#39;Match found: &#39;</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="k">else</span><span class="p">:</span>
    <span class="k">print</span> <span class="s">&#39;No match&#39;</span>
</pre></div>
</div>
<p>Two pattern methods return all of the matches for a pattern.
<tt class="xref py py-meth docutils literal"><span class="pre">findall()</span></tt> returns a list of matching strings:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">p</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">&#39;\d+&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="s">&#39;12 drummers drumming, 11 pipers piping, 10 lords a-leaping&#39;</span><span class="p">)</span>
<span class="go">[&#39;12&#39;, &#39;11&#39;, &#39;10&#39;]</span>
</pre></div>
</div>
<p><tt class="xref py py-meth docutils literal"><span class="pre">findall()</span></tt> has to create the entire list before it can be returned as the
result.  The <tt class="xref py py-meth docutils literal"><span class="pre">finditer()</span></tt> method returns a sequence of
<a class="reference internal" href="../library/re.html#match-objects"><em>match object</em></a> instances as an <a class="reference internal" href="../glossary.html#term-iterator"><em class="xref std std-term">iterator</em></a>. <a class="footnote-reference" href="#id3" id="id1">[1]</a></p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">iterator</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">finditer</span><span class="p">(</span><span class="s">&#39;12 drummers drumming, 11 ... 10 ...&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">iterator</span>  
<span class="go">&lt;callable-iterator object at 0x...&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">match</span> <span class="ow">in</span> <span class="n">iterator</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">print</span> <span class="n">match</span><span class="o">.</span><span class="n">span</span><span class="p">()</span>
<span class="gp">...</span>
<span class="go">(0, 2)</span>
<span class="go">(22, 24)</span>
<span class="go">(29, 31)</span>
</pre></div>
</div>
</div>
<div class="section" id="module-level-functions">
<h3>Module-Level Functions<a class="headerlink" href="#module-level-functions" title="Permalink to this headline">¶</a></h3>
<p>You don&#8217;t have to create a pattern object and call its methods; the
<a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><tt class="xref py py-mod docutils literal"><span class="pre">re</span></tt></a> module also provides top-level functions called <tt class="xref py py-func docutils literal"><span class="pre">match()</span></tt>,
<tt class="xref py py-func docutils literal"><span class="pre">search()</span></tt>, <tt class="xref py py-func docutils literal"><span class="pre">findall()</span></tt>, <tt class="xref py py-func docutils literal"><span class="pre">sub()</span></tt>, and so forth.  These functions
take the same arguments as the corresponding pattern method, with
the RE string added as the first argument, and still return either <tt class="docutils literal"><span class="pre">None</span></tt> or a
<a class="reference internal" href="../library/re.html#match-objects"><em>match object</em></a> instance.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">r&#39;From\s+&#39;</span><span class="p">,</span> <span class="s">&#39;Fromage amk&#39;</span><span class="p">)</span>
<span class="go">None</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">r&#39;From\s+&#39;</span><span class="p">,</span> <span class="s">&#39;From amk Thu May 14 19:12:10 1998&#39;</span><span class="p">)</span>  
<span class="go">&lt;_sre.SRE_Match object at 0x...&gt;</span>
</pre></div>
</div>
<p>Under the hood, these functions simply create a pattern object for you
and call the appropriate method on it.  They also store the compiled object in a
cache, so future calls using the same RE are faster.</p>
<p>Should you use these module-level functions, or should you get the
pattern and call its methods yourself?  That choice depends on how
frequently the RE will be used, and on your personal coding style.  If the RE is
being used at only one point in the code, then the module functions are probably
more convenient.  If a program contains a lot of regular expressions, or re-uses
the same ones in several locations, then it might be worthwhile to collect all
the definitions in one place, in a section of code that compiles all the REs
ahead of time.  To take an example from the standard library, here&#8217;s an extract
from the deprecated <tt class="xref py py-mod docutils literal"><span class="pre">xmllib</span></tt> module:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">ref</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="o">...</span> <span class="p">)</span>
<span class="n">entityref</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="o">...</span> <span class="p">)</span>
<span class="n">charref</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="o">...</span> <span class="p">)</span>
<span class="n">starttagopen</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="o">...</span> <span class="p">)</span>
</pre></div>
</div>
<p>I generally prefer to work with the compiled object, even for one-time uses, but
few people will be as much of a purist about this as I am.</p>
</div>
<div class="section" id="compilation-flags">
<h3>Compilation Flags<a class="headerlink" href="#compilation-flags" title="Permalink to this headline">¶</a></h3>
<p>Compilation flags let you modify some aspects of how regular expressions work.
Flags are available in the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><tt class="xref py py-mod docutils literal"><span class="pre">re</span></tt></a> module under two names, a long name such as
<tt class="xref py py-const docutils literal"><span class="pre">IGNORECASE</span></tt> and a short, one-letter form such as <tt class="xref py py-const docutils literal"><span class="pre">I</span></tt>.  (If you&#8217;re
familiar with Perl&#8217;s pattern modifiers, the one-letter forms use the same
letters; the short form of <a class="reference internal" href="../library/re.html#re.VERBOSE" title="re.VERBOSE"><tt class="xref py py-const docutils literal"><span class="pre">re.VERBOSE</span></tt></a> is <a class="reference internal" href="../library/re.html#re.X" title="re.X"><tt class="xref py py-const docutils literal"><span class="pre">re.X</span></tt></a>, for example.)
Multiple flags can be specified by bitwise OR-ing them; <tt class="docutils literal"><span class="pre">re.I</span> <span class="pre">|</span> <span class="pre">re.M</span></tt> sets
both the <tt class="xref py py-const docutils literal"><span class="pre">I</span></tt> and <tt class="xref py py-const docutils literal"><span class="pre">M</span></tt> flags, for example.</p>
<p>Here&#8217;s a table of the available flags, followed by a more detailed explanation
of each one.</p>
<table border="1" class="docutils">
<colgroup>
<col width="43%" />
<col width="57%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Flag</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><tt class="xref py py-const docutils literal"><span class="pre">DOTALL</span></tt>, <tt class="xref py py-const docutils literal"><span class="pre">S</span></tt></td>
<td>Make <tt class="docutils literal"><span class="pre">.</span></tt> match any character, including
newlines</td>
</tr>
<tr class="row-odd"><td><tt class="xref py py-const docutils literal"><span class="pre">IGNORECASE</span></tt>, <tt class="xref py py-const docutils literal"><span class="pre">I</span></tt></td>
<td>Do case-insensitive matches</td>
</tr>
<tr class="row-even"><td><tt class="xref py py-const docutils literal"><span class="pre">LOCALE</span></tt>, <tt class="xref py py-const docutils literal"><span class="pre">L</span></tt></td>
<td>Do a locale-aware match</td>
</tr>
<tr class="row-odd"><td><tt class="xref py py-const docutils literal"><span class="pre">MULTILINE</span></tt>, <tt class="xref py py-const docutils literal"><span class="pre">M</span></tt></td>
<td>Multi-line matching, affecting <tt class="docutils literal"><span class="pre">^</span></tt> and
<tt class="docutils literal"><span class="pre">$</span></tt></td>
</tr>
<tr class="row-even"><td><tt class="xref py py-const docutils literal"><span class="pre">VERBOSE</span></tt>, <tt class="xref py py-const docutils literal"><span class="pre">X</span></tt></td>
<td>Enable verbose REs, which can be organized
more cleanly and understandably.</td>
</tr>
<tr class="row-odd"><td><tt class="xref py py-const docutils literal"><span class="pre">UNICODE</span></tt>, <tt class="xref py py-const docutils literal"><span class="pre">U</span></tt></td>
<td>Makes several escapes like <tt class="docutils literal"><span class="pre">\w</span></tt>, <tt class="docutils literal"><span class="pre">\b</span></tt>,
<tt class="docutils literal"><span class="pre">\s</span></tt> and <tt class="docutils literal"><span class="pre">\d</span></tt> dependent on the Unicode
character database.</td>
</tr>
</tbody>
</table>
<dl class="data">
<dt>
<tt class="descname">I</tt></dt>
<dt>
<tt class="descname">IGNORECASE</tt></dt>
<dd><p>Perform case-insensitive matching; character class and literal strings will
match letters by ignoring case.  For example, <tt class="docutils literal"><span class="pre">[A-Z]</span></tt> will match lowercase
letters, too, and <tt class="docutils literal"><span class="pre">Spam</span></tt> will match <tt class="docutils literal"><span class="pre">Spam</span></tt>, <tt class="docutils literal"><span class="pre">spam</span></tt>, or <tt class="docutils literal"><span class="pre">spAM</span></tt>. This
lowercasing doesn&#8217;t take the current locale into account; it will if you also
set the <tt class="xref py py-const docutils literal"><span class="pre">LOCALE</span></tt> flag.</p>
</dd></dl>

<dl class="data">
<dt>
<tt class="descname">L</tt></dt>
<dt>
<tt class="descname">LOCALE</tt></dt>
<dd><p>Make <tt class="docutils literal"><span class="pre">\w</span></tt>, <tt class="docutils literal"><span class="pre">\W</span></tt>, <tt class="docutils literal"><span class="pre">\b</span></tt>, and <tt class="docutils literal"><span class="pre">\B</span></tt>, dependent on the current locale.</p>
<p>Locales are a feature of the C library intended to help in writing programs that
take account of language differences.  For example, if you&#8217;re processing French
text, you&#8217;d want to be able to write <tt class="docutils literal"><span class="pre">\w+</span></tt> to match words, but <tt class="docutils literal"><span class="pre">\w</span></tt> only
matches the character class <tt class="docutils literal"><span class="pre">[A-Za-z]</span></tt>; it won&#8217;t match <tt class="docutils literal"><span class="pre">'é'</span></tt> or <tt class="docutils literal"><span class="pre">'ç'</span></tt>.  If
your system is configured properly and a French locale is selected, certain C
functions will tell the program that <tt class="docutils literal"><span class="pre">'é'</span></tt> should also be considered a letter.
Setting the <tt class="xref py py-const docutils literal"><span class="pre">LOCALE</span></tt> flag when compiling a regular expression will cause
the resulting compiled object to use these C functions for <tt class="docutils literal"><span class="pre">\w</span></tt>; this is
slower, but also enables <tt class="docutils literal"><span class="pre">\w+</span></tt> to match French words as you&#8217;d expect.</p>
</dd></dl>

<dl class="data">
<dt>
<tt class="descname">M</tt></dt>
<dt>
<tt class="descname">MULTILINE</tt></dt>
<dd><p>(<tt class="docutils literal"><span class="pre">^</span></tt> and <tt class="docutils literal"><span class="pre">$</span></tt> haven&#8217;t been explained yet;  they&#8217;ll be introduced in section
<a class="reference internal" href="#more-metacharacters"><em>More Metacharacters</em></a>.)</p>
<p>Usually <tt class="docutils literal"><span class="pre">^</span></tt> matches only at the beginning of the string, and <tt class="docutils literal"><span class="pre">$</span></tt> matches
only at the end of the string and immediately before the newline (if any) at the
end of the string. When this flag is specified, <tt class="docutils literal"><span class="pre">^</span></tt> matches at the beginning
of the string and at the beginning of each line within the string, immediately
following each newline.  Similarly, the <tt class="docutils literal"><span class="pre">$</span></tt> metacharacter matches either at
the end of the string and at the end of each line (immediately preceding each
newline).</p>
</dd></dl>

<dl class="data">
<dt>
<tt class="descname">S</tt></dt>
<dt>
<tt class="descname">DOTALL</tt></dt>
<dd><p>Makes the <tt class="docutils literal"><span class="pre">'.'</span></tt> special character match any character at all, including a
newline; without this flag, <tt class="docutils literal"><span class="pre">'.'</span></tt> will match anything <em>except</em> a newline.</p>
</dd></dl>

<dl class="data">
<dt>
<tt class="descname">U</tt></dt>
<dt>
<tt class="descname">UNICODE</tt></dt>
<dd><p>Make <tt class="docutils literal"><span class="pre">\w</span></tt>, <tt class="docutils literal"><span class="pre">\W</span></tt>, <tt class="docutils literal"><span class="pre">\b</span></tt>, <tt class="docutils literal"><span class="pre">\B</span></tt>, <tt class="docutils literal"><span class="pre">\d</span></tt>, <tt class="docutils literal"><span class="pre">\D</span></tt>, <tt class="docutils literal"><span class="pre">\s</span></tt> and <tt class="docutils literal"><span class="pre">\S</span></tt>
dependent on the Unicode character properties database.</p>
</dd></dl>

<dl class="data">
<dt>
<tt class="descname">X</tt></dt>
<dt>
<tt class="descname">VERBOSE</tt></dt>
<dd><p>This flag allows you to write regular expressions that are more readable by
granting you more flexibility in how you can format them.  When this flag has
been specified, whitespace within the RE string is ignored, except when the
whitespace is in a character class or preceded by an unescaped backslash; this
lets you organize and indent the RE more clearly.  This flag also lets you put
comments within a RE that will be ignored by the engine; comments are marked by
a <tt class="docutils literal"><span class="pre">'#'</span></tt> that&#8217;s neither in a character class or preceded by an unescaped
backslash.</p>
<p>For example, here&#8217;s a RE that uses <a class="reference internal" href="../library/re.html#re.VERBOSE" title="re.VERBOSE"><tt class="xref py py-const docutils literal"><span class="pre">re.VERBOSE</span></tt></a>; see how much easier it
is to read?</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">charref</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&quot;&quot;&quot;</span>
<span class="s"> &amp;[#]                # Start of a numeric entity reference</span>
<span class="s"> (</span>
<span class="s">     0[0-7]+         # Octal form</span>
<span class="s">   | [0-9]+          # Decimal form</span>
<span class="s">   | x[0-9a-fA-F]+   # Hexadecimal form</span>
<span class="s"> )</span>
<span class="s"> ;                   # Trailing semicolon</span>
<span class="s">&quot;&quot;&quot;</span><span class="p">,</span> <span class="n">re</span><span class="o">.</span><span class="n">VERBOSE</span><span class="p">)</span>
</pre></div>
</div>
<p>Without the verbose setting, the RE would look like this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">charref</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">&quot;&amp;#(0[0-7]+&quot;</span>
                     <span class="s">&quot;|[0-9]+&quot;</span>
                     <span class="s">&quot;|x[0-9a-fA-F]+);&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>In the above example, Python&#8217;s automatic concatenation of string literals has
been used to break up the RE into smaller pieces, but it&#8217;s still more difficult
to understand than the version using <a class="reference internal" href="../library/re.html#re.VERBOSE" title="re.VERBOSE"><tt class="xref py py-const docutils literal"><span class="pre">re.VERBOSE</span></tt></a>.</p>
</dd></dl>

</div>
</div>
<div class="section" id="more-pattern-power">
<h2>More Pattern Power<a class="headerlink" href="#more-pattern-power" title="Permalink to this headline">¶</a></h2>
<p>So far we&#8217;ve only covered a part of the features of regular expressions.  In
this section, we&#8217;ll cover some new metacharacters, and how to use groups to
retrieve portions of the text that was matched.</p>
<div class="section" id="more-metacharacters">
<span id="id2"></span><h3>More Metacharacters<a class="headerlink" href="#more-metacharacters" title="Permalink to this headline">¶</a></h3>
<p>There are some metacharacters that we haven&#8217;t covered yet.  Most of them will be
covered in this section.</p>
<p>Some of the remaining metacharacters to be discussed are <em class="dfn">zero-width
assertions</em>.  They don&#8217;t cause the engine to advance through the string;
instead, they consume no characters at all, and simply succeed or fail.  For
example, <tt class="docutils literal"><span class="pre">\b</span></tt> is an assertion that the current position is located at a word
boundary; the position isn&#8217;t changed by the <tt class="docutils literal"><span class="pre">\b</span></tt> at all.  This means that
zero-width assertions should never be repeated, because if they match once at a
given location, they can obviously be matched an infinite number of times.</p>
<dl class="docutils">
<dt><tt class="docutils literal"><span class="pre">|</span></tt></dt>
<dd><p class="first">Alternation, or the &#8220;or&#8221; operator.   If A and B are regular expressions,
<tt class="docutils literal"><span class="pre">A|B</span></tt> will match any string that matches either <tt class="docutils literal"><span class="pre">A</span></tt> or <tt class="docutils literal"><span class="pre">B</span></tt>. <tt class="docutils literal"><span class="pre">|</span></tt> has very
low precedence in order to make it work reasonably when you&#8217;re alternating
multi-character strings. <tt class="docutils literal"><span class="pre">Crow|Servo</span></tt> will match either <tt class="docutils literal"><span class="pre">Crow</span></tt> or <tt class="docutils literal"><span class="pre">Servo</span></tt>,
not <tt class="docutils literal"><span class="pre">Cro</span></tt>, a <tt class="docutils literal"><span class="pre">'w'</span></tt> or an <tt class="docutils literal"><span class="pre">'S'</span></tt>, and <tt class="docutils literal"><span class="pre">ervo</span></tt>.</p>
<p class="last">To match a literal <tt class="docutils literal"><span class="pre">'|'</span></tt>, use <tt class="docutils literal"><span class="pre">\|</span></tt>, or enclose it inside a character class,
as in <tt class="docutils literal"><span class="pre">[|]</span></tt>.</p>
</dd>
<dt><tt class="docutils literal"><span class="pre">^</span></tt></dt>
<dd><p class="first">Matches at the beginning of lines.  Unless the <tt class="xref py py-const docutils literal"><span class="pre">MULTILINE</span></tt> flag has been
set, this will only match at the beginning of the string.  In <tt class="xref py py-const docutils literal"><span class="pre">MULTILINE</span></tt>
mode, this also matches immediately after each newline within the string.</p>
<p>For example, if you wish to match the word <tt class="docutils literal"><span class="pre">From</span></tt> only at the beginning of a
line, the RE to use is <tt class="docutils literal"><span class="pre">^From</span></tt>.</p>
<div class="last highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s">&#39;^From&#39;</span><span class="p">,</span> <span class="s">&#39;From Here to Eternity&#39;</span><span class="p">)</span>  
<span class="go">&lt;_sre.SRE_Match object at 0x...&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s">&#39;^From&#39;</span><span class="p">,</span> <span class="s">&#39;Reciting From Memory&#39;</span><span class="p">)</span>
<span class="go">None</span>
</pre></div>
</div>
</dd>
<dt><tt class="docutils literal"><span class="pre">$</span></tt></dt>
<dd><p class="first">Matches at the end of a line, which is defined as either the end of the string,
or any location followed by a newline character.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s">&#39;}$&#39;</span><span class="p">,</span> <span class="s">&#39;{block}&#39;</span><span class="p">)</span>  
<span class="go">&lt;_sre.SRE_Match object at 0x...&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s">&#39;}$&#39;</span><span class="p">,</span> <span class="s">&#39;{block} &#39;</span><span class="p">)</span>
<span class="go">None</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s">&#39;}$&#39;</span><span class="p">,</span> <span class="s">&#39;{block}</span><span class="se">\n</span><span class="s">&#39;</span><span class="p">)</span>  
<span class="go">&lt;_sre.SRE_Match object at 0x...&gt;</span>
</pre></div>
</div>
<p class="last">To match a literal <tt class="docutils literal"><span class="pre">'$'</span></tt>, use <tt class="docutils literal"><span class="pre">\$</span></tt> or enclose it inside a character class,
as in  <tt class="docutils literal"><span class="pre">[$]</span></tt>.</p>
</dd>
<dt><tt class="docutils literal"><span class="pre">\A</span></tt></dt>
<dd>Matches only at the start of the string.  When not in <tt class="xref py py-const docutils literal"><span class="pre">MULTILINE</span></tt> mode,
<tt class="docutils literal"><span class="pre">\A</span></tt> and <tt class="docutils literal"><span class="pre">^</span></tt> are effectively the same.  In <tt class="xref py py-const docutils literal"><span class="pre">MULTILINE</span></tt> mode, they&#8217;re
different: <tt class="docutils literal"><span class="pre">\A</span></tt> still matches only at the beginning of the string, but <tt class="docutils literal"><span class="pre">^</span></tt>
may match at any location inside the string that follows a newline character.</dd>
<dt><tt class="docutils literal"><span class="pre">\Z</span></tt></dt>
<dd>Matches only at the end of the string.</dd>
<dt><tt class="docutils literal"><span class="pre">\b</span></tt></dt>
<dd><p class="first">Word boundary.  This is a zero-width assertion that matches only at the
beginning or end of a word.  A word is defined as a sequence of alphanumeric
characters, so the end of a word is indicated by whitespace or a
non-alphanumeric character.</p>
<p>The following example matches <tt class="docutils literal"><span class="pre">class</span></tt> only when it&#8217;s a complete word; it won&#8217;t
match when it&#8217;s contained inside another word.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">p</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&#39;\bclass\b&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">p</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s">&#39;no class at all&#39;</span><span class="p">)</span>  
<span class="go">&lt;_sre.SRE_Match object at 0x...&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">p</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s">&#39;the declassified algorithm&#39;</span><span class="p">)</span>
<span class="go">None</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">p</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s">&#39;one subclass is&#39;</span><span class="p">)</span>
<span class="go">None</span>
</pre></div>
</div>
<p>There are two subtleties you should remember when using this special sequence.
First, this is the worst collision between Python&#8217;s string literals and regular
expression sequences.  In Python&#8217;s string literals, <tt class="docutils literal"><span class="pre">\b</span></tt> is the backspace
character, ASCII value 8.  If you&#8217;re not using raw strings, then Python will
convert the <tt class="docutils literal"><span class="pre">\b</span></tt> to a backspace, and your RE won&#8217;t match as you expect it to.
The following example looks the same as our previous RE, but omits the <tt class="docutils literal"><span class="pre">'r'</span></tt>
in front of the RE string.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">p</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">&#39;</span><span class="se">\b</span><span class="s">class</span><span class="se">\b</span><span class="s">&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">p</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s">&#39;no class at all&#39;</span><span class="p">)</span>
<span class="go">None</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">p</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s">&#39;</span><span class="se">\b</span><span class="s">&#39;</span> <span class="o">+</span> <span class="s">&#39;class&#39;</span> <span class="o">+</span> <span class="s">&#39;</span><span class="se">\b</span><span class="s">&#39;</span><span class="p">)</span>  
<span class="go">&lt;_sre.SRE_Match object at 0x...&gt;</span>
</pre></div>
</div>
<p class="last">Second, inside a character class, where there&#8217;s no use for this assertion,
<tt class="docutils literal"><span class="pre">\b</span></tt> represents the backspace character, for compatibility with Python&#8217;s
string literals.</p>
</dd>
<dt><tt class="docutils literal"><span class="pre">\B</span></tt></dt>
<dd>Another zero-width assertion, this is the opposite of <tt class="docutils literal"><span class="pre">\b</span></tt>, only matching when
the current position is not at a word boundary.</dd>
</dl>
</div>
<div class="section" id="grouping">
<h3>Grouping<a class="headerlink" href="#grouping" title="Permalink to this headline">¶</a></h3>
<p>Frequently you need to obtain more information than just whether the RE matched
or not.  Regular expressions are often used to dissect strings by writing a RE
divided into several subgroups which match different components of interest.
For example, an RFC-822 header line is divided into a header name and a value,
separated by a <tt class="docutils literal"><span class="pre">':'</span></tt>, like this:</p>
<div class="highlight-python"><pre>From: author@example.com
User-Agent: Thunderbird 1.5.0.9 (X11/20061227)
MIME-Version: 1.0
To: editor@example.com</pre>
</div>
<p>This can be handled by writing a regular expression which matches an entire
header line, and has one group which matches the header name, and another group
which matches the header&#8217;s value.</p>
<p>Groups are marked by the <tt class="docutils literal"><span class="pre">'('</span></tt>, <tt class="docutils literal"><span class="pre">')'</span></tt> metacharacters. <tt class="docutils literal"><span class="pre">'('</span></tt> and <tt class="docutils literal"><span class="pre">')'</span></tt>
have much the same meaning as they do in mathematical expressions; they group
together the expressions contained inside them, and you can repeat the contents
of a group with a repeating qualifier, such as <tt class="docutils literal"><span class="pre">*</span></tt>, <tt class="docutils literal"><span class="pre">+</span></tt>, <tt class="docutils literal"><span class="pre">?</span></tt>, or
<tt class="docutils literal"><span class="pre">{m,n}</span></tt>.  For example, <tt class="docutils literal"><span class="pre">(ab)*</span></tt> will match zero or more repetitions of
<tt class="docutils literal"><span class="pre">ab</span></tt>.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">p</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">&#39;(ab)*&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">p</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">&#39;ababababab&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">span</span><span class="p">()</span>
<span class="go">(0, 10)</span>
</pre></div>
</div>
<p>Groups indicated with <tt class="docutils literal"><span class="pre">'('</span></tt>, <tt class="docutils literal"><span class="pre">')'</span></tt> also capture the starting and ending
index of the text that they match; this can be retrieved by passing an argument
to <tt class="xref py py-meth docutils literal"><span class="pre">group()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">start()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">end()</span></tt>, and <tt class="xref py py-meth docutils literal"><span class="pre">span()</span></tt>.  Groups are
numbered starting with 0.  Group 0 is always present; it&#8217;s the whole RE, so
<a class="reference internal" href="../library/re.html#match-objects"><em>match object</em></a> methods all have group 0 as their default
argument.  Later we&#8217;ll see how to express groups that don&#8217;t capture the span
of text that they match.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">p</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">&#39;(a)b&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">&#39;ab&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">()</span>
<span class="go">&#39;ab&#39;</span>
<span class="gp">&gt;&gt;&gt; </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">&#39;ab&#39;</span>
</pre></div>
</div>
<p>Subgroups are numbered from left to right, from 1 upward.  Groups can be nested;
to determine the number, just count the opening parenthesis characters, going
from left to right.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">p</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">&#39;(a(b)c)d&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">&#39;abcd&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </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">&#39;abcd&#39;</span>
<span class="gp">&gt;&gt;&gt; </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">&#39;abc&#39;</span>
<span class="gp">&gt;&gt;&gt; </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">&#39;b&#39;</span>
</pre></div>
</div>
<p><tt class="xref py py-meth docutils literal"><span class="pre">group()</span></tt> can be passed multiple group numbers at a time, in which case it
will return a tuple containing the corresponding values for those groups.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </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="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">)</span>
<span class="go">(&#39;b&#39;, &#39;abc&#39;, &#39;b&#39;)</span>
</pre></div>
</div>
<p>The <tt class="xref py py-meth docutils literal"><span class="pre">groups()</span></tt> method returns a tuple containing the strings for all the
subgroups, from 1 up to however many there are.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">groups</span><span class="p">()</span>
<span class="go">(&#39;abc&#39;, &#39;b&#39;)</span>
</pre></div>
</div>
<p>Backreferences in a pattern allow you to specify that the contents of an earlier
capturing group must also be found at the current location in the string.  For
example, <tt class="docutils literal"><span class="pre">\1</span></tt> will succeed if the exact contents of group 1 can be found at
the current position, and fails otherwise.  Remember that Python&#8217;s string
literals also use a backslash followed by numbers to allow including arbitrary
characters in a string, so be sure to use a raw string when incorporating
backreferences in a RE.</p>
<p>For example, the following RE detects doubled words in a string.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">p</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&#39;(\b\w+)\s+\1&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s">&#39;Paris in the the spring&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">group</span><span class="p">()</span>
<span class="go">&#39;the the&#39;</span>
</pre></div>
</div>
<p>Backreferences like this aren&#8217;t often useful for just searching through a string
&#8212; there are few text formats which repeat data in this way &#8212; but you&#8217;ll soon
find out that they&#8217;re <em>very</em> useful when performing string substitutions.</p>
</div>
<div class="section" id="non-capturing-and-named-groups">
<h3>Non-capturing and Named Groups<a class="headerlink" href="#non-capturing-and-named-groups" title="Permalink to this headline">¶</a></h3>
<p>Elaborate REs may use many groups, both to capture substrings of interest, and
to group and structure the RE itself.  In complex REs, it becomes difficult to
keep track of the group numbers.  There are two features which help with this
problem.  Both of them use a common syntax for regular expression extensions, so
we&#8217;ll look at that first.</p>
<p>Perl 5 added several additional features to standard regular expressions, and
the Python <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><tt class="xref py py-mod docutils literal"><span class="pre">re</span></tt></a> module supports most of them.   It would have been
difficult to choose new single-keystroke metacharacters or new special sequences
beginning with <tt class="docutils literal"><span class="pre">\</span></tt> to represent the new features without making Perl&#8217;s regular
expressions confusingly different from standard REs.  If you chose <tt class="docutils literal"><span class="pre">&amp;</span></tt> as a
new metacharacter, for example, old expressions would be assuming that <tt class="docutils literal"><span class="pre">&amp;</span></tt> was
a regular character and wouldn&#8217;t have escaped it by writing <tt class="docutils literal"><span class="pre">\&amp;</span></tt> or <tt class="docutils literal"><span class="pre">[&amp;]</span></tt>.</p>
<p>The solution chosen by the Perl developers was to use <tt class="docutils literal"><span class="pre">(?...)</span></tt> as the
extension syntax.  <tt class="docutils literal"><span class="pre">?</span></tt> immediately after a parenthesis was a syntax error
because the <tt class="docutils literal"><span class="pre">?</span></tt> would have nothing to repeat, so this didn&#8217;t introduce any
compatibility problems.  The characters immediately after the <tt class="docutils literal"><span class="pre">?</span></tt>  indicate
what extension is being used, so <tt class="docutils literal"><span class="pre">(?=foo)</span></tt> is one thing (a positive lookahead
assertion) and <tt class="docutils literal"><span class="pre">(?:foo)</span></tt> is something else (a non-capturing group containing
the subexpression <tt class="docutils literal"><span class="pre">foo</span></tt>).</p>
<p>Python adds an extension syntax to Perl&#8217;s extension syntax.  If the first
character after the question mark is a <tt class="docutils literal"><span class="pre">P</span></tt>, you know that it&#8217;s an extension
that&#8217;s specific to Python.  Currently there are two such extensions:
<tt class="docutils literal"><span class="pre">(?P&lt;name&gt;...)</span></tt> defines a named group, and <tt class="docutils literal"><span class="pre">(?P=name)</span></tt> is a backreference to
a named group.  If future versions of Perl 5 add similar features using a
different syntax, the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><tt class="xref py py-mod docutils literal"><span class="pre">re</span></tt></a> module will be changed to support the new
syntax, while preserving the Python-specific syntax for compatibility&#8217;s sake.</p>
<p>Now that we&#8217;ve looked at the general extension syntax, we can return to the
features that simplify working with groups in complex REs. Since groups are
numbered from left to right and a complex expression may use many groups, it can
become difficult to keep track of the correct numbering.  Modifying such a
complex RE is annoying, too: insert a new group near the beginning and you
change the numbers of everything that follows it.</p>
<p>Sometimes you&#8217;ll want to use a group to collect a part of a regular expression,
but aren&#8217;t interested in retrieving the group&#8217;s contents. You can make this fact
explicit by using a non-capturing group: <tt class="docutils literal"><span class="pre">(?:...)</span></tt>, where you can replace the
<tt class="docutils literal"><span class="pre">...</span></tt> with any other regular expression.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </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">&quot;([abc])+&quot;</span><span class="p">,</span> <span class="s">&quot;abc&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">groups</span><span class="p">()</span>
<span class="go">(&#39;c&#39;,)</span>
<span class="gp">&gt;&gt;&gt; </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">&quot;(?:[abc])+&quot;</span><span class="p">,</span> <span class="s">&quot;abc&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">groups</span><span class="p">()</span>
<span class="go">()</span>
</pre></div>
</div>
<p>Except for the fact that you can&#8217;t retrieve the contents of what the group
matched, a non-capturing group behaves exactly the same as a capturing group;
you can put anything inside it, repeat it with a repetition metacharacter such
as <tt class="docutils literal"><span class="pre">*</span></tt>, and nest it within other groups (capturing or non-capturing).
<tt class="docutils literal"><span class="pre">(?:...)</span></tt> is particularly useful when modifying an existing pattern, since you
can add new groups without changing how all the other groups are numbered.  It
should be mentioned that there&#8217;s no performance difference in searching between
capturing and non-capturing groups; neither form is any faster than the other.</p>
<p>A more significant feature is named groups: instead of referring to them by
numbers, groups can be referenced by a name.</p>
<p>The syntax for a named group is one of the Python-specific extensions:
<tt class="docutils literal"><span class="pre">(?P&lt;name&gt;...)</span></tt>.  <em>name</em> is, obviously, the name of the group.  Named groups
also behave exactly like capturing groups, and additionally associate a name
with a group.  The <a class="reference internal" href="../library/re.html#match-objects"><em>match object</em></a> methods that deal with
capturing groups all accept either integers that refer to the group by number
or strings that contain the desired group&#8217;s name.  Named groups are still
given numbers, so you can retrieve information about a group in two ways:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">p</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&#39;(?P&lt;word&gt;\b\w+\b)&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">search</span><span class="p">(</span> <span class="s">&#39;(((( Lots of punctuation )))&#39;</span> <span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="s">&#39;word&#39;</span><span class="p">)</span>
<span class="go">&#39;Lots&#39;</span>
<span class="gp">&gt;&gt;&gt; </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">&#39;Lots&#39;</span>
</pre></div>
</div>
<p>Named groups are handy because they let you use easily-remembered names, instead
of having to remember numbers.  Here&#8217;s an example RE from the <a class="reference internal" href="../library/imaplib.html#module-imaplib" title="imaplib: IMAP4 protocol client (requires sockets)."><tt class="xref py py-mod docutils literal"><span class="pre">imaplib</span></tt></a>
module:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">InternalDate</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&#39;INTERNALDATE &quot;&#39;</span>
        <span class="s">r&#39;(?P&lt;day&gt;[ 123][0-9])-(?P&lt;mon&gt;[A-Z][a-z][a-z])-&#39;</span>
        <span class="s">r&#39;(?P&lt;year&gt;[0-9][0-9][0-9][0-9])&#39;</span>
        <span class="s">r&#39; (?P&lt;hour&gt;[0-9][0-9]):(?P&lt;min&gt;[0-9][0-9]):(?P&lt;sec&gt;[0-9][0-9])&#39;</span>
        <span class="s">r&#39; (?P&lt;zonen&gt;[-+])(?P&lt;zoneh&gt;[0-9][0-9])(?P&lt;zonem&gt;[0-9][0-9])&#39;</span>
        <span class="s">r&#39;&quot;&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>It&#8217;s obviously much easier to retrieve <tt class="docutils literal"><span class="pre">m.group('zonem')</span></tt>, instead of having
to remember to retrieve group 9.</p>
<p>The syntax for backreferences in an expression such as <tt class="docutils literal"><span class="pre">(...)\1</span></tt> refers to the
number of the group.  There&#8217;s naturally a variant that uses the group name
instead of the number. This is another Python extension: <tt class="docutils literal"><span class="pre">(?P=name)</span></tt> indicates
that the contents of the group called <em>name</em> should again be matched at the
current point.  The regular expression for finding doubled words,
<tt class="docutils literal"><span class="pre">(\b\w+)\s+\1</span></tt> can also be written as <tt class="docutils literal"><span class="pre">(?P&lt;word&gt;\b\w+)\s+(?P=word)</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">p</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&#39;(?P&lt;word&gt;\b\w+)\s+(?P=word)&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s">&#39;Paris in the the spring&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">group</span><span class="p">()</span>
<span class="go">&#39;the the&#39;</span>
</pre></div>
</div>
</div>
<div class="section" id="lookahead-assertions">
<h3>Lookahead Assertions<a class="headerlink" href="#lookahead-assertions" title="Permalink to this headline">¶</a></h3>
<p>Another zero-width assertion is the lookahead assertion.  Lookahead assertions
are available in both positive and negative form, and  look like this:</p>
<dl class="docutils">
<dt><tt class="docutils literal"><span class="pre">(?=...)</span></tt></dt>
<dd>Positive lookahead assertion.  This succeeds if the contained regular
expression, represented here by <tt class="docutils literal"><span class="pre">...</span></tt>, successfully matches at the current
location, and fails otherwise. But, once the contained expression has been
tried, the matching engine doesn&#8217;t advance at all; the rest of the pattern is
tried right where the assertion started.</dd>
<dt><tt class="docutils literal"><span class="pre">(?!...)</span></tt></dt>
<dd>Negative lookahead assertion.  This is the opposite of the positive assertion;
it succeeds if the contained expression <em>doesn&#8217;t</em> match at the current position
in the string.</dd>
</dl>
<p>To make this concrete, let&#8217;s look at a case where a lookahead is useful.
Consider a simple pattern to match a filename and split it apart into a base
name and an extension, separated by a <tt class="docutils literal"><span class="pre">.</span></tt>.  For example, in <tt class="docutils literal"><span class="pre">news.rc</span></tt>,
<tt class="docutils literal"><span class="pre">news</span></tt> is the base name, and <tt class="docutils literal"><span class="pre">rc</span></tt> is the filename&#8217;s extension.</p>
<p>The pattern to match this is quite simple:</p>
<p><tt class="docutils literal"><span class="pre">.*[.].*$</span></tt></p>
<p>Notice that the <tt class="docutils literal"><span class="pre">.</span></tt> needs to be treated specially because it&#8217;s a
metacharacter; I&#8217;ve put it inside a character class.  Also notice the trailing
<tt class="docutils literal"><span class="pre">$</span></tt>; this is added to ensure that all the rest of the string must be included
in the extension.  This regular expression matches <tt class="docutils literal"><span class="pre">foo.bar</span></tt> and
<tt class="docutils literal"><span class="pre">autoexec.bat</span></tt> and <tt class="docutils literal"><span class="pre">sendmail.cf</span></tt> and <tt class="docutils literal"><span class="pre">printers.conf</span></tt>.</p>
<p>Now, consider complicating the problem a bit; what if you want to match
filenames where the extension is not <tt class="docutils literal"><span class="pre">bat</span></tt>? Some incorrect attempts:</p>
<p><tt class="docutils literal"><span class="pre">.*[.][^b].*$</span></tt>  The first attempt above tries to exclude <tt class="docutils literal"><span class="pre">bat</span></tt> by requiring
that the first character of the extension is not a <tt class="docutils literal"><span class="pre">b</span></tt>.  This is wrong,
because the pattern also doesn&#8217;t match <tt class="docutils literal"><span class="pre">foo.bar</span></tt>.</p>
<p><tt class="docutils literal"><span class="pre">.*[.]([^b]..|.[^a].|..[^t])$</span></tt></p>
<p>The expression gets messier when you try to patch up the first solution by
requiring one of the following cases to match: the first character of the
extension isn&#8217;t <tt class="docutils literal"><span class="pre">b</span></tt>; the second character isn&#8217;t <tt class="docutils literal"><span class="pre">a</span></tt>; or the third character
isn&#8217;t <tt class="docutils literal"><span class="pre">t</span></tt>.  This accepts <tt class="docutils literal"><span class="pre">foo.bar</span></tt> and rejects <tt class="docutils literal"><span class="pre">autoexec.bat</span></tt>, but it
requires a three-letter extension and won&#8217;t accept a filename with a two-letter
extension such as <tt class="docutils literal"><span class="pre">sendmail.cf</span></tt>.  We&#8217;ll complicate the pattern again in an
effort to fix it.</p>
<p><tt class="docutils literal"><span class="pre">.*[.]([^b].?.?|.[^a]?.?|..?[^t]?)$</span></tt></p>
<p>In the third attempt, the second and third letters are all made optional in
order to allow matching extensions shorter than three characters, such as
<tt class="docutils literal"><span class="pre">sendmail.cf</span></tt>.</p>
<p>The pattern&#8217;s getting really complicated now, which makes it hard to read and
understand.  Worse, if the problem changes and you want to exclude both <tt class="docutils literal"><span class="pre">bat</span></tt>
and <tt class="docutils literal"><span class="pre">exe</span></tt> as extensions, the pattern would get even more complicated and
confusing.</p>
<p>A negative lookahead cuts through all this confusion:</p>
<p><tt class="docutils literal"><span class="pre">.*[.](?!bat$).*$</span></tt>  The negative lookahead means: if the expression <tt class="docutils literal"><span class="pre">bat</span></tt>
doesn&#8217;t match at this point, try the rest of the pattern; if <tt class="docutils literal"><span class="pre">bat$</span></tt> does
match, the whole pattern will fail.  The trailing <tt class="docutils literal"><span class="pre">$</span></tt> is required to ensure
that something like <tt class="docutils literal"><span class="pre">sample.batch</span></tt>, where the extension only starts with
<tt class="docutils literal"><span class="pre">bat</span></tt>, will be allowed.</p>
<p>Excluding another filename extension is now easy; simply add it as an
alternative inside the assertion.  The following pattern excludes filenames that
end in either <tt class="docutils literal"><span class="pre">bat</span></tt> or <tt class="docutils literal"><span class="pre">exe</span></tt>:</p>
<p><tt class="docutils literal"><span class="pre">.*[.](?!bat$|exe$).*$</span></tt></p>
</div>
</div>
<div class="section" id="modifying-strings">
<h2>Modifying Strings<a class="headerlink" href="#modifying-strings" title="Permalink to this headline">¶</a></h2>
<p>Up to this point, we&#8217;ve simply performed searches against a static string.
Regular expressions are also commonly used to modify strings in various ways,
using the following pattern methods:</p>
<table border="1" class="docutils">
<colgroup>
<col width="28%" />
<col width="72%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Method/Attribute</th>
<th class="head">Purpose</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><tt class="docutils literal"><span class="pre">split()</span></tt></td>
<td>Split the string into a list, splitting it
wherever the RE matches</td>
</tr>
<tr class="row-odd"><td><tt class="docutils literal"><span class="pre">sub()</span></tt></td>
<td>Find all substrings where the RE matches, and
replace them with a different string</td>
</tr>
<tr class="row-even"><td><tt class="docutils literal"><span class="pre">subn()</span></tt></td>
<td>Does the same thing as <tt class="xref py py-meth docutils literal"><span class="pre">sub()</span></tt>,  but
returns the new string and the number of
replacements</td>
</tr>
</tbody>
</table>
<div class="section" id="splitting-strings">
<h3>Splitting Strings<a class="headerlink" href="#splitting-strings" title="Permalink to this headline">¶</a></h3>
<p>The <tt class="xref py py-meth docutils literal"><span class="pre">split()</span></tt> method of a pattern splits a string apart
wherever the RE matches, returning a list of the pieces. It&#8217;s similar to the
<tt class="xref py py-meth docutils literal"><span class="pre">split()</span></tt> method of strings but provides much more generality in the
delimiters that you can split by; <tt class="xref py py-meth docutils literal"><span class="pre">split()</span></tt> only supports splitting by
whitespace or by a fixed string.  As you&#8217;d expect, there&#8217;s a module-level
<a class="reference internal" href="../library/re.html#re.split" title="re.split"><tt class="xref py py-func docutils literal"><span class="pre">re.split()</span></tt></a> function, too.</p>
<dl class="method">
<dt>
<tt class="descclassname">.</tt><tt class="descname">split</tt><big>(</big><em>string</em><span class="optional">[</span>, <em>maxsplit=0</em><span class="optional">]</span><big>)</big></dt>
<dd><p>Split <em>string</em> by the matches of the regular expression.  If capturing
parentheses are used in the RE, then their contents will also be returned as
part of the resulting list.  If <em>maxsplit</em> is nonzero, at most <em>maxsplit</em> splits
are performed.</p>
</dd></dl>

<p>You can limit the number of splits made, by passing a value for <em>maxsplit</em>.
When <em>maxsplit</em> is nonzero, at most <em>maxsplit</em> splits will be made, and the
remainder of the string is returned as the final element of the list.  In the
following example, the delimiter is any sequence of non-alphanumeric characters.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">p</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&#39;\W+&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s">&#39;This is a test, short and sweet, of split().&#39;</span><span class="p">)</span>
<span class="go">[&#39;This&#39;, &#39;is&#39;, &#39;a&#39;, &#39;test&#39;, &#39;short&#39;, &#39;and&#39;, &#39;sweet&#39;, &#39;of&#39;, &#39;split&#39;, &#39;&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s">&#39;This is a test, short and sweet, of split().&#39;</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
<span class="go">[&#39;This&#39;, &#39;is&#39;, &#39;a&#39;, &#39;test, short and sweet, of split().&#39;]</span>
</pre></div>
</div>
<p>Sometimes you&#8217;re not only interested in what the text between delimiters is, but
also need to know what the delimiter was.  If capturing parentheses are used in
the RE, then their values are also returned as part of the list.  Compare the
following calls:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">p</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&#39;\W+&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p2</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&#39;(\W+)&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s">&#39;This... is a test.&#39;</span><span class="p">)</span>
<span class="go">[&#39;This&#39;, &#39;is&#39;, &#39;a&#39;, &#39;test&#39;, &#39;&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p2</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s">&#39;This... is a test.&#39;</span><span class="p">)</span>
<span class="go">[&#39;This&#39;, &#39;... &#39;, &#39;is&#39;, &#39; &#39;, &#39;a&#39;, &#39; &#39;, &#39;test&#39;, &#39;.&#39;, &#39;&#39;]</span>
</pre></div>
</div>
<p>The module-level function <a class="reference internal" href="../library/re.html#re.split" title="re.split"><tt class="xref py py-func docutils literal"><span class="pre">re.split()</span></tt></a> adds the RE to be used as the first
argument, but is otherwise the same.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s">&#39;[\W]+&#39;</span><span class="p">,</span> <span class="s">&#39;Words, words, words.&#39;</span><span class="p">)</span>
<span class="go">[&#39;Words&#39;, &#39;words&#39;, &#39;words&#39;, &#39;&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s">&#39;([\W]+)&#39;</span><span class="p">,</span> <span class="s">&#39;Words, words, words.&#39;</span><span class="p">)</span>
<span class="go">[&#39;Words&#39;, &#39;, &#39;, &#39;words&#39;, &#39;, &#39;, &#39;words&#39;, &#39;.&#39;, &#39;&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s">&#39;[\W]+&#39;</span><span class="p">,</span> <span class="s">&#39;Words, words, words.&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="go">[&#39;Words&#39;, &#39;words, words.&#39;]</span>
</pre></div>
</div>
</div>
<div class="section" id="search-and-replace">
<h3>Search and Replace<a class="headerlink" href="#search-and-replace" title="Permalink to this headline">¶</a></h3>
<p>Another common task is to find all the matches for a pattern, and replace them
with a different string.  The <tt class="xref py py-meth docutils literal"><span class="pre">sub()</span></tt> method takes a replacement value,
which can be either a string or a function, and the string to be processed.</p>
<dl class="method">
<dt>
<tt class="descclassname">.</tt><tt class="descname">sub</tt><big>(</big><em>replacement</em>, <em>string</em><span class="optional">[</span>, <em>count=0</em><span class="optional">]</span><big>)</big></dt>
<dd><p>Returns the string obtained by replacing the leftmost non-overlapping
occurrences of the RE in <em>string</em> by the replacement <em>replacement</em>.  If the
pattern isn&#8217;t found, <em>string</em> is returned unchanged.</p>
<p>The optional argument <em>count</em> is the maximum number of pattern occurrences to be
replaced; <em>count</em> must be a non-negative integer.  The default value of 0 means
to replace all occurrences.</p>
</dd></dl>

<p>Here&#8217;s a simple example of using the <tt class="xref py py-meth docutils literal"><span class="pre">sub()</span></tt> method.  It replaces colour
names with the word <tt class="docutils literal"><span class="pre">colour</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">p</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">&#39;(blue|white|red)&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span> <span class="s">&#39;colour&#39;</span><span class="p">,</span> <span class="s">&#39;blue socks and red shoes&#39;</span><span class="p">)</span>
<span class="go">&#39;colour socks and colour shoes&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span> <span class="s">&#39;colour&#39;</span><span class="p">,</span> <span class="s">&#39;blue socks and red shoes&#39;</span><span class="p">,</span> <span class="n">count</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="go">&#39;colour socks and red shoes&#39;</span>
</pre></div>
</div>
<p>The <tt class="xref py py-meth docutils literal"><span class="pre">subn()</span></tt> method does the same work, but returns a 2-tuple containing the
new string value and the number of replacements  that were performed:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">p</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">&#39;(blue|white|red)&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">subn</span><span class="p">(</span> <span class="s">&#39;colour&#39;</span><span class="p">,</span> <span class="s">&#39;blue socks and red shoes&#39;</span><span class="p">)</span>
<span class="go">(&#39;colour socks and colour shoes&#39;, 2)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">subn</span><span class="p">(</span> <span class="s">&#39;colour&#39;</span><span class="p">,</span> <span class="s">&#39;no colours at all&#39;</span><span class="p">)</span>
<span class="go">(&#39;no colours at all&#39;, 0)</span>
</pre></div>
</div>
<p>Empty matches are replaced only when they&#8217;re not adjacent to a previous match.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">p</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">&#39;x*&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="s">&#39;-&#39;</span><span class="p">,</span> <span class="s">&#39;abxd&#39;</span><span class="p">)</span>
<span class="go">&#39;-a-b-d-&#39;</span>
</pre></div>
</div>
<p>If <em>replacement</em> is a string, any backslash escapes in it are processed.  That
is, <tt class="docutils literal"><span class="pre">\n</span></tt> is converted to a single newline character, <tt class="docutils literal"><span class="pre">\r</span></tt> is converted to a
carriage return, and so forth. Unknown escapes such as <tt class="docutils literal"><span class="pre">\j</span></tt> are left alone.
Backreferences, such as <tt class="docutils literal"><span class="pre">\6</span></tt>, are replaced with the substring matched by the
corresponding group in the RE.  This lets you incorporate portions of the
original text in the resulting replacement string.</p>
<p>This example matches the word <tt class="docutils literal"><span class="pre">section</span></tt> followed by a string enclosed in
<tt class="docutils literal"><span class="pre">{</span></tt>, <tt class="docutils literal"><span class="pre">}</span></tt>, and changes <tt class="docutils literal"><span class="pre">section</span></tt> to <tt class="docutils literal"><span class="pre">subsection</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">p</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">&#39;section{ ( [^}]* ) }&#39;</span><span class="p">,</span> <span class="n">re</span><span class="o">.</span><span class="n">VERBOSE</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="s">r&#39;subsection{\1}&#39;</span><span class="p">,</span><span class="s">&#39;section{First} section{second}&#39;</span><span class="p">)</span>
<span class="go">&#39;subsection{First} subsection{second}&#39;</span>
</pre></div>
</div>
<p>There&#8217;s also a syntax for referring to named groups as defined by the
<tt class="docutils literal"><span class="pre">(?P&lt;name&gt;...)</span></tt> syntax.  <tt class="docutils literal"><span class="pre">\g&lt;name&gt;</span></tt> will use the substring matched by the
group named <tt class="docutils literal"><span class="pre">name</span></tt>, and  <tt class="docutils literal"><span class="pre">\g&lt;number&gt;</span></tt>  uses the corresponding group number.
<tt class="docutils literal"><span class="pre">\g&lt;2&gt;</span></tt> is therefore equivalent to <tt class="docutils literal"><span class="pre">\2</span></tt>,  but isn&#8217;t ambiguous in a
replacement string such as <tt class="docutils literal"><span class="pre">\g&lt;2&gt;0</span></tt>.  (<tt class="docutils literal"><span class="pre">\20</span></tt> would be interpreted as a
reference to group 20, not a reference to group 2 followed by the literal
character <tt class="docutils literal"><span class="pre">'0'</span></tt>.)  The following substitutions are all equivalent, but use all
three variations of the replacement string.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">p</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">&#39;section{ (?P&lt;name&gt; [^}]* ) }&#39;</span><span class="p">,</span> <span class="n">re</span><span class="o">.</span><span class="n">VERBOSE</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="s">r&#39;subsection{\1}&#39;</span><span class="p">,</span><span class="s">&#39;section{First}&#39;</span><span class="p">)</span>
<span class="go">&#39;subsection{First}&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="s">r&#39;subsection{\g&lt;1&gt;}&#39;</span><span class="p">,</span><span class="s">&#39;section{First}&#39;</span><span class="p">)</span>
<span class="go">&#39;subsection{First}&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="s">r&#39;subsection{\g&lt;name&gt;}&#39;</span><span class="p">,</span><span class="s">&#39;section{First}&#39;</span><span class="p">)</span>
<span class="go">&#39;subsection{First}&#39;</span>
</pre></div>
</div>
<p><em>replacement</em> can also be a function, which gives you even more control.  If
<em>replacement</em> is a function, the function is called for every non-overlapping
occurrence of <em>pattern</em>.  On each call, the function is passed a
<a class="reference internal" href="../library/re.html#match-objects"><em>match object</em></a> argument for the match and can use this
information to compute the desired replacement string and return it.</p>
<p>In the following example, the replacement function translates decimals into
hexadecimal:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">hexrepl</span><span class="p">(</span><span class="n">match</span><span class="p">):</span>
<span class="gp">... </span>    <span class="s">&quot;Return the hex string for a decimal number&quot;</span>
<span class="gp">... </span>    <span class="n">value</span> <span class="o">=</span> <span class="nb">int</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="gp">... </span>    <span class="k">return</span> <span class="nb">hex</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</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&#39;\d+&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="n">hexrepl</span><span class="p">,</span> <span class="s">&#39;Call 65490 for printing, 49152 for user code.&#39;</span><span class="p">)</span>
<span class="go">&#39;Call 0xffd2 for printing, 0xc000 for user code.&#39;</span>
</pre></div>
</div>
<p>When using the module-level <a class="reference internal" href="../library/re.html#re.sub" title="re.sub"><tt class="xref py py-func docutils literal"><span class="pre">re.sub()</span></tt></a> function, the pattern is passed as
the first argument.  The pattern may be provided as an object or as a string; if
you need to specify regular expression flags, you must either use a
pattern object as the first parameter, or use embedded modifiers in the
pattern string, e.g. <tt class="docutils literal"><span class="pre">sub(&quot;(?i)b+&quot;,</span> <span class="pre">&quot;x&quot;,</span> <span class="pre">&quot;bbbb</span> <span class="pre">BBBB&quot;)</span></tt> returns <tt class="docutils literal"><span class="pre">'x</span> <span class="pre">x'</span></tt>.</p>
</div>
</div>
<div class="section" id="common-problems">
<h2>Common Problems<a class="headerlink" href="#common-problems" title="Permalink to this headline">¶</a></h2>
<p>Regular expressions are a powerful tool for some applications, but in some ways
their behaviour isn&#8217;t intuitive and at times they don&#8217;t behave the way you may
expect them to.  This section will point out some of the most common pitfalls.</p>
<div class="section" id="use-string-methods">
<h3>Use String Methods<a class="headerlink" href="#use-string-methods" title="Permalink to this headline">¶</a></h3>
<p>Sometimes using the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><tt class="xref py py-mod docutils literal"><span class="pre">re</span></tt></a> module is a mistake.  If you&#8217;re matching a fixed
string, or a single character class, and you&#8217;re not using any <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><tt class="xref py py-mod docutils literal"><span class="pre">re</span></tt></a> features
such as the <tt class="xref py py-const docutils literal"><span class="pre">IGNORECASE</span></tt> flag, then the full power of regular expressions
may not be required. Strings have several methods for performing operations with
fixed strings and they&#8217;re usually much faster, because the implementation is a
single small C loop that&#8217;s been optimized for the purpose, instead of the large,
more generalized regular expression engine.</p>
<p>One example might be replacing a single fixed string with another one; for
example, you might replace <tt class="docutils literal"><span class="pre">word</span></tt> with <tt class="docutils literal"><span class="pre">deed</span></tt>.  <tt class="docutils literal"><span class="pre">re.sub()</span></tt> seems like the
function to use for this, but consider the <tt class="xref py py-meth docutils literal"><span class="pre">replace()</span></tt> method.  Note that
<tt class="xref py py-func docutils literal"><span class="pre">replace()</span></tt> will also replace <tt class="docutils literal"><span class="pre">word</span></tt> inside words, turning <tt class="docutils literal"><span class="pre">swordfish</span></tt>
into <tt class="docutils literal"><span class="pre">sdeedfish</span></tt>, but the  naive RE <tt class="docutils literal"><span class="pre">word</span></tt> would have done that, too.  (To
avoid performing the substitution on parts of words, the pattern would have to
be <tt class="docutils literal"><span class="pre">\bword\b</span></tt>, in order to require that <tt class="docutils literal"><span class="pre">word</span></tt> have a word boundary on
either side.  This takes the job beyond  <tt class="xref py py-meth docutils literal"><span class="pre">replace()</span></tt>&#8216;s abilities.)</p>
<p>Another common task is deleting every occurrence of a single character from a
string or replacing it with another single character.  You might do this with
something like <tt class="docutils literal"><span class="pre">re.sub('\n',</span> <span class="pre">'</span> <span class="pre">',</span> <span class="pre">S)</span></tt>, but <tt class="xref py py-meth docutils literal"><span class="pre">translate()</span></tt> is capable of
doing both tasks and will be faster than any regular expression operation can
be.</p>
<p>In short, before turning to the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><tt class="xref py py-mod docutils literal"><span class="pre">re</span></tt></a> module, consider whether your problem
can be solved with a faster and simpler string method.</p>
</div>
<div class="section" id="match-versus-search">
<h3>match() versus search()<a class="headerlink" href="#match-versus-search" title="Permalink to this headline">¶</a></h3>
<p>The <tt class="xref py py-func docutils literal"><span class="pre">match()</span></tt> function only checks if the RE matches at the beginning of the
string while <tt class="xref py py-func docutils literal"><span class="pre">search()</span></tt> will scan forward through the string for a match.
It&#8217;s important to keep this distinction in mind.  Remember,  <tt class="xref py py-func docutils literal"><span class="pre">match()</span></tt> will
only report a successful match which will start at 0; if the match wouldn&#8217;t
start at zero,  <tt class="xref py py-func docutils literal"><span class="pre">match()</span></tt> will <em>not</em> report it.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">&#39;super&#39;</span><span class="p">,</span> <span class="s">&#39;superstition&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">span</span><span class="p">()</span>
<span class="go">(0, 5)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">&#39;super&#39;</span><span class="p">,</span> <span class="s">&#39;insuperable&#39;</span><span class="p">)</span>
<span class="go">None</span>
</pre></div>
</div>
<p>On the other hand, <tt class="xref py py-func docutils literal"><span class="pre">search()</span></tt> will scan forward through the string,
reporting the first match it finds.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s">&#39;super&#39;</span><span class="p">,</span> <span class="s">&#39;superstition&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">span</span><span class="p">()</span>
<span class="go">(0, 5)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s">&#39;super&#39;</span><span class="p">,</span> <span class="s">&#39;insuperable&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">span</span><span class="p">()</span>
<span class="go">(2, 7)</span>
</pre></div>
</div>
<p>Sometimes you&#8217;ll be tempted to keep using <a class="reference internal" href="../library/re.html#re.match" title="re.match"><tt class="xref py py-func docutils literal"><span class="pre">re.match()</span></tt></a>, and just add <tt class="docutils literal"><span class="pre">.*</span></tt>
to the front of your RE.  Resist this temptation and use <a class="reference internal" href="../library/re.html#re.search" title="re.search"><tt class="xref py py-func docutils literal"><span class="pre">re.search()</span></tt></a>
instead.  The regular expression compiler does some analysis of REs in order to
speed up the process of looking for a match.  One such analysis figures out what
the first character of a match must be; for example, a pattern starting with
<tt class="docutils literal"><span class="pre">Crow</span></tt> must match starting with a <tt class="docutils literal"><span class="pre">'C'</span></tt>.  The analysis lets the engine
quickly scan through the string looking for the starting character, only trying
the full match if a <tt class="docutils literal"><span class="pre">'C'</span></tt> is found.</p>
<p>Adding <tt class="docutils literal"><span class="pre">.*</span></tt> defeats this optimization, requiring scanning to the end of the
string and then backtracking to find a match for the rest of the RE.  Use
<a class="reference internal" href="../library/re.html#re.search" title="re.search"><tt class="xref py py-func docutils literal"><span class="pre">re.search()</span></tt></a> instead.</p>
</div>
<div class="section" id="greedy-versus-non-greedy">
<h3>Greedy versus Non-Greedy<a class="headerlink" href="#greedy-versus-non-greedy" title="Permalink to this headline">¶</a></h3>
<p>When repeating a regular expression, as in <tt class="docutils literal"><span class="pre">a*</span></tt>, the resulting action is to
consume as much of the pattern as possible.  This fact often bites you when
you&#8217;re trying to match a pair of balanced delimiters, such as the angle brackets
surrounding an HTML tag.  The naive pattern for matching a single HTML tag
doesn&#8217;t work because of the greedy nature of <tt class="docutils literal"><span class="pre">.*</span></tt>.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s">&#39;&lt;html&gt;&lt;head&gt;&lt;title&gt;Title&lt;/title&gt;&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="go">32</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">&#39;&lt;.*&gt;&#39;</span><span class="p">,</span> <span class="n">s</span><span class="p">)</span><span class="o">.</span><span class="n">span</span><span class="p">()</span>
<span class="go">(0, 32)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">&#39;&lt;.*&gt;&#39;</span><span class="p">,</span> <span class="n">s</span><span class="p">)</span><span class="o">.</span><span class="n">group</span><span class="p">()</span>
<span class="go">&lt;html&gt;&lt;head&gt;&lt;title&gt;Title&lt;/title&gt;</span>
</pre></div>
</div>
<p>The RE matches the <tt class="docutils literal"><span class="pre">'&lt;'</span></tt> in <tt class="docutils literal"><span class="pre">&lt;html&gt;</span></tt>, and the <tt class="docutils literal"><span class="pre">.*</span></tt> consumes the rest of
the string.  There&#8217;s still more left in the RE, though, and the <tt class="docutils literal"><span class="pre">&gt;</span></tt> can&#8217;t
match at the end of the string, so the regular expression engine has to
backtrack character by character until it finds a match for the <tt class="docutils literal"><span class="pre">&gt;</span></tt>.   The
final match extends from the <tt class="docutils literal"><span class="pre">'&lt;'</span></tt> in <tt class="docutils literal"><span class="pre">&lt;html&gt;</span></tt> to the <tt class="docutils literal"><span class="pre">'&gt;'</span></tt> in
<tt class="docutils literal"><span class="pre">&lt;/title&gt;</span></tt>, which isn&#8217;t what you want.</p>
<p>In this case, the solution is to use the non-greedy qualifiers <tt class="docutils literal"><span class="pre">*?</span></tt>, <tt class="docutils literal"><span class="pre">+?</span></tt>,
<tt class="docutils literal"><span class="pre">??</span></tt>, or <tt class="docutils literal"><span class="pre">{m,n}?</span></tt>, which match as <em>little</em> text as possible.  In the above
example, the <tt class="docutils literal"><span class="pre">'&gt;'</span></tt> is tried immediately after the first <tt class="docutils literal"><span class="pre">'&lt;'</span></tt> matches, and
when it fails, the engine advances a character at a time, retrying the <tt class="docutils literal"><span class="pre">'&gt;'</span></tt>
at every step.  This produces just the right result:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">&#39;&lt;.*?&gt;&#39;</span><span class="p">,</span> <span class="n">s</span><span class="p">)</span><span class="o">.</span><span class="n">group</span><span class="p">()</span>
<span class="go">&lt;html&gt;</span>
</pre></div>
</div>
<p>(Note that parsing HTML or XML with regular expressions is painful.
Quick-and-dirty patterns will handle common cases, but HTML and XML have special
cases that will break the obvious regular expression; by the time you&#8217;ve written
a regular expression that handles all of the possible cases, the patterns will
be <em>very</em> complicated.  Use an HTML or XML parser module for such tasks.)</p>
</div>
<div class="section" id="using-re-verbose">
<h3>Using re.VERBOSE<a class="headerlink" href="#using-re-verbose" title="Permalink to this headline">¶</a></h3>
<p>By now you&#8217;ve probably noticed that regular expressions are a very compact
notation, but they&#8217;re not terribly readable.  REs of moderate complexity can
become lengthy collections of backslashes, parentheses, and metacharacters,
making them difficult to read and understand.</p>
<p>For such REs, specifying the <tt class="docutils literal"><span class="pre">re.VERBOSE</span></tt> flag when compiling the regular
expression can be helpful, because it allows you to format the regular
expression more clearly.</p>
<p>The <tt class="docutils literal"><span class="pre">re.VERBOSE</span></tt> flag has several effects.  Whitespace in the regular
expression that <em>isn&#8217;t</em> inside a character class is ignored.  This means that an
expression such as <tt class="docutils literal"><span class="pre">dog</span> <span class="pre">|</span> <span class="pre">cat</span></tt> is equivalent to the less readable <tt class="docutils literal"><span class="pre">dog|cat</span></tt>,
but <tt class="docutils literal"><span class="pre">[a</span> <span class="pre">b]</span></tt> will still match the characters <tt class="docutils literal"><span class="pre">'a'</span></tt>, <tt class="docutils literal"><span class="pre">'b'</span></tt>, or a space.  In
addition, you can also put comments inside a RE; comments extend from a <tt class="docutils literal"><span class="pre">#</span></tt>
character to the next newline.  When used with triple-quoted strings, this
enables REs to be formatted more neatly:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">pat</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&quot;&quot;&quot;</span>
<span class="s"> \s*                 # Skip leading whitespace</span>
<span class="s"> (?P&lt;header&gt;[^:]+)   # Header name</span>
<span class="s"> \s* :               # Whitespace, and a colon</span>
<span class="s"> (?P&lt;value&gt;.*?)      # The header&#39;s value -- *? used to</span>
<span class="s">                     # lose the following trailing whitespace</span>
<span class="s"> \s*$                # Trailing whitespace to end-of-line</span>
<span class="s">&quot;&quot;&quot;</span><span class="p">,</span> <span class="n">re</span><span class="o">.</span><span class="n">VERBOSE</span><span class="p">)</span>
</pre></div>
</div>
<p>This is far more readable than:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">pat</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&quot;\s*(?P&lt;header&gt;[^:]+)\s*:(?P&lt;value&gt;.*?)\s*$&quot;</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="feedback">
<h2>Feedback<a class="headerlink" href="#feedback" title="Permalink to this headline">¶</a></h2>
<p>Regular expressions are a complicated topic.  Did this document help you
understand them?  Were there parts that were unclear, or Problems you
encountered that weren&#8217;t covered here?  If so, please send suggestions for
improvements to the author.</p>
<p>The most complete book on regular expressions is almost certainly Jeffrey
Friedl&#8217;s Mastering Regular Expressions, published by O&#8217;Reilly.  Unfortunately,
it exclusively concentrates on Perl and Java&#8217;s flavours of regular expressions,
and doesn&#8217;t contain any Python material at all, so it won&#8217;t be useful as a
reference for programming in Python.  (The first edition covered Python&#8217;s
now-removed <tt class="xref py py-mod docutils literal"><span class="pre">regex</span></tt> module, which won&#8217;t help you much.)  Consider checking
it out from your library.</p>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id3" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>Introduced in Python 2.2.2.</td></tr>
</tbody>
</table>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Regular Expression HOWTO</a><ul>
<li><a class="reference internal" href="#introduction">Introduction</a></li>
<li><a class="reference internal" href="#simple-patterns">Simple Patterns</a><ul>
<li><a class="reference internal" href="#matching-characters">Matching Characters</a></li>
<li><a class="reference internal" href="#repeating-things">Repeating Things</a></li>
</ul>
</li>
<li><a class="reference internal" href="#using-regular-expressions">Using Regular Expressions</a><ul>
<li><a class="reference internal" href="#compiling-regular-expressions">Compiling Regular Expressions</a></li>
<li><a class="reference internal" href="#the-backslash-plague">The Backslash Plague</a></li>
<li><a class="reference internal" href="#performing-matches">Performing Matches</a></li>
<li><a class="reference internal" href="#module-level-functions">Module-Level Functions</a></li>
<li><a class="reference internal" href="#compilation-flags">Compilation Flags</a></li>
</ul>
</li>
<li><a class="reference internal" href="#more-pattern-power">More Pattern Power</a><ul>
<li><a class="reference internal" href="#more-metacharacters">More Metacharacters</a></li>
<li><a class="reference internal" href="#grouping">Grouping</a></li>
<li><a class="reference internal" href="#non-capturing-and-named-groups">Non-capturing and Named Groups</a></li>
<li><a class="reference internal" href="#lookahead-assertions">Lookahead Assertions</a></li>
</ul>
</li>
<li><a class="reference internal" href="#modifying-strings">Modifying Strings</a><ul>
<li><a class="reference internal" href="#splitting-strings">Splitting Strings</a></li>
<li><a class="reference internal" href="#search-and-replace">Search and Replace</a></li>
</ul>
</li>
<li><a class="reference internal" href="#common-problems">Common Problems</a><ul>
<li><a class="reference internal" href="#use-string-methods">Use String Methods</a></li>
<li><a class="reference internal" href="#match-versus-search">match() versus search()</a></li>
<li><a class="reference internal" href="#greedy-versus-non-greedy">Greedy versus Non-Greedy</a></li>
<li><a class="reference internal" href="#using-re-verbose">Using re.VERBOSE</a></li>
</ul>
</li>
<li><a class="reference internal" href="#feedback">Feedback</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="logging-cookbook.html"
                        title="previous chapter">Logging Cookbook</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="sockets.html"
                        title="next chapter">Socket Programming HOWTO</a></p>
<h3>This Page</h3>
<ul class="this-page-menu">
  <li><a href="../bugs.html">Report a Bug</a></li>
  <li><a href="../_sources/howto/regex.txt"
         rel="nofollow">Show Source</a></li>
</ul>

<div id="searchbox" style="display: none">
  <h3>Quick search</h3>
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    <p class="searchtip" style="font-size: 90%">
    Enter search terms or a module, class or function name.
    </p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="sockets.html" title="Socket Programming HOWTO"
             >next</a> |</li>
        <li class="right" >
          <a href="logging-cookbook.html" title="Logging Cookbook"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="http://www.python.org/">Python</a> &raquo;</li>
        <li>
          <a href="../index.html">Python 2.7.5 documentation</a> &raquo;
        </li>

          <li><a href="index.html" >Python HOWTOs</a> &raquo;</li> 
      </ul>
    </div>
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="http://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Jul 03, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.1.3.
    </div>

  </body>
</html>

./BlackJoker Mini Shell 1.0