GIF89a;
Direktori : /usr/share/doc/python-docs-2.7.5/html/howto/ |
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 — 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> »</li> <li> <a href="../index.html">Python 2.7.5 documentation</a> » </li> <li><a href="index.html" accesskey="U">Python HOWTOs</a> »</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 <<a class="reference external" href="mailto:amk%40amk.ca">amk<span>@</span>amk<span>.</span>ca</a>></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 “Does this string match the pattern?”, or “Is there a match for the pattern anywhere in this string?”. 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’t covered in this document, because it requires that you have a good understanding of the matching engine’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’ll start by learning about the simplest possible regular expressions. Since regular expressions are used to operate on strings, we’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’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’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’ll look at are <tt class="docutils literal"><span class="pre">[</span></tt> and <tt class="docutils literal"><span class="pre">]</span></tt>. They’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’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’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’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’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 “any character”.</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’t already possible with the methods available on strings. However, if that was the only additional capability of regexes, they wouldn’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’ll look at is <tt class="docutils literal"><span class="pre">*</span></tt>. <tt class="docutils literal"><span class="pre">*</span></tt> doesn’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’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’t have enough memory to construct a string that large, so you shouldn’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’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’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’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’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>‘s), but won’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’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 — 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’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’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’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">>>> </span><span class="kn">import</span> <span class="nn">re</span> <span class="gp">>>> </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">'ab*'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">p</span> <span class="go"><_sre.SRE_Pattern object at 0x...></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’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">>>> </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">'ab*'</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’t part of the core Python language, and no special syntax was created for expressing them. (There are applications that don’t need REs at all, so there’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’s usage of the same character for the same purpose in string literals.</p> <p>Let’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">"\\\\section"</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’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"\n"</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">"\n"</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">"ab*"</span></tt></td> <td><tt class="docutils literal"><span class="pre">r"ab*"</span></tt></td> </tr> <tr class="row-odd"><td><tt class="docutils literal"><span class="pre">"\\\\section"</span></tt></td> <td><tt class="docutils literal"><span class="pre">r"\\section"</span></tt></td> </tr> <tr class="row-even"><td><tt class="docutils literal"><span class="pre">"\\w+\\s+\\1"</span></tt></td> <td><tt class="docutils literal"><span class="pre">r"\w+\s+\1"</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’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’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) >>> import re >>> p = re.compile('[a-z]+') >>> p #doctest: +ELLIPSIS <_sre.SRE_Pattern object at 0x...></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’t match at all, since <tt class="docutils literal"><span class="pre">+</span></tt> means ‘one or more repetitions’. <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">>>> </span><span class="n">p</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">""</span><span class="p">)</span> <span class="gp">>>> </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">""</span><span class="p">)</span> <span class="go">None</span> </pre></div> </div> <p>Now, let’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">>>> </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">'tempo'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">m</span> <span class="go"><_sre.SRE_Match object at 0x...></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">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">()</span> <span class="go">'tempo'</span> <span class="gp">>>> </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">>>> </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">>>> </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">'::: message'</span><span class="p">)</span> <span class="go">None</span> <span class="gp">>>> </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">'::: message'</span><span class="p">);</span> <span class="k">print</span> <span class="n">m</span> <span class="go"><_sre.SRE_Match object at 0x...></span> <span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">()</span> <span class="go">'message'</span> <span class="gp">>>> </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">'string goes here'</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">'Match found: '</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">'No match'</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">>>> </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">'\d+'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">p</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="s">'12 drummers drumming, 11 pipers piping, 10 lords a-leaping'</span><span class="p">)</span> <span class="go">['12', '11', '10']</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">>>> </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">'12 drummers drumming, 11 ... 10 ...'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">iterator</span> <span class="go"><callable-iterator object at 0x...></span> <span class="gp">>>> </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’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">>>> </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'From\s+'</span><span class="p">,</span> <span class="s">'Fromage amk'</span><span class="p">)</span> <span class="go">None</span> <span class="gp">>>> </span><span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">r'From\s+'</span><span class="p">,</span> <span class="s">'From amk Thu May 14 19:12:10 1998'</span><span class="p">)</span> <span class="go"><_sre.SRE_Match object at 0x...></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’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’re familiar with Perl’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’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’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’re processing French text, you’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’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’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’t been explained yet; they’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’s neither in a character class or preceded by an unescaped backslash.</p> <p>For example, here’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"""</span> <span class="s"> &[#] # 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">"""</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">"&#(0[0-7]+"</span> <span class="s">"|[0-9]+"</span> <span class="s">"|x[0-9a-fA-F]+);"</span><span class="p">)</span> </pre></div> </div> <p>In the above example, Python’s automatic concatenation of string literals has been used to break up the RE into smaller pieces, but it’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’ve only covered a part of the features of regular expressions. In this section, we’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’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’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’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 “or” 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’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">>>> </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">'^From'</span><span class="p">,</span> <span class="s">'From Here to Eternity'</span><span class="p">)</span> <span class="go"><_sre.SRE_Match object at 0x...></span> <span class="gp">>>> </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">'^From'</span><span class="p">,</span> <span class="s">'Reciting From Memory'</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">>>> </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">'}$'</span><span class="p">,</span> <span class="s">'{block}'</span><span class="p">)</span> <span class="go"><_sre.SRE_Match object at 0x...></span> <span class="gp">>>> </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">'}$'</span><span class="p">,</span> <span class="s">'{block} '</span><span class="p">)</span> <span class="go">None</span> <span class="gp">>>> </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">'}$'</span><span class="p">,</span> <span class="s">'{block}</span><span class="se">\n</span><span class="s">'</span><span class="p">)</span> <span class="go"><_sre.SRE_Match object at 0x...></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’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’s a complete word; it won’t match when it’s contained inside another word.</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </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'\bclass\b'</span><span class="p">)</span> <span class="gp">>>> </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">'no class at all'</span><span class="p">)</span> <span class="go"><_sre.SRE_Match object at 0x...></span> <span class="gp">>>> </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">'the declassified algorithm'</span><span class="p">)</span> <span class="go">None</span> <span class="gp">>>> </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">'one subclass is'</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’s string literals and regular expression sequences. In Python’s string literals, <tt class="docutils literal"><span class="pre">\b</span></tt> is the backspace character, ASCII value 8. If you’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’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">>>> </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">'</span><span class="se">\b</span><span class="s">class</span><span class="se">\b</span><span class="s">'</span><span class="p">)</span> <span class="gp">>>> </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">'no class at all'</span><span class="p">)</span> <span class="go">None</span> <span class="gp">>>> </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">'</span><span class="se">\b</span><span class="s">'</span> <span class="o">+</span> <span class="s">'class'</span> <span class="o">+</span> <span class="s">'</span><span class="se">\b</span><span class="s">'</span><span class="p">)</span> <span class="go"><_sre.SRE_Match object at 0x...></span> </pre></div> </div> <p class="last">Second, inside a character class, where there’s no use for this assertion, <tt class="docutils literal"><span class="pre">\b</span></tt> represents the backspace character, for compatibility with Python’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’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">>>> </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">'(ab)*'</span><span class="p">)</span> <span class="gp">>>> </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">'ababababab'</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’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’ll see how to express groups that don’t capture the span of text that they match.</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </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">'(a)b'</span><span class="p">)</span> <span class="gp">>>> </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">'ab'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">()</span> <span class="go">'ab'</span> <span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span> <span class="go">'ab'</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">>>> </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">'(a(b)c)d'</span><span class="p">)</span> <span class="gp">>>> </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">'abcd'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span> <span class="go">'abcd'</span> <span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="go">'abc'</span> <span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="go">'b'</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">>>> </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">('b', 'abc', 'b')</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">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">groups</span><span class="p">()</span> <span class="go">('abc', 'b')</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’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">>>> </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'(\b\w+)\s+\1'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">p</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s">'Paris in the the spring'</span><span class="p">)</span><span class="o">.</span><span class="n">group</span><span class="p">()</span> <span class="go">'the the'</span> </pre></div> </div> <p>Backreferences like this aren’t often useful for just searching through a string — there are few text formats which repeat data in this way — but you’ll soon find out that they’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’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’s regular expressions confusingly different from standard REs. If you chose <tt class="docutils literal"><span class="pre">&</span></tt> as a new metacharacter, for example, old expressions would be assuming that <tt class="docutils literal"><span class="pre">&</span></tt> was a regular character and wouldn’t have escaped it by writing <tt class="docutils literal"><span class="pre">\&</span></tt> or <tt class="docutils literal"><span class="pre">[&]</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’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’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’s an extension that’s specific to Python. Currently there are two such extensions: <tt class="docutils literal"><span class="pre">(?P<name>...)</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’s sake.</p> <p>Now that we’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’ll want to use a group to collect a part of a regular expression, but aren’t interested in retrieving the group’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">>>> </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">"([abc])+"</span><span class="p">,</span> <span class="s">"abc"</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">groups</span><span class="p">()</span> <span class="go">('c',)</span> <span class="gp">>>> </span><span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">"(?:[abc])+"</span><span class="p">,</span> <span class="s">"abc"</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">groups</span><span class="p">()</span> <span class="go">()</span> </pre></div> </div> <p>Except for the fact that you can’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’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<name>...)</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’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">>>> </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'(?P<word>\b\w+\b)'</span><span class="p">)</span> <span class="gp">>>> </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">'(((( Lots of punctuation )))'</span> <span class="p">)</span> <span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="s">'word'</span><span class="p">)</span> <span class="go">'Lots'</span> <span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="go">'Lots'</span> </pre></div> </div> <p>Named groups are handy because they let you use easily-remembered names, instead of having to remember numbers. Here’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'INTERNALDATE "'</span> <span class="s">r'(?P<day>[ 123][0-9])-(?P<mon>[A-Z][a-z][a-z])-'</span> <span class="s">r'(?P<year>[0-9][0-9][0-9][0-9])'</span> <span class="s">r' (?P<hour>[0-9][0-9]):(?P<min>[0-9][0-9]):(?P<sec>[0-9][0-9])'</span> <span class="s">r' (?P<zonen>[-+])(?P<zoneh>[0-9][0-9])(?P<zonem>[0-9][0-9])'</span> <span class="s">r'"'</span><span class="p">)</span> </pre></div> </div> <p>It’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’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<word>\b\w+)\s+(?P=word)</span></tt>:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </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'(?P<word>\b\w+)\s+(?P=word)'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">p</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s">'Paris in the the spring'</span><span class="p">)</span><span class="o">.</span><span class="n">group</span><span class="p">()</span> <span class="go">'the the'</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’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’t</em> match at the current position in the string.</dd> </dl> <p>To make this concrete, let’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’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’s a metacharacter; I’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’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’t <tt class="docutils literal"><span class="pre">b</span></tt>; the second character isn’t <tt class="docutils literal"><span class="pre">a</span></tt>; or the third character isn’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’t accept a filename with a two-letter extension such as <tt class="docutils literal"><span class="pre">sendmail.cf</span></tt>. We’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’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’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’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’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’d expect, there’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">>>> </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'\W+'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">p</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s">'This is a test, short and sweet, of split().'</span><span class="p">)</span> <span class="go">['This', 'is', 'a', 'test', 'short', 'and', 'sweet', 'of', 'split', '']</span> <span class="gp">>>> </span><span class="n">p</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s">'This is a test, short and sweet, of split().'</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span> <span class="go">['This', 'is', 'a', 'test, short and sweet, of split().']</span> </pre></div> </div> <p>Sometimes you’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">>>> </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'\W+'</span><span class="p">)</span> <span class="gp">>>> </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'(\W+)'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">p</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s">'This... is a test.'</span><span class="p">)</span> <span class="go">['This', 'is', 'a', 'test', '']</span> <span class="gp">>>> </span><span class="n">p2</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s">'This... is a test.'</span><span class="p">)</span> <span class="go">['This', '... ', 'is', ' ', 'a', ' ', 'test', '.', '']</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">>>> </span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s">'[\W]+'</span><span class="p">,</span> <span class="s">'Words, words, words.'</span><span class="p">)</span> <span class="go">['Words', 'words', 'words', '']</span> <span class="gp">>>> </span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s">'([\W]+)'</span><span class="p">,</span> <span class="s">'Words, words, words.'</span><span class="p">)</span> <span class="go">['Words', ', ', 'words', ', ', 'words', '.', '']</span> <span class="gp">>>> </span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s">'[\W]+'</span><span class="p">,</span> <span class="s">'Words, words, words.'</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span> <span class="go">['Words', 'words, words.']</span> </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’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’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">>>> </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">'(blue|white|red)'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">p</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span> <span class="s">'colour'</span><span class="p">,</span> <span class="s">'blue socks and red shoes'</span><span class="p">)</span> <span class="go">'colour socks and colour shoes'</span> <span class="gp">>>> </span><span class="n">p</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span> <span class="s">'colour'</span><span class="p">,</span> <span class="s">'blue socks and red shoes'</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">'colour socks and red shoes'</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">>>> </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">'(blue|white|red)'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">p</span><span class="o">.</span><span class="n">subn</span><span class="p">(</span> <span class="s">'colour'</span><span class="p">,</span> <span class="s">'blue socks and red shoes'</span><span class="p">)</span> <span class="go">('colour socks and colour shoes', 2)</span> <span class="gp">>>> </span><span class="n">p</span><span class="o">.</span><span class="n">subn</span><span class="p">(</span> <span class="s">'colour'</span><span class="p">,</span> <span class="s">'no colours at all'</span><span class="p">)</span> <span class="go">('no colours at all', 0)</span> </pre></div> </div> <p>Empty matches are replaced only when they’re not adjacent to a previous match.</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </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">'x*'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">p</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="s">'-'</span><span class="p">,</span> <span class="s">'abxd'</span><span class="p">)</span> <span class="go">'-a-b-d-'</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">>>> </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">'section{ ( [^}]* ) }'</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">>>> </span><span class="n">p</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="s">r'subsection{\1}'</span><span class="p">,</span><span class="s">'section{First} section{second}'</span><span class="p">)</span> <span class="go">'subsection{First} subsection{second}'</span> </pre></div> </div> <p>There’s also a syntax for referring to named groups as defined by the <tt class="docutils literal"><span class="pre">(?P<name>...)</span></tt> syntax. <tt class="docutils literal"><span class="pre">\g<name></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<number></span></tt> uses the corresponding group number. <tt class="docutils literal"><span class="pre">\g<2></span></tt> is therefore equivalent to <tt class="docutils literal"><span class="pre">\2</span></tt>, but isn’t ambiguous in a replacement string such as <tt class="docutils literal"><span class="pre">\g<2>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">>>> </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">'section{ (?P<name> [^}]* ) }'</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">>>> </span><span class="n">p</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="s">r'subsection{\1}'</span><span class="p">,</span><span class="s">'section{First}'</span><span class="p">)</span> <span class="go">'subsection{First}'</span> <span class="gp">>>> </span><span class="n">p</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="s">r'subsection{\g<1>}'</span><span class="p">,</span><span class="s">'section{First}'</span><span class="p">)</span> <span class="go">'subsection{First}'</span> <span class="gp">>>> </span><span class="n">p</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="s">r'subsection{\g<name>}'</span><span class="p">,</span><span class="s">'section{First}'</span><span class="p">)</span> <span class="go">'subsection{First}'</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">>>> </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">"Return the hex string for a decimal number"</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">>>> </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'\d+'</span><span class="p">)</span> <span class="gp">>>> </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">'Call 65490 for printing, 49152 for user code.'</span><span class="p">)</span> <span class="go">'Call 0xffd2 for printing, 0xc000 for user code.'</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("(?i)b+",</span> <span class="pre">"x",</span> <span class="pre">"bbbb</span> <span class="pre">BBBB")</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’t intuitive and at times they don’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’re matching a fixed string, or a single character class, and you’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’re usually much faster, because the implementation is a single small C loop that’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>‘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’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’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">>>> </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">'super'</span><span class="p">,</span> <span class="s">'superstition'</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">>>> </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">'super'</span><span class="p">,</span> <span class="s">'insuperable'</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">>>> </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">'super'</span><span class="p">,</span> <span class="s">'superstition'</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">>>> </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">'super'</span><span class="p">,</span> <span class="s">'insuperable'</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’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’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’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">>>> </span><span class="n">s</span> <span class="o">=</span> <span class="s">'<html><head><title>Title</title>'</span> <span class="gp">>>> </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">>>> </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">'<.*>'</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">>>> </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">'<.*>'</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"><html><head><title>Title</title></span> </pre></div> </div> <p>The RE matches the <tt class="docutils literal"><span class="pre">'<'</span></tt> in <tt class="docutils literal"><span class="pre"><html></span></tt>, and the <tt class="docutils literal"><span class="pre">.*</span></tt> consumes the rest of the string. There’s still more left in the RE, though, and the <tt class="docutils literal"><span class="pre">></span></tt> can’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">></span></tt>. The final match extends from the <tt class="docutils literal"><span class="pre">'<'</span></tt> in <tt class="docutils literal"><span class="pre"><html></span></tt> to the <tt class="docutils literal"><span class="pre">'>'</span></tt> in <tt class="docutils literal"><span class="pre"></title></span></tt>, which isn’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">'>'</span></tt> is tried immediately after the first <tt class="docutils literal"><span class="pre">'<'</span></tt> matches, and when it fails, the engine advances a character at a time, retrying the <tt class="docutils literal"><span class="pre">'>'</span></tt> at every step. This produces just the right result:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </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">'<.*?>'</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"><html></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’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’ve probably noticed that regular expressions are a very compact notation, but they’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’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"""</span> <span class="s"> \s* # Skip leading whitespace</span> <span class="s"> (?P<header>[^:]+) # Header name</span> <span class="s"> \s* : # Whitespace, and a colon</span> <span class="s"> (?P<value>.*?) # The header'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">"""</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"\s*(?P<header>[^:]+)\s*:(?P<value>.*?)\s*$"</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’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’s Mastering Regular Expressions, published by O’Reilly. Unfortunately, it exclusively concentrates on Perl and Java’s flavours of regular expressions, and doesn’t contain any Python material at all, so it won’t be useful as a reference for programming in Python. (The first edition covered Python’s now-removed <tt class="xref py py-mod docutils literal"><span class="pre">regex</span></tt> module, which won’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> »</li> <li> <a href="../index.html">Python 2.7.5 documentation</a> » </li> <li><a href="index.html" >Python HOWTOs</a> »</li> </ul> </div> <div class="footer"> © <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>