gooderp18绿色标准版
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1712 lines
162KB

  1. <!DOCTYPE html>
  2. <html lang="en" data-content_root="../">
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />
  6. <meta property="og:title" content="Regular Expression HOWTO" />
  7. <meta property="og:type" content="website" />
  8. <meta property="og:url" content="https://docs.python.org/3/howto/regex.html" />
  9. <meta property="og:site_name" content="Python documentation" />
  10. <meta property="og:description" content="Author, A.M. Kuchling < amk@amk.ca>,. Abstract: This document is an introductory tutorial to using regular expressions in Python with the re module. It provides a gentler introduction than the corr..." />
  11. <meta property="og:image" content="https://docs.python.org/3/_static/og-image.png" />
  12. <meta property="og:image:alt" content="Python documentation" />
  13. <meta name="description" content="Author, A.M. Kuchling < amk@amk.ca>,. Abstract: This document is an introductory tutorial to using regular expressions in Python with the re module. It provides a gentler introduction than the corr..." />
  14. <meta property="og:image:width" content="200" />
  15. <meta property="og:image:height" content="200" />
  16. <meta name="theme-color" content="#3776ab" />
  17. <title>Regular Expression HOWTO &#8212; Python 3.12.3 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
  18. <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=80d5e7a1" />
  19. <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=bb723527" />
  20. <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=b20cc3f5" />
  21. <script src="../_static/documentation_options.js?v=2c828074"></script>
  22. <script src="../_static/doctools.js?v=888ff710"></script>
  23. <script src="../_static/sphinx_highlight.js?v=dc90522c"></script>
  24. <script src="../_static/sidebar.js"></script>
  25. <link rel="search" type="application/opensearchdescription+xml"
  26. title="Search within Python 3.12.3 documentation"
  27. href="../_static/opensearch.xml"/>
  28. <link rel="author" title="About these documents" href="../about.html" />
  29. <link rel="index" title="Index" href="../genindex.html" />
  30. <link rel="search" title="Search" href="../search.html" />
  31. <link rel="copyright" title="Copyright" href="../copyright.html" />
  32. <link rel="next" title="Socket Programming HOWTO" href="sockets.html" />
  33. <link rel="prev" title="Logging Cookbook" href="logging-cookbook.html" />
  34. <link rel="canonical" href="https://docs.python.org/3/howto/regex.html" />
  35. <style>
  36. @media only screen {
  37. table.full-width-table {
  38. width: 100%;
  39. }
  40. }
  41. </style>
  42. <link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
  43. <link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
  44. <script type="text/javascript" src="../_static/copybutton.js"></script>
  45. <script type="text/javascript" src="../_static/menu.js"></script>
  46. <script type="text/javascript" src="../_static/search-focus.js"></script>
  47. <script type="text/javascript" src="../_static/themetoggle.js"></script>
  48. </head>
  49. <body>
  50. <div class="mobile-nav">
  51. <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
  52. aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
  53. <nav class="nav-content" role="navigation">
  54. <label for="menuToggler" class="toggler__label">
  55. <span></span>
  56. </label>
  57. <span class="nav-items-wrapper">
  58. <a href="https://www.python.org/" class="nav-logo">
  59. <img src="../_static/py.svg" alt="Python logo"/>
  60. </a>
  61. <span class="version_switcher_placeholder"></span>
  62. <form role="search" class="search" action="../search.html" method="get">
  63. <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
  64. <path fill-rule="nonzero" fill="currentColor" d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 001.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 00-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 005.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path>
  65. </svg>
  66. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
  67. <input type="submit" value="Go"/>
  68. </form>
  69. </span>
  70. </nav>
  71. <div class="menu-wrapper">
  72. <nav class="menu" role="navigation" aria-label="main navigation">
  73. <div class="language_switcher_placeholder"></div>
  74. <label class="theme-selector-label">
  75. Theme
  76. <select class="theme-selector" oninput="activateTheme(this.value)">
  77. <option value="auto" selected>Auto</option>
  78. <option value="light">Light</option>
  79. <option value="dark">Dark</option>
  80. </select>
  81. </label>
  82. <div>
  83. <h3><a href="../contents.html">Table of Contents</a></h3>
  84. <ul>
  85. <li><a class="reference internal" href="#">Regular Expression HOWTO</a><ul>
  86. <li><a class="reference internal" href="#introduction">Introduction</a></li>
  87. <li><a class="reference internal" href="#simple-patterns">Simple Patterns</a><ul>
  88. <li><a class="reference internal" href="#matching-characters">Matching Characters</a></li>
  89. <li><a class="reference internal" href="#repeating-things">Repeating Things</a></li>
  90. </ul>
  91. </li>
  92. <li><a class="reference internal" href="#using-regular-expressions">Using Regular Expressions</a><ul>
  93. <li><a class="reference internal" href="#compiling-regular-expressions">Compiling Regular Expressions</a></li>
  94. <li><a class="reference internal" href="#the-backslash-plague">The Backslash Plague</a></li>
  95. <li><a class="reference internal" href="#performing-matches">Performing Matches</a></li>
  96. <li><a class="reference internal" href="#module-level-functions">Module-Level Functions</a></li>
  97. <li><a class="reference internal" href="#compilation-flags">Compilation Flags</a></li>
  98. </ul>
  99. </li>
  100. <li><a class="reference internal" href="#more-pattern-power">More Pattern Power</a><ul>
  101. <li><a class="reference internal" href="#more-metacharacters">More Metacharacters</a></li>
  102. <li><a class="reference internal" href="#grouping">Grouping</a></li>
  103. <li><a class="reference internal" href="#non-capturing-and-named-groups">Non-capturing and Named Groups</a></li>
  104. <li><a class="reference internal" href="#lookahead-assertions">Lookahead Assertions</a></li>
  105. </ul>
  106. </li>
  107. <li><a class="reference internal" href="#modifying-strings">Modifying Strings</a><ul>
  108. <li><a class="reference internal" href="#splitting-strings">Splitting Strings</a></li>
  109. <li><a class="reference internal" href="#search-and-replace">Search and Replace</a></li>
  110. </ul>
  111. </li>
  112. <li><a class="reference internal" href="#common-problems">Common Problems</a><ul>
  113. <li><a class="reference internal" href="#use-string-methods">Use String Methods</a></li>
  114. <li><a class="reference internal" href="#match-versus-search">match() versus search()</a></li>
  115. <li><a class="reference internal" href="#greedy-versus-non-greedy">Greedy versus Non-Greedy</a></li>
  116. <li><a class="reference internal" href="#using-re-verbose">Using re.VERBOSE</a></li>
  117. </ul>
  118. </li>
  119. <li><a class="reference internal" href="#feedback">Feedback</a></li>
  120. </ul>
  121. </li>
  122. </ul>
  123. </div>
  124. <div>
  125. <h4>Previous topic</h4>
  126. <p class="topless"><a href="logging-cookbook.html"
  127. title="previous chapter">Logging Cookbook</a></p>
  128. </div>
  129. <div>
  130. <h4>Next topic</h4>
  131. <p class="topless"><a href="sockets.html"
  132. title="next chapter">Socket Programming HOWTO</a></p>
  133. </div>
  134. <div role="note" aria-label="source link">
  135. <h3>This Page</h3>
  136. <ul class="this-page-menu">
  137. <li><a href="../bugs.html">Report a Bug</a></li>
  138. <li>
  139. <a href="https://github.com/python/cpython/blob/main/Doc/howto/regex.rst"
  140. rel="nofollow">Show Source
  141. </a>
  142. </li>
  143. </ul>
  144. </div>
  145. </nav>
  146. </div>
  147. </div>
  148. <div class="related" role="navigation" aria-label="related navigation">
  149. <h3>Navigation</h3>
  150. <ul>
  151. <li class="right" style="margin-right: 10px">
  152. <a href="../genindex.html" title="General Index"
  153. accesskey="I">index</a></li>
  154. <li class="right" >
  155. <a href="../py-modindex.html" title="Python Module Index"
  156. >modules</a> |</li>
  157. <li class="right" >
  158. <a href="sockets.html" title="Socket Programming HOWTO"
  159. accesskey="N">next</a> |</li>
  160. <li class="right" >
  161. <a href="logging-cookbook.html" title="Logging Cookbook"
  162. accesskey="P">previous</a> |</li>
  163. <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  164. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  165. <li class="switchers">
  166. <div class="language_switcher_placeholder"></div>
  167. <div class="version_switcher_placeholder"></div>
  168. </li>
  169. <li>
  170. </li>
  171. <li id="cpython-language-and-version">
  172. <a href="../index.html">3.12.3 Documentation</a> &#187;
  173. </li>
  174. <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python HOWTOs</a> &#187;</li>
  175. <li class="nav-item nav-item-this"><a href="">Regular Expression HOWTO</a></li>
  176. <li class="right">
  177. <div class="inline-search" role="search">
  178. <form class="inline-search" action="../search.html" method="get">
  179. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
  180. <input type="submit" value="Go" />
  181. </form>
  182. </div>
  183. |
  184. </li>
  185. <li class="right">
  186. <label class="theme-selector-label">
  187. Theme
  188. <select class="theme-selector" oninput="activateTheme(this.value)">
  189. <option value="auto" selected>Auto</option>
  190. <option value="light">Light</option>
  191. <option value="dark">Dark</option>
  192. </select>
  193. </label> |</li>
  194. </ul>
  195. </div>
  196. <div class="document">
  197. <div class="documentwrapper">
  198. <div class="bodywrapper">
  199. <div class="body" role="main">
  200. <section id="regular-expression-howto">
  201. <span id="regex-howto"></span><h1>Regular Expression HOWTO<a class="headerlink" href="#regular-expression-howto" title="Link to this heading">¶</a></h1>
  202. <dl class="field-list simple">
  203. <dt class="field-odd">Author<span class="colon">:</span></dt>
  204. <dd class="field-odd"><p>A.M. Kuchling &lt;<a class="reference external" href="mailto:amk&#37;&#52;&#48;amk&#46;ca">amk<span>&#64;</span>amk<span>&#46;</span>ca</a>&gt;</p>
  205. </dd>
  206. </dl>
  207. <aside class="topic">
  208. <p class="topic-title">Abstract</p>
  209. <p>This document is an introductory tutorial to using regular expressions in Python
  210. with the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module. It provides a gentler introduction than the
  211. corresponding section in the Library Reference.</p>
  212. </aside>
  213. <section id="introduction">
  214. <h2>Introduction<a class="headerlink" href="#introduction" title="Link to this heading">¶</a></h2>
  215. <p>Regular expressions (called REs, or regexes, or regex patterns) are essentially
  216. a tiny, highly specialized programming language embedded inside Python and made
  217. available through the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module. Using this little language, you specify
  218. the rules for the set of possible strings that you want to match; this set might
  219. contain English sentences, or e-mail addresses, or TeX commands, or anything you
  220. like. You can then ask questions such as “Does this string match the pattern?”,
  221. or “Is there a match for the pattern anywhere in this string?”. You can also
  222. use REs to modify a string or to split it apart in various ways.</p>
  223. <p>Regular expression patterns are compiled into a series of bytecodes which are
  224. then executed by a matching engine written in C. For advanced use, it may be
  225. necessary to pay careful attention to how the engine will execute a given RE,
  226. and write the RE in a certain way in order to produce bytecode that runs faster.
  227. Optimization isn’t covered in this document, because it requires that you have a
  228. good understanding of the matching engine’s internals.</p>
  229. <p>The regular expression language is relatively small and restricted, so not all
  230. possible string processing tasks can be done using regular expressions. There
  231. are also tasks that <em>can</em> be done with regular expressions, but the expressions
  232. turn out to be very complicated. In these cases, you may be better off writing
  233. Python code to do the processing; while Python code will be slower than an
  234. elaborate regular expression, it will also probably be more understandable.</p>
  235. </section>
  236. <section id="simple-patterns">
  237. <h2>Simple Patterns<a class="headerlink" href="#simple-patterns" title="Link to this heading">¶</a></h2>
  238. <p>We’ll start by learning about the simplest possible regular expressions. Since
  239. regular expressions are used to operate on strings, we’ll begin with the most
  240. common task: matching characters.</p>
  241. <p>For a detailed explanation of the computer science underlying regular
  242. expressions (deterministic and non-deterministic finite automata), you can refer
  243. to almost any textbook on writing compilers.</p>
  244. <section id="matching-characters">
  245. <h3>Matching Characters<a class="headerlink" href="#matching-characters" title="Link to this heading">¶</a></h3>
  246. <p>Most letters and characters will simply match themselves. For example, the
  247. regular expression <code class="docutils literal notranslate"><span class="pre">test</span></code> will match the string <code class="docutils literal notranslate"><span class="pre">test</span></code> exactly. (You can
  248. enable a case-insensitive mode that would let this RE match <code class="docutils literal notranslate"><span class="pre">Test</span></code> or <code class="docutils literal notranslate"><span class="pre">TEST</span></code>
  249. as well; more about this later.)</p>
  250. <p>There are exceptions to this rule; some characters are special
  251. <em class="dfn">metacharacters</em>, and don’t match themselves. Instead, they signal that
  252. some out-of-the-ordinary thing should be matched, or they affect other portions
  253. of the RE by repeating them or changing their meaning. Much of this document is
  254. devoted to discussing various metacharacters and what they do.</p>
  255. <p>Here’s a complete list of the metacharacters; their meanings will be discussed
  256. in the rest of this HOWTO.</p>
  257. <div class="highlight-none notranslate"><div class="highlight"><pre><span></span>. ^ $ * + ? { } [ ] \ | ( )
  258. </pre></div>
  259. </div>
  260. <p>The first metacharacters we’ll look at are <code class="docutils literal notranslate"><span class="pre">[</span></code> and <code class="docutils literal notranslate"><span class="pre">]</span></code>. They’re used for
  261. specifying a character class, which is a set of characters that you wish to
  262. match. Characters can be listed individually, or a range of characters can be
  263. indicated by giving two characters and separating them by a <code class="docutils literal notranslate"><span class="pre">'-'</span></code>. For
  264. example, <code class="docutils literal notranslate"><span class="pre">[abc]</span></code> will match any of the characters <code class="docutils literal notranslate"><span class="pre">a</span></code>, <code class="docutils literal notranslate"><span class="pre">b</span></code>, or <code class="docutils literal notranslate"><span class="pre">c</span></code>; this
  265. is the same as <code class="docutils literal notranslate"><span class="pre">[a-c]</span></code>, which uses a range to express the same set of
  266. characters. If you wanted to match only lowercase letters, your RE would be
  267. <code class="docutils literal notranslate"><span class="pre">[a-z]</span></code>.</p>
  268. <p>Metacharacters (except <code class="docutils literal notranslate"><span class="pre">\</span></code>) are not active inside classes. For example, <code class="docutils literal notranslate"><span class="pre">[akm$]</span></code> will
  269. match any of the characters <code class="docutils literal notranslate"><span class="pre">'a'</span></code>, <code class="docutils literal notranslate"><span class="pre">'k'</span></code>, <code class="docutils literal notranslate"><span class="pre">'m'</span></code>, or <code class="docutils literal notranslate"><span class="pre">'$'</span></code>; <code class="docutils literal notranslate"><span class="pre">'$'</span></code> is
  270. usually a metacharacter, but inside a character class it’s stripped of its
  271. special nature.</p>
  272. <p>You can match the characters not listed within the class by <em class="dfn">complementing</em>
  273. the set. This is indicated by including a <code class="docutils literal notranslate"><span class="pre">'^'</span></code> as the first character of the
  274. class. For example, <code class="docutils literal notranslate"><span class="pre">[^5]</span></code> will match any character except <code class="docutils literal notranslate"><span class="pre">'5'</span></code>. If the
  275. caret appears elsewhere in a character class, it does not have special meaning.
  276. For example: <code class="docutils literal notranslate"><span class="pre">[5^]</span></code> will match either a <code class="docutils literal notranslate"><span class="pre">'5'</span></code> or a <code class="docutils literal notranslate"><span class="pre">'^'</span></code>.</p>
  277. <p>Perhaps the most important metacharacter is the backslash, <code class="docutils literal notranslate"><span class="pre">\</span></code>. As in Python
  278. string literals, the backslash can be followed by various characters to signal
  279. various special sequences. It’s also used to escape all the metacharacters so
  280. you can still match them in patterns; for example, if you need to match a <code class="docutils literal notranslate"><span class="pre">[</span></code>
  281. or <code class="docutils literal notranslate"><span class="pre">\</span></code>, you can precede them with a backslash to remove their special
  282. meaning: <code class="docutils literal notranslate"><span class="pre">\[</span></code> or <code class="docutils literal notranslate"><span class="pre">\\</span></code>.</p>
  283. <p>Some of the special sequences beginning with <code class="docutils literal notranslate"><span class="pre">'\'</span></code> represent
  284. predefined sets of characters that are often useful, such as the set
  285. of digits, the set of letters, or the set of anything that isn’t
  286. whitespace.</p>
  287. <p>Let’s take an example: <code class="docutils literal notranslate"><span class="pre">\w</span></code> matches any alphanumeric character. If
  288. the regex pattern is expressed in bytes, this is equivalent to the
  289. class <code class="docutils literal notranslate"><span class="pre">[a-zA-Z0-9_]</span></code>. If the regex pattern is a string, <code class="docutils literal notranslate"><span class="pre">\w</span></code> will
  290. match all the characters marked as letters in the Unicode database
  291. provided by the <a class="reference internal" href="../library/unicodedata.html#module-unicodedata" title="unicodedata: Access the Unicode Database."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unicodedata</span></code></a> module. You can use the more
  292. restricted definition of <code class="docutils literal notranslate"><span class="pre">\w</span></code> in a string pattern by supplying the
  293. <a class="reference internal" href="../library/re.html#re.ASCII" title="re.ASCII"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.ASCII</span></code></a> flag when compiling the regular expression.</p>
  294. <p>The following list of special sequences isn’t complete. For a complete
  295. list of sequences and expanded class definitions for Unicode string
  296. patterns, see the last part of <a class="reference internal" href="../library/re.html#re-syntax"><span class="std std-ref">Regular Expression Syntax</span></a> in the Standard Library reference. In general, the
  297. Unicode versions match any character that’s in the appropriate
  298. category in the Unicode database.</p>
  299. <dl class="simple">
  300. <dt><code class="docutils literal notranslate"><span class="pre">\d</span></code></dt><dd><p>Matches any decimal digit; this is equivalent to the class <code class="docutils literal notranslate"><span class="pre">[0-9]</span></code>.</p>
  301. </dd>
  302. <dt><code class="docutils literal notranslate"><span class="pre">\D</span></code></dt><dd><p>Matches any non-digit character; this is equivalent to the class <code class="docutils literal notranslate"><span class="pre">[^0-9]</span></code>.</p>
  303. </dd>
  304. <dt><code class="docutils literal notranslate"><span class="pre">\s</span></code></dt><dd><p>Matches any whitespace character; this is equivalent to the class <code class="docutils literal notranslate"><span class="pre">[</span>
  305. <span class="pre">\t\n\r\f\v]</span></code>.</p>
  306. </dd>
  307. <dt><code class="docutils literal notranslate"><span class="pre">\S</span></code></dt><dd><p>Matches any non-whitespace character; this is equivalent to the class <code class="docutils literal notranslate"><span class="pre">[^</span>
  308. <span class="pre">\t\n\r\f\v]</span></code>.</p>
  309. </dd>
  310. <dt><code class="docutils literal notranslate"><span class="pre">\w</span></code></dt><dd><p>Matches any alphanumeric character; this is equivalent to the class
  311. <code class="docutils literal notranslate"><span class="pre">[a-zA-Z0-9_]</span></code>.</p>
  312. </dd>
  313. <dt><code class="docutils literal notranslate"><span class="pre">\W</span></code></dt><dd><p>Matches any non-alphanumeric character; this is equivalent to the class
  314. <code class="docutils literal notranslate"><span class="pre">[^a-zA-Z0-9_]</span></code>.</p>
  315. </dd>
  316. </dl>
  317. <p>These sequences can be included inside a character class. For example,
  318. <code class="docutils literal notranslate"><span class="pre">[\s,.]</span></code> is a character class that will match any whitespace character, or
  319. <code class="docutils literal notranslate"><span class="pre">','</span></code> or <code class="docutils literal notranslate"><span class="pre">'.'</span></code>.</p>
  320. <p>The final metacharacter in this section is <code class="docutils literal notranslate"><span class="pre">.</span></code>. It matches anything except a
  321. newline character, and there’s an alternate mode (<a class="reference internal" href="../library/re.html#re.DOTALL" title="re.DOTALL"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.DOTALL</span></code></a>) where it will
  322. match even a newline. <code class="docutils literal notranslate"><span class="pre">.</span></code> is often used where you want to match “any
  323. character”.</p>
  324. </section>
  325. <section id="repeating-things">
  326. <h3>Repeating Things<a class="headerlink" href="#repeating-things" title="Link to this heading">¶</a></h3>
  327. <p>Being able to match varying sets of characters is the first thing regular
  328. expressions can do that isn’t already possible with the methods available on
  329. strings. However, if that was the only additional capability of regexes, they
  330. wouldn’t be much of an advance. Another capability is that you can specify that
  331. portions of the RE must be repeated a certain number of times.</p>
  332. <p>The first metacharacter for repeating things that we’ll look at is <code class="docutils literal notranslate"><span class="pre">*</span></code>. <code class="docutils literal notranslate"><span class="pre">*</span></code>
  333. doesn’t match the literal character <code class="docutils literal notranslate"><span class="pre">'*'</span></code>; instead, it specifies that the
  334. previous character can be matched zero or more times, instead of exactly once.</p>
  335. <p>For example, <code class="docutils literal notranslate"><span class="pre">ca*t</span></code> will match <code class="docutils literal notranslate"><span class="pre">'ct'</span></code> (0 <code class="docutils literal notranslate"><span class="pre">'a'</span></code> characters), <code class="docutils literal notranslate"><span class="pre">'cat'</span></code> (1 <code class="docutils literal notranslate"><span class="pre">'a'</span></code>),
  336. <code class="docutils literal notranslate"><span class="pre">'caaat'</span></code> (3 <code class="docutils literal notranslate"><span class="pre">'a'</span></code> characters), and so forth.</p>
  337. <p>Repetitions such as <code class="docutils literal notranslate"><span class="pre">*</span></code> are <em class="dfn">greedy</em>; when repeating a RE, the matching
  338. engine will try to repeat it as many times as possible. If later portions of the
  339. pattern don’t match, the matching engine will then back up and try again with
  340. fewer repetitions.</p>
  341. <p>A step-by-step example will make this more obvious. Let’s consider the
  342. expression <code class="docutils literal notranslate"><span class="pre">a[bcd]*b</span></code>. This matches the letter <code class="docutils literal notranslate"><span class="pre">'a'</span></code>, zero or more letters
  343. from the class <code class="docutils literal notranslate"><span class="pre">[bcd]</span></code>, and finally ends with a <code class="docutils literal notranslate"><span class="pre">'b'</span></code>. Now imagine matching
  344. this RE against the string <code class="docutils literal notranslate"><span class="pre">'abcbd'</span></code>.</p>
  345. <table class="docutils align-default">
  346. <thead>
  347. <tr class="row-odd"><th class="head"><p>Step</p></th>
  348. <th class="head"><p>Matched</p></th>
  349. <th class="head"><p>Explanation</p></th>
  350. </tr>
  351. </thead>
  352. <tbody>
  353. <tr class="row-even"><td><p>1</p></td>
  354. <td><p><code class="docutils literal notranslate"><span class="pre">a</span></code></p></td>
  355. <td><p>The <code class="docutils literal notranslate"><span class="pre">a</span></code> in the RE matches.</p></td>
  356. </tr>
  357. <tr class="row-odd"><td><p>2</p></td>
  358. <td><p><code class="docutils literal notranslate"><span class="pre">abcbd</span></code></p></td>
  359. <td><p>The engine matches <code class="docutils literal notranslate"><span class="pre">[bcd]*</span></code>,
  360. going as far as it can, which
  361. is to the end of the string.</p></td>
  362. </tr>
  363. <tr class="row-even"><td><p>3</p></td>
  364. <td><p><em>Failure</em></p></td>
  365. <td><p>The engine tries to match
  366. <code class="docutils literal notranslate"><span class="pre">b</span></code>, but the current position
  367. is at the end of the string, so
  368. it fails.</p></td>
  369. </tr>
  370. <tr class="row-odd"><td><p>4</p></td>
  371. <td><p><code class="docutils literal notranslate"><span class="pre">abcb</span></code></p></td>
  372. <td><p>Back up, so that <code class="docutils literal notranslate"><span class="pre">[bcd]*</span></code>
  373. matches one less character.</p></td>
  374. </tr>
  375. <tr class="row-even"><td><p>5</p></td>
  376. <td><p><em>Failure</em></p></td>
  377. <td><p>Try <code class="docutils literal notranslate"><span class="pre">b</span></code> again, but the
  378. current position is at the last
  379. character, which is a <code class="docutils literal notranslate"><span class="pre">'d'</span></code>.</p></td>
  380. </tr>
  381. <tr class="row-odd"><td><p>6</p></td>
  382. <td><p><code class="docutils literal notranslate"><span class="pre">abc</span></code></p></td>
  383. <td><p>Back up again, so that
  384. <code class="docutils literal notranslate"><span class="pre">[bcd]*</span></code> is only matching
  385. <code class="docutils literal notranslate"><span class="pre">bc</span></code>.</p></td>
  386. </tr>
  387. <tr class="row-even"><td><p>6</p></td>
  388. <td><p><code class="docutils literal notranslate"><span class="pre">abcb</span></code></p></td>
  389. <td><p>Try <code class="docutils literal notranslate"><span class="pre">b</span></code> again. This time
  390. the character at the
  391. current position is <code class="docutils literal notranslate"><span class="pre">'b'</span></code>, so
  392. it succeeds.</p></td>
  393. </tr>
  394. </tbody>
  395. </table>
  396. <p>The end of the RE has now been reached, and it has matched <code class="docutils literal notranslate"><span class="pre">'abcb'</span></code>. This
  397. demonstrates how the matching engine goes as far as it can at first, and if no
  398. match is found it will then progressively back up and retry the rest of the RE
  399. again and again. It will back up until it has tried zero matches for
  400. <code class="docutils literal notranslate"><span class="pre">[bcd]*</span></code>, and if that subsequently fails, the engine will conclude that the
  401. string doesn’t match the RE at all.</p>
  402. <p>Another repeating metacharacter is <code class="docutils literal notranslate"><span class="pre">+</span></code>, which matches one or more times. Pay
  403. careful attention to the difference between <code class="docutils literal notranslate"><span class="pre">*</span></code> and <code class="docutils literal notranslate"><span class="pre">+</span></code>; <code class="docutils literal notranslate"><span class="pre">*</span></code> matches
  404. <em>zero</em> or more times, so whatever’s being repeated may not be present at all,
  405. while <code class="docutils literal notranslate"><span class="pre">+</span></code> requires at least <em>one</em> occurrence. To use a similar example,
  406. <code class="docutils literal notranslate"><span class="pre">ca+t</span></code> will match <code class="docutils literal notranslate"><span class="pre">'cat'</span></code> (1 <code class="docutils literal notranslate"><span class="pre">'a'</span></code>), <code class="docutils literal notranslate"><span class="pre">'caaat'</span></code> (3 <code class="docutils literal notranslate"><span class="pre">'a'</span></code>s), but won’t
  407. match <code class="docutils literal notranslate"><span class="pre">'ct'</span></code>.</p>
  408. <p>There are two more repeating operators or quantifiers. The question mark character, <code class="docutils literal notranslate"><span class="pre">?</span></code>,
  409. matches either once or zero times; you can think of it as marking something as
  410. being optional. For example, <code class="docutils literal notranslate"><span class="pre">home-?brew</span></code> matches either <code class="docutils literal notranslate"><span class="pre">'homebrew'</span></code> or
  411. <code class="docutils literal notranslate"><span class="pre">'home-brew'</span></code>.</p>
  412. <p>The most complicated quantifier is <code class="docutils literal notranslate"><span class="pre">{m,n}</span></code>, where <em>m</em> and <em>n</em> are
  413. decimal integers. This quantifier means there must be at least <em>m</em> repetitions,
  414. and at most <em>n</em>. For example, <code class="docutils literal notranslate"><span class="pre">a/{1,3}b</span></code> will match <code class="docutils literal notranslate"><span class="pre">'a/b'</span></code>, <code class="docutils literal notranslate"><span class="pre">'a//b'</span></code>, and
  415. <code class="docutils literal notranslate"><span class="pre">'a///b'</span></code>. It won’t match <code class="docutils literal notranslate"><span class="pre">'ab'</span></code>, which has no slashes, or <code class="docutils literal notranslate"><span class="pre">'a////b'</span></code>, which
  416. has four.</p>
  417. <p>You can omit either <em>m</em> or <em>n</em>; in that case, a reasonable value is assumed for
  418. the missing value. Omitting <em>m</em> is interpreted as a lower limit of 0, while
  419. omitting <em>n</em> results in an upper bound of infinity.</p>
  420. <p>The simplest case <code class="docutils literal notranslate"><span class="pre">{m}</span></code> matches the preceding item exactly <em>m</em> times.
  421. For example, <code class="docutils literal notranslate"><span class="pre">a/{2}b</span></code> will only match <code class="docutils literal notranslate"><span class="pre">'a//b'</span></code>.</p>
  422. <p>Readers of a reductionist bent may notice that the three other quantifiers can
  423. all be expressed using this notation. <code class="docutils literal notranslate"><span class="pre">{0,}</span></code> is the same as <code class="docutils literal notranslate"><span class="pre">*</span></code>, <code class="docutils literal notranslate"><span class="pre">{1,}</span></code>
  424. is equivalent to <code class="docutils literal notranslate"><span class="pre">+</span></code>, and <code class="docutils literal notranslate"><span class="pre">{0,1}</span></code> is the same as <code class="docutils literal notranslate"><span class="pre">?</span></code>. It’s better to use
  425. <code class="docutils literal notranslate"><span class="pre">*</span></code>, <code class="docutils literal notranslate"><span class="pre">+</span></code>, or <code class="docutils literal notranslate"><span class="pre">?</span></code> when you can, simply because they’re shorter and easier
  426. to read.</p>
  427. </section>
  428. </section>
  429. <section id="using-regular-expressions">
  430. <h2>Using Regular Expressions<a class="headerlink" href="#using-regular-expressions" title="Link to this heading">¶</a></h2>
  431. <p>Now that we’ve looked at some simple regular expressions, how do we actually use
  432. them in Python? The <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module provides an interface to the regular
  433. expression engine, allowing you to compile REs into objects and then perform
  434. matches with them.</p>
  435. <section id="compiling-regular-expressions">
  436. <h3>Compiling Regular Expressions<a class="headerlink" href="#compiling-regular-expressions" title="Link to this heading">¶</a></h3>
  437. <p>Regular expressions are compiled into pattern objects, which have
  438. methods for various operations such as searching for pattern matches or
  439. performing string substitutions.</p>
  440. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">re</span>
  441. <span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">&#39;ab*&#39;</span><span class="p">)</span>
  442. <span class="gp">&gt;&gt;&gt; </span><span class="n">p</span>
  443. <span class="go">re.compile(&#39;ab*&#39;)</span>
  444. </pre></div>
  445. </div>
  446. <p><a class="reference internal" href="../library/re.html#re.compile" title="re.compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.compile()</span></code></a> also accepts an optional <em>flags</em> argument, used to enable
  447. various special features and syntax variations. We’ll go over the available
  448. settings later, but for now a single example will do:</p>
  449. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">&#39;ab*&#39;</span><span class="p">,</span> <span class="n">re</span><span class="o">.</span><span class="n">IGNORECASE</span><span class="p">)</span>
  450. </pre></div>
  451. </div>
  452. <p>The RE is passed to <a class="reference internal" href="../library/re.html#re.compile" title="re.compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.compile()</span></code></a> as a string. REs are handled as strings
  453. because regular expressions aren’t part of the core Python language, and no
  454. special syntax was created for expressing them. (There are applications that
  455. don’t need REs at all, so there’s no need to bloat the language specification by
  456. including them.) Instead, the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module is simply a C extension module
  457. included with Python, just like the <a class="reference internal" href="../library/socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></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."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zlib</span></code></a> modules.</p>
  458. <p>Putting REs in strings keeps the Python language simpler, but has one
  459. disadvantage which is the topic of the next section.</p>
  460. </section>
  461. <section id="the-backslash-plague">
  462. <span id="id1"></span><h3>The Backslash Plague<a class="headerlink" href="#the-backslash-plague" title="Link to this heading">¶</a></h3>
  463. <p>As stated earlier, regular expressions use the backslash character (<code class="docutils literal notranslate"><span class="pre">'\'</span></code>) to
  464. indicate special forms or to allow special characters to be used without
  465. invoking their special meaning. This conflicts with Python’s usage of the same
  466. character for the same purpose in string literals.</p>
  467. <p>Let’s say you want to write a RE that matches the string <code class="docutils literal notranslate"><span class="pre">\section</span></code>, which
  468. might be found in a LaTeX file. To figure out what to write in the program
  469. code, start with the desired string to be matched. Next, you must escape any
  470. backslashes and other metacharacters by preceding them with a backslash,
  471. resulting in the string <code class="docutils literal notranslate"><span class="pre">\\section</span></code>. The resulting string that must be passed
  472. to <a class="reference internal" href="../library/re.html#re.compile" title="re.compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.compile()</span></code></a> must be <code class="docutils literal notranslate"><span class="pre">\\section</span></code>. However, to express this as a
  473. Python string literal, both backslashes must be escaped <em>again</em>.</p>
  474. <table class="docutils align-default">
  475. <thead>
  476. <tr class="row-odd"><th class="head"><p>Characters</p></th>
  477. <th class="head"><p>Stage</p></th>
  478. </tr>
  479. </thead>
  480. <tbody>
  481. <tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">\section</span></code></p></td>
  482. <td><p>Text string to be matched</p></td>
  483. </tr>
  484. <tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">\\section</span></code></p></td>
  485. <td><p>Escaped backslash for <a class="reference internal" href="../library/re.html#re.compile" title="re.compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.compile()</span></code></a></p></td>
  486. </tr>
  487. <tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">&quot;\\\\section&quot;</span></code></p></td>
  488. <td><p>Escaped backslashes for a string literal</p></td>
  489. </tr>
  490. </tbody>
  491. </table>
  492. <p>In short, to match a literal backslash, one has to write <code class="docutils literal notranslate"><span class="pre">'\\\\'</span></code> as the RE
  493. string, because the regular expression must be <code class="docutils literal notranslate"><span class="pre">\\</span></code>, and each backslash must
  494. be expressed as <code class="docutils literal notranslate"><span class="pre">\\</span></code> inside a regular Python string literal. In REs that
  495. feature backslashes repeatedly, this leads to lots of repeated backslashes and
  496. makes the resulting strings difficult to understand.</p>
  497. <p>The solution is to use Python’s raw string notation for regular expressions;
  498. backslashes are not handled in any special way in a string literal prefixed with
  499. <code class="docutils literal notranslate"><span class="pre">'r'</span></code>, so <code class="docutils literal notranslate"><span class="pre">r&quot;\n&quot;</span></code> is a two-character string containing <code class="docutils literal notranslate"><span class="pre">'\'</span></code> and <code class="docutils literal notranslate"><span class="pre">'n'</span></code>,
  500. while <code class="docutils literal notranslate"><span class="pre">&quot;\n&quot;</span></code> is a one-character string containing a newline. Regular
  501. expressions will often be written in Python code using this raw string notation.</p>
  502. <p>In addition, special escape sequences that are valid in regular expressions,
  503. but not valid as Python string literals, now result in a
  504. <a class="reference internal" href="../library/exceptions.html#DeprecationWarning" title="DeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DeprecationWarning</span></code></a> and will eventually become a <a class="reference internal" href="../library/exceptions.html#SyntaxError" title="SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a>,
  505. which means the sequences will be invalid if raw string notation or escaping
  506. the backslashes isn’t used.</p>
  507. <table class="docutils align-default">
  508. <thead>
  509. <tr class="row-odd"><th class="head"><p>Regular String</p></th>
  510. <th class="head"><p>Raw string</p></th>
  511. </tr>
  512. </thead>
  513. <tbody>
  514. <tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">&quot;ab*&quot;</span></code></p></td>
  515. <td><p><code class="docutils literal notranslate"><span class="pre">r&quot;ab*&quot;</span></code></p></td>
  516. </tr>
  517. <tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">&quot;\\\\section&quot;</span></code></p></td>
  518. <td><p><code class="docutils literal notranslate"><span class="pre">r&quot;\\section&quot;</span></code></p></td>
  519. </tr>
  520. <tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">&quot;\\w+\\s+\\1&quot;</span></code></p></td>
  521. <td><p><code class="docutils literal notranslate"><span class="pre">r&quot;\w+\s+\1&quot;</span></code></p></td>
  522. </tr>
  523. </tbody>
  524. </table>
  525. </section>
  526. <section id="performing-matches">
  527. <h3>Performing Matches<a class="headerlink" href="#performing-matches" title="Link to this heading">¶</a></h3>
  528. <p>Once you have an object representing a compiled regular expression, what do you
  529. do with it? Pattern objects have several methods and attributes.
  530. 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."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> docs
  531. for a complete listing.</p>
  532. <table class="docutils align-default">
  533. <thead>
  534. <tr class="row-odd"><th class="head"><p>Method/Attribute</p></th>
  535. <th class="head"><p>Purpose</p></th>
  536. </tr>
  537. </thead>
  538. <tbody>
  539. <tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">match()</span></code></p></td>
  540. <td><p>Determine if the RE matches at the beginning
  541. of the string.</p></td>
  542. </tr>
  543. <tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">search()</span></code></p></td>
  544. <td><p>Scan through a string, looking for any
  545. location where this RE matches.</p></td>
  546. </tr>
  547. <tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">findall()</span></code></p></td>
  548. <td><p>Find all substrings where the RE matches, and
  549. returns them as a list.</p></td>
  550. </tr>
  551. <tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">finditer()</span></code></p></td>
  552. <td><p>Find all substrings where the RE matches, and
  553. returns them as an <a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a>.</p></td>
  554. </tr>
  555. </tbody>
  556. </table>
  557. <p><a class="reference internal" href="../library/re.html#re.Pattern.match" title="re.Pattern.match"><code class="xref py py-meth docutils literal notranslate"><span class="pre">match()</span></code></a> and <a class="reference internal" href="../library/re.html#re.Pattern.search" title="re.Pattern.search"><code class="xref py py-meth docutils literal notranslate"><span class="pre">search()</span></code></a> return <code class="docutils literal notranslate"><span class="pre">None</span></code> if no match can be found. If
  558. they’re successful, a <a class="reference internal" href="../library/re.html#match-objects"><span class="std std-ref">match object</span></a> instance is returned,
  559. containing information about the match: where it starts and ends, the substring
  560. it matched, and more.</p>
  561. <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."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a>
  562. module.</p>
  563. <p>This HOWTO uses the standard Python interpreter for its examples. First, run the
  564. Python interpreter, import the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module, and compile a RE:</p>
  565. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">re</span>
  566. <span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">&#39;[a-z]+&#39;</span><span class="p">)</span>
  567. <span class="gp">&gt;&gt;&gt; </span><span class="n">p</span>
  568. <span class="go">re.compile(&#39;[a-z]+&#39;)</span>
  569. </pre></div>
  570. </div>
  571. <p>Now, you can try matching various strings against the RE <code class="docutils literal notranslate"><span class="pre">[a-z]+</span></code>. An empty
  572. string shouldn’t match at all, since <code class="docutils literal notranslate"><span class="pre">+</span></code> means ‘one or more repetitions’.
  573. <a class="reference internal" href="../library/re.html#re.Pattern.match" title="re.Pattern.match"><code class="xref py py-meth docutils literal notranslate"><span class="pre">match()</span></code></a> should return <code class="docutils literal notranslate"><span class="pre">None</span></code> in this case, which will cause the
  574. interpreter to print no output. You can explicitly print the result of
  575. <code class="xref py py-meth docutils literal notranslate"><span class="pre">match()</span></code> to make this clear.</p>
  576. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;&quot;</span><span class="p">)</span>
  577. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;&quot;</span><span class="p">))</span>
  578. <span class="go">None</span>
  579. </pre></div>
  580. </div>
  581. <p>Now, let’s try it on a string that it should match, such as <code class="docutils literal notranslate"><span class="pre">tempo</span></code>. In this
  582. case, <a class="reference internal" href="../library/re.html#re.Pattern.match" title="re.Pattern.match"><code class="xref py py-meth docutils literal notranslate"><span class="pre">match()</span></code></a> will return a <a class="reference internal" href="../library/re.html#match-objects"><span class="std std-ref">match object</span></a>, so you
  583. should store the result in a variable for later use.</p>
  584. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s1">&#39;tempo&#39;</span><span class="p">)</span>
  585. <span class="gp">&gt;&gt;&gt; </span><span class="n">m</span>
  586. <span class="go">&lt;re.Match object; span=(0, 5), match=&#39;tempo&#39;&gt;</span>
  587. </pre></div>
  588. </div>
  589. <p>Now you can query the <a class="reference internal" href="../library/re.html#match-objects"><span class="std std-ref">match object</span></a> for information
  590. about the matching string. Match object instances
  591. also have several methods and attributes; the most important ones are:</p>
  592. <table class="docutils align-default">
  593. <thead>
  594. <tr class="row-odd"><th class="head"><p>Method/Attribute</p></th>
  595. <th class="head"><p>Purpose</p></th>
  596. </tr>
  597. </thead>
  598. <tbody>
  599. <tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">group()</span></code></p></td>
  600. <td><p>Return the string matched by the RE</p></td>
  601. </tr>
  602. <tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">start()</span></code></p></td>
  603. <td><p>Return the starting position of the match</p></td>
  604. </tr>
  605. <tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">end()</span></code></p></td>
  606. <td><p>Return the ending position of the match</p></td>
  607. </tr>
  608. <tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">span()</span></code></p></td>
  609. <td><p>Return a tuple containing the (start, end)
  610. positions of the match</p></td>
  611. </tr>
  612. </tbody>
  613. </table>
  614. <p>Trying these methods will soon clarify their meaning:</p>
  615. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">()</span>
  616. <span class="go">&#39;tempo&#39;</span>
  617. <span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">start</span><span class="p">(),</span> <span class="n">m</span><span class="o">.</span><span class="n">end</span><span class="p">()</span>
  618. <span class="go">(0, 5)</span>
  619. <span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">span</span><span class="p">()</span>
  620. <span class="go">(0, 5)</span>
  621. </pre></div>
  622. </div>
  623. <p><a class="reference internal" href="../library/re.html#re.Match.group" title="re.Match.group"><code class="xref py py-meth docutils literal notranslate"><span class="pre">group()</span></code></a> returns the substring that was matched by the RE. <a class="reference internal" href="../library/re.html#re.Match.start" title="re.Match.start"><code class="xref py py-meth docutils literal notranslate"><span class="pre">start()</span></code></a>
  624. and <a class="reference internal" href="../library/re.html#re.Match.end" title="re.Match.end"><code class="xref py py-meth docutils literal notranslate"><span class="pre">end()</span></code></a> return the starting and ending index of the match. <a class="reference internal" href="../library/re.html#re.Match.span" title="re.Match.span"><code class="xref py py-meth docutils literal notranslate"><span class="pre">span()</span></code></a>
  625. returns both start and end indexes in a single tuple. Since the <a class="reference internal" href="../library/re.html#re.Pattern.match" title="re.Pattern.match"><code class="xref py py-meth docutils literal notranslate"><span class="pre">match()</span></code></a>
  626. method only checks if the RE matches at the start of a string, <code class="xref py py-meth docutils literal notranslate"><span class="pre">start()</span></code>
  627. will always be zero. However, the <a class="reference internal" href="../library/re.html#re.Pattern.search" title="re.Pattern.search"><code class="xref py py-meth docutils literal notranslate"><span class="pre">search()</span></code></a> method of patterns
  628. scans through the string, so the match may not start at zero in that
  629. case.</p>
  630. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s1">&#39;::: message&#39;</span><span class="p">))</span>
  631. <span class="go">None</span>
  632. <span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;::: message&#39;</span><span class="p">);</span> <span class="nb">print</span><span class="p">(</span><span class="n">m</span><span class="p">)</span>
  633. <span class="go">&lt;re.Match object; span=(4, 11), match=&#39;message&#39;&gt;</span>
  634. <span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">()</span>
  635. <span class="go">&#39;message&#39;</span>
  636. <span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">span</span><span class="p">()</span>
  637. <span class="go">(4, 11)</span>
  638. </pre></div>
  639. </div>
  640. <p>In actual programs, the most common style is to store the
  641. <a class="reference internal" href="../library/re.html#match-objects"><span class="std std-ref">match object</span></a> in a variable, and then check if it was
  642. <code class="docutils literal notranslate"><span class="pre">None</span></code>. This usually looks like:</p>
  643. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></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="o">...</span> <span class="p">)</span>
  644. <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="s1">&#39;string goes here&#39;</span> <span class="p">)</span>
  645. <span class="k">if</span> <span class="n">m</span><span class="p">:</span>
  646. <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Match found: &#39;</span><span class="p">,</span> <span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">())</span>
  647. <span class="k">else</span><span class="p">:</span>
  648. <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;No match&#39;</span><span class="p">)</span>
  649. </pre></div>
  650. </div>
  651. <p>Two pattern methods return all of the matches for a pattern.
  652. <a class="reference internal" href="../library/re.html#re.Pattern.findall" title="re.Pattern.findall"><code class="xref py py-meth docutils literal notranslate"><span class="pre">findall()</span></code></a> returns a list of matching strings:</p>
  653. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;\d+&#39;</span><span class="p">)</span>
  654. <span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="s1">&#39;12 drummers drumming, 11 pipers piping, 10 lords a-leaping&#39;</span><span class="p">)</span>
  655. <span class="go">[&#39;12&#39;, &#39;11&#39;, &#39;10&#39;]</span>
  656. </pre></div>
  657. </div>
  658. <p>The <code class="docutils literal notranslate"><span class="pre">r</span></code> prefix, making the literal a raw string literal, is needed in this
  659. example because escape sequences in a normal “cooked” string literal that are
  660. not recognized by Python, as opposed to regular expressions, now result in a
  661. <a class="reference internal" href="../library/exceptions.html#DeprecationWarning" title="DeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DeprecationWarning</span></code></a> and will eventually become a <a class="reference internal" href="../library/exceptions.html#SyntaxError" title="SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a>. See
  662. <a class="reference internal" href="#the-backslash-plague"><span class="std std-ref">The Backslash Plague</span></a>.</p>
  663. <p><a class="reference internal" href="../library/re.html#re.Pattern.findall" title="re.Pattern.findall"><code class="xref py py-meth docutils literal notranslate"><span class="pre">findall()</span></code></a> has to create the entire list before it can be returned as the
  664. result. The <a class="reference internal" href="../library/re.html#re.Pattern.finditer" title="re.Pattern.finditer"><code class="xref py py-meth docutils literal notranslate"><span class="pre">finditer()</span></code></a> method returns a sequence of
  665. <a class="reference internal" href="../library/re.html#match-objects"><span class="std std-ref">match object</span></a> instances as an <a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a>:</p>
  666. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">iterator</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">finditer</span><span class="p">(</span><span class="s1">&#39;12 drummers drumming, 11 ... 10 ...&#39;</span><span class="p">)</span>
  667. <span class="gp">&gt;&gt;&gt; </span><span class="n">iterator</span>
  668. <span class="go">&lt;callable_iterator object at 0x...&gt;</span>
  669. <span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">match</span> <span class="ow">in</span> <span class="n">iterator</span><span class="p">:</span>
  670. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">match</span><span class="o">.</span><span class="n">span</span><span class="p">())</span>
  671. <span class="gp">...</span>
  672. <span class="go">(0, 2)</span>
  673. <span class="go">(22, 24)</span>
  674. <span class="go">(29, 31)</span>
  675. </pre></div>
  676. </div>
  677. </section>
  678. <section id="module-level-functions">
  679. <h3>Module-Level Functions<a class="headerlink" href="#module-level-functions" title="Link to this heading">¶</a></h3>
  680. <p>You don’t have to create a pattern object and call its methods; the
  681. <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module also provides top-level functions called <a class="reference internal" href="../library/re.html#re.match" title="re.match"><code class="xref py py-func docutils literal notranslate"><span class="pre">match()</span></code></a>,
  682. <a class="reference internal" href="../library/re.html#re.search" title="re.search"><code class="xref py py-func docutils literal notranslate"><span class="pre">search()</span></code></a>, <a class="reference internal" href="../library/re.html#re.findall" title="re.findall"><code class="xref py py-func docutils literal notranslate"><span class="pre">findall()</span></code></a>, <a class="reference internal" href="../library/re.html#re.sub" title="re.sub"><code class="xref py py-func docutils literal notranslate"><span class="pre">sub()</span></code></a>, and so forth. These functions
  683. take the same arguments as the corresponding pattern method with
  684. the RE string added as the first argument, and still return either <code class="docutils literal notranslate"><span class="pre">None</span></code> or a
  685. <a class="reference internal" href="../library/re.html#match-objects"><span class="std std-ref">match object</span></a> instance.</p>
  686. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;From\s+&#39;</span><span class="p">,</span> <span class="s1">&#39;Fromage amk&#39;</span><span class="p">))</span>
  687. <span class="go">None</span>
  688. <span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;From\s+&#39;</span><span class="p">,</span> <span class="s1">&#39;From amk Thu May 14 19:12:10 1998&#39;</span><span class="p">)</span>
  689. <span class="go">&lt;re.Match object; span=(0, 5), match=&#39;From &#39;&gt;</span>
  690. </pre></div>
  691. </div>
  692. <p>Under the hood, these functions simply create a pattern object for you
  693. and call the appropriate method on it. They also store the compiled
  694. object in a cache, so future calls using the same RE won’t need to
  695. parse the pattern again and again.</p>
  696. <p>Should you use these module-level functions, or should you get the
  697. pattern and call its methods yourself? If you’re accessing a regex
  698. within a loop, pre-compiling it will save a few function calls.
  699. Outside of loops, there’s not much difference thanks to the internal
  700. cache.</p>
  701. </section>
  702. <section id="compilation-flags">
  703. <h3>Compilation Flags<a class="headerlink" href="#compilation-flags" title="Link to this heading">¶</a></h3>
  704. <p>Compilation flags let you modify some aspects of how regular expressions work.
  705. Flags are available in the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module under two names, a long name such as
  706. <a class="reference internal" href="../library/re.html#re.IGNORECASE" title="re.IGNORECASE"><code class="xref py py-const docutils literal notranslate"><span class="pre">IGNORECASE</span></code></a> and a short, one-letter form such as <a class="reference internal" href="../library/re.html#re.I" title="re.I"><code class="xref py py-const docutils literal notranslate"><span class="pre">I</span></code></a>. (If you’re
  707. familiar with Perl’s pattern modifiers, the one-letter forms use the same
  708. letters; the short form of <a class="reference internal" href="../library/re.html#re.VERBOSE" title="re.VERBOSE"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.VERBOSE</span></code></a> is <a class="reference internal" href="../library/re.html#re.X" title="re.X"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.X</span></code></a>, for example.)
  709. Multiple flags can be specified by bitwise OR-ing them; <code class="docutils literal notranslate"><span class="pre">re.I</span> <span class="pre">|</span> <span class="pre">re.M</span></code> sets
  710. both the <a class="reference internal" href="../library/re.html#re.I" title="re.I"><code class="xref py py-const docutils literal notranslate"><span class="pre">I</span></code></a> and <a class="reference internal" href="../library/re.html#re.M" title="re.M"><code class="xref py py-const docutils literal notranslate"><span class="pre">M</span></code></a> flags, for example.</p>
  711. <p>Here’s a table of the available flags, followed by a more detailed explanation
  712. of each one.</p>
  713. <table class="docutils align-default">
  714. <thead>
  715. <tr class="row-odd"><th class="head"><p>Flag</p></th>
  716. <th class="head"><p>Meaning</p></th>
  717. </tr>
  718. </thead>
  719. <tbody>
  720. <tr class="row-even"><td><p><a class="reference internal" href="../library/re.html#re.ASCII" title="re.ASCII"><code class="xref py py-const docutils literal notranslate"><span class="pre">ASCII</span></code></a>, <a class="reference internal" href="../library/re.html#re.A" title="re.A"><code class="xref py py-const docutils literal notranslate"><span class="pre">A</span></code></a></p></td>
  721. <td><p>Makes several escapes like <code class="docutils literal notranslate"><span class="pre">\w</span></code>, <code class="docutils literal notranslate"><span class="pre">\b</span></code>,
  722. <code class="docutils literal notranslate"><span class="pre">\s</span></code> and <code class="docutils literal notranslate"><span class="pre">\d</span></code> match only on ASCII
  723. characters with the respective property.</p></td>
  724. </tr>
  725. <tr class="row-odd"><td><p><a class="reference internal" href="../library/re.html#re.DOTALL" title="re.DOTALL"><code class="xref py py-const docutils literal notranslate"><span class="pre">DOTALL</span></code></a>, <a class="reference internal" href="../library/re.html#re.S" title="re.S"><code class="xref py py-const docutils literal notranslate"><span class="pre">S</span></code></a></p></td>
  726. <td><p>Make <code class="docutils literal notranslate"><span class="pre">.</span></code> match any character, including
  727. newlines.</p></td>
  728. </tr>
  729. <tr class="row-even"><td><p><a class="reference internal" href="../library/re.html#re.IGNORECASE" title="re.IGNORECASE"><code class="xref py py-const docutils literal notranslate"><span class="pre">IGNORECASE</span></code></a>, <a class="reference internal" href="../library/re.html#re.I" title="re.I"><code class="xref py py-const docutils literal notranslate"><span class="pre">I</span></code></a></p></td>
  730. <td><p>Do case-insensitive matches.</p></td>
  731. </tr>
  732. <tr class="row-odd"><td><p><a class="reference internal" href="../library/re.html#re.LOCALE" title="re.LOCALE"><code class="xref py py-const docutils literal notranslate"><span class="pre">LOCALE</span></code></a>, <a class="reference internal" href="../library/re.html#re.L" title="re.L"><code class="xref py py-const docutils literal notranslate"><span class="pre">L</span></code></a></p></td>
  733. <td><p>Do a locale-aware match.</p></td>
  734. </tr>
  735. <tr class="row-even"><td><p><a class="reference internal" href="../library/re.html#re.MULTILINE" title="re.MULTILINE"><code class="xref py py-const docutils literal notranslate"><span class="pre">MULTILINE</span></code></a>, <a class="reference internal" href="../library/re.html#re.M" title="re.M"><code class="xref py py-const docutils literal notranslate"><span class="pre">M</span></code></a></p></td>
  736. <td><p>Multi-line matching, affecting <code class="docutils literal notranslate"><span class="pre">^</span></code> and
  737. <code class="docutils literal notranslate"><span class="pre">$</span></code>.</p></td>
  738. </tr>
  739. <tr class="row-odd"><td><p><a class="reference internal" href="../library/re.html#re.VERBOSE" title="re.VERBOSE"><code class="xref py py-const docutils literal notranslate"><span class="pre">VERBOSE</span></code></a>, <a class="reference internal" href="../library/re.html#re.X" title="re.X"><code class="xref py py-const docutils literal notranslate"><span class="pre">X</span></code></a>
  740. (for ‘extended’)</p></td>
  741. <td><p>Enable verbose REs, which can be organized
  742. more cleanly and understandably.</p></td>
  743. </tr>
  744. </tbody>
  745. </table>
  746. <dl class="py data">
  747. <dt class="sig sig-object py">
  748. <span class="sig-prename descclassname"><span class="pre">re.</span></span><span class="sig-name descname"><span class="pre">I</span></span></dt>
  749. <dt class="sig sig-object py">
  750. <span class="sig-prename descclassname"><span class="pre">re.</span></span><span class="sig-name descname"><span class="pre">IGNORECASE</span></span></dt>
  751. <dd><p>Perform case-insensitive matching; character class and literal strings will
  752. match letters by ignoring case. For example, <code class="docutils literal notranslate"><span class="pre">[A-Z]</span></code> will match lowercase
  753. letters, too. Full Unicode matching also works unless the <a class="reference internal" href="../library/re.html#re.ASCII" title="re.ASCII"><code class="xref py py-const docutils literal notranslate"><span class="pre">ASCII</span></code></a>
  754. flag is used to disable non-ASCII matches. When the Unicode patterns
  755. <code class="docutils literal notranslate"><span class="pre">[a-z]</span></code> or <code class="docutils literal notranslate"><span class="pre">[A-Z]</span></code> are used in combination with the <a class="reference internal" href="../library/re.html#re.IGNORECASE" title="re.IGNORECASE"><code class="xref py py-const docutils literal notranslate"><span class="pre">IGNORECASE</span></code></a>
  756. flag, they will match the 52 ASCII letters and 4 additional non-ASCII
  757. letters: ‘İ’ (U+0130, Latin capital letter I with dot above), ‘ı’ (U+0131,
  758. Latin small letter dotless i), ‘ſ’ (U+017F, Latin small letter long s) and
  759. ‘K’ (U+212A, Kelvin sign). <code class="docutils literal notranslate"><span class="pre">Spam</span></code> will match <code class="docutils literal notranslate"><span class="pre">'Spam'</span></code>, <code class="docutils literal notranslate"><span class="pre">'spam'</span></code>,
  760. <code class="docutils literal notranslate"><span class="pre">'spAM'</span></code>, or <code class="docutils literal notranslate"><span class="pre">'ſpam'</span></code> (the latter is matched only in Unicode mode).
  761. This lowercasing doesn’t take the current locale into account;
  762. it will if you also set the <a class="reference internal" href="../library/re.html#re.LOCALE" title="re.LOCALE"><code class="xref py py-const docutils literal notranslate"><span class="pre">LOCALE</span></code></a> flag.</p>
  763. </dd></dl>
  764. <dl class="py data">
  765. <dt class="sig sig-object py">
  766. <span class="sig-prename descclassname"><span class="pre">re.</span></span><span class="sig-name descname"><span class="pre">L</span></span></dt>
  767. <dt class="sig sig-object py">
  768. <span class="sig-prename descclassname"><span class="pre">re.</span></span><span class="sig-name descname"><span class="pre">LOCALE</span></span></dt>
  769. <dd><p>Make <code class="docutils literal notranslate"><span class="pre">\w</span></code>, <code class="docutils literal notranslate"><span class="pre">\W</span></code>, <code class="docutils literal notranslate"><span class="pre">\b</span></code>, <code class="docutils literal notranslate"><span class="pre">\B</span></code> and case-insensitive matching dependent
  770. on the current locale instead of the Unicode database.</p>
  771. <p>Locales are a feature of the C library intended to help in writing programs
  772. that take account of language differences. For example, if you’re
  773. processing encoded French text, you’d want to be able to write <code class="docutils literal notranslate"><span class="pre">\w+</span></code> to
  774. match words, but <code class="docutils literal notranslate"><span class="pre">\w</span></code> only matches the character class <code class="docutils literal notranslate"><span class="pre">[A-Za-z]</span></code> in
  775. bytes patterns; it won’t match bytes corresponding to <code class="docutils literal notranslate"><span class="pre">é</span></code> or <code class="docutils literal notranslate"><span class="pre">ç</span></code>.
  776. If your system is configured properly and a French locale is selected,
  777. certain C functions will tell the program that the byte corresponding to
  778. <code class="docutils literal notranslate"><span class="pre">é</span></code> should also be considered a letter.
  779. Setting the <a class="reference internal" href="../library/re.html#re.LOCALE" title="re.LOCALE"><code class="xref py py-const docutils literal notranslate"><span class="pre">LOCALE</span></code></a> flag when compiling a regular expression will cause
  780. the resulting compiled object to use these C functions for <code class="docutils literal notranslate"><span class="pre">\w</span></code>; this is
  781. slower, but also enables <code class="docutils literal notranslate"><span class="pre">\w+</span></code> to match French words as you’d expect.
  782. The use of this flag is discouraged in Python 3 as the locale mechanism
  783. is very unreliable, it only handles one “culture” at a time, and it only
  784. works with 8-bit locales. Unicode matching is already enabled by default
  785. in Python 3 for Unicode (str) patterns, and it is able to handle different
  786. locales/languages.</p>
  787. </dd></dl>
  788. <dl class="py data">
  789. <dt class="sig sig-object py">
  790. <span class="sig-prename descclassname"><span class="pre">re.</span></span><span class="sig-name descname"><span class="pre">M</span></span></dt>
  791. <dt class="sig sig-object py">
  792. <span class="sig-prename descclassname"><span class="pre">re.</span></span><span class="sig-name descname"><span class="pre">MULTILINE</span></span></dt>
  793. <dd><p>(<code class="docutils literal notranslate"><span class="pre">^</span></code> and <code class="docutils literal notranslate"><span class="pre">$</span></code> haven’t been explained yet; they’ll be introduced in section
  794. <a class="reference internal" href="#more-metacharacters"><span class="std std-ref">More Metacharacters</span></a>.)</p>
  795. <p>Usually <code class="docutils literal notranslate"><span class="pre">^</span></code> matches only at the beginning of the string, and <code class="docutils literal notranslate"><span class="pre">$</span></code> matches
  796. only at the end of the string and immediately before the newline (if any) at the
  797. end of the string. When this flag is specified, <code class="docutils literal notranslate"><span class="pre">^</span></code> matches at the beginning
  798. of the string and at the beginning of each line within the string, immediately
  799. following each newline. Similarly, the <code class="docutils literal notranslate"><span class="pre">$</span></code> metacharacter matches either at
  800. the end of the string and at the end of each line (immediately preceding each
  801. newline).</p>
  802. </dd></dl>
  803. <dl class="py data">
  804. <dt class="sig sig-object py">
  805. <span class="sig-prename descclassname"><span class="pre">re.</span></span><span class="sig-name descname"><span class="pre">S</span></span></dt>
  806. <dt class="sig sig-object py">
  807. <span class="sig-prename descclassname"><span class="pre">re.</span></span><span class="sig-name descname"><span class="pre">DOTALL</span></span></dt>
  808. <dd><p>Makes the <code class="docutils literal notranslate"><span class="pre">'.'</span></code> special character match any character at all, including a
  809. newline; without this flag, <code class="docutils literal notranslate"><span class="pre">'.'</span></code> will match anything <em>except</em> a newline.</p>
  810. </dd></dl>
  811. <dl class="py data">
  812. <dt class="sig sig-object py">
  813. <span class="sig-prename descclassname"><span class="pre">re.</span></span><span class="sig-name descname"><span class="pre">A</span></span></dt>
  814. <dt class="sig sig-object py">
  815. <span class="sig-prename descclassname"><span class="pre">re.</span></span><span class="sig-name descname"><span class="pre">ASCII</span></span></dt>
  816. <dd><p>Make <code class="docutils literal notranslate"><span class="pre">\w</span></code>, <code class="docutils literal notranslate"><span class="pre">\W</span></code>, <code class="docutils literal notranslate"><span class="pre">\b</span></code>, <code class="docutils literal notranslate"><span class="pre">\B</span></code>, <code class="docutils literal notranslate"><span class="pre">\s</span></code> and <code class="docutils literal notranslate"><span class="pre">\S</span></code> perform ASCII-only
  817. matching instead of full Unicode matching. This is only meaningful for
  818. Unicode patterns, and is ignored for byte patterns.</p>
  819. </dd></dl>
  820. <dl class="py data">
  821. <dt class="sig sig-object py">
  822. <span class="sig-prename descclassname"><span class="pre">re.</span></span><span class="sig-name descname"><span class="pre">X</span></span></dt>
  823. <dt class="sig sig-object py">
  824. <span class="sig-prename descclassname"><span class="pre">re.</span></span><span class="sig-name descname"><span class="pre">VERBOSE</span></span></dt>
  825. <dd><p>This flag allows you to write regular expressions that are more readable by
  826. granting you more flexibility in how you can format them. When this flag has
  827. been specified, whitespace within the RE string is ignored, except when the
  828. whitespace is in a character class or preceded by an unescaped backslash; this
  829. lets you organize and indent the RE more clearly. This flag also lets you put
  830. comments within a RE that will be ignored by the engine; comments are marked by
  831. a <code class="docutils literal notranslate"><span class="pre">'#'</span></code> that’s neither in a character class or preceded by an unescaped
  832. backslash.</p>
  833. <p>For example, here’s a RE that uses <a class="reference internal" href="../library/re.html#re.VERBOSE" title="re.VERBOSE"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.VERBOSE</span></code></a>; see how much easier it
  834. is to read?</p>
  835. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></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="sa">r</span><span class="s2">&quot;&quot;&quot;</span>
  836. <span class="s2"> &amp;[#] # Start of a numeric entity reference</span>
  837. <span class="s2"> (</span>
  838. <span class="s2"> 0[0-7]+ # Octal form</span>
  839. <span class="s2"> | [0-9]+ # Decimal form</span>
  840. <span class="s2"> | x[0-9a-fA-F]+ # Hexadecimal form</span>
  841. <span class="s2"> )</span>
  842. <span class="s2"> ; # Trailing semicolon</span>
  843. <span class="s2">&quot;&quot;&quot;</span><span class="p">,</span> <span class="n">re</span><span class="o">.</span><span class="n">VERBOSE</span><span class="p">)</span>
  844. </pre></div>
  845. </div>
  846. <p>Without the verbose setting, the RE would look like this:</p>
  847. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></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="s2">&quot;&amp;#(0[0-7]+&quot;</span>
  848. <span class="s2">&quot;|[0-9]+&quot;</span>
  849. <span class="s2">&quot;|x[0-9a-fA-F]+);&quot;</span><span class="p">)</span>
  850. </pre></div>
  851. </div>
  852. <p>In the above example, Python’s automatic concatenation of string literals has
  853. been used to break up the RE into smaller pieces, but it’s still more difficult
  854. to understand than the version using <a class="reference internal" href="../library/re.html#re.VERBOSE" title="re.VERBOSE"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.VERBOSE</span></code></a>.</p>
  855. </dd></dl>
  856. </section>
  857. </section>
  858. <section id="more-pattern-power">
  859. <h2>More Pattern Power<a class="headerlink" href="#more-pattern-power" title="Link to this heading">¶</a></h2>
  860. <p>So far we’ve only covered a part of the features of regular expressions. In
  861. this section, we’ll cover some new metacharacters, and how to use groups to
  862. retrieve portions of the text that was matched.</p>
  863. <section id="more-metacharacters">
  864. <span id="id2"></span><h3>More Metacharacters<a class="headerlink" href="#more-metacharacters" title="Link to this heading">¶</a></h3>
  865. <p>There are some metacharacters that we haven’t covered yet. Most of them will be
  866. covered in this section.</p>
  867. <p>Some of the remaining metacharacters to be discussed are <em class="dfn">zero-width
  868. assertions</em>. They don’t cause the engine to advance through the string;
  869. instead, they consume no characters at all, and simply succeed or fail. For
  870. example, <code class="docutils literal notranslate"><span class="pre">\b</span></code> is an assertion that the current position is located at a word
  871. boundary; the position isn’t changed by the <code class="docutils literal notranslate"><span class="pre">\b</span></code> at all. This means that
  872. zero-width assertions should never be repeated, because if they match once at a
  873. given location, they can obviously be matched an infinite number of times.</p>
  874. <dl>
  875. <dt><code class="docutils literal notranslate"><span class="pre">|</span></code></dt><dd><p>Alternation, or the “or” operator. If <em>A</em> and <em>B</em> are regular expressions,
  876. <code class="docutils literal notranslate"><span class="pre">A|B</span></code> will match any string that matches either <em>A</em> or <em>B</em>. <code class="docutils literal notranslate"><span class="pre">|</span></code> has very
  877. low precedence in order to make it work reasonably when you’re alternating
  878. multi-character strings. <code class="docutils literal notranslate"><span class="pre">Crow|Servo</span></code> will match either <code class="docutils literal notranslate"><span class="pre">'Crow'</span></code> or <code class="docutils literal notranslate"><span class="pre">'Servo'</span></code>,
  879. not <code class="docutils literal notranslate"><span class="pre">'Cro'</span></code>, a <code class="docutils literal notranslate"><span class="pre">'w'</span></code> or an <code class="docutils literal notranslate"><span class="pre">'S'</span></code>, and <code class="docutils literal notranslate"><span class="pre">'ervo'</span></code>.</p>
  880. <p>To match a literal <code class="docutils literal notranslate"><span class="pre">'|'</span></code>, use <code class="docutils literal notranslate"><span class="pre">\|</span></code>, or enclose it inside a character class,
  881. as in <code class="docutils literal notranslate"><span class="pre">[|]</span></code>.</p>
  882. </dd>
  883. <dt><code class="docutils literal notranslate"><span class="pre">^</span></code></dt><dd><p>Matches at the beginning of lines. Unless the <a class="reference internal" href="../library/re.html#re.MULTILINE" title="re.MULTILINE"><code class="xref py py-const docutils literal notranslate"><span class="pre">MULTILINE</span></code></a> flag has been
  884. set, this will only match at the beginning of the string. In <a class="reference internal" href="../library/re.html#re.MULTILINE" title="re.MULTILINE"><code class="xref py py-const docutils literal notranslate"><span class="pre">MULTILINE</span></code></a>
  885. mode, this also matches immediately after each newline within the string.</p>
  886. <p>For example, if you wish to match the word <code class="docutils literal notranslate"><span class="pre">From</span></code> only at the beginning of a
  887. line, the RE to use is <code class="docutils literal notranslate"><span class="pre">^From</span></code>.</p>
  888. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;^From&#39;</span><span class="p">,</span> <span class="s1">&#39;From Here to Eternity&#39;</span><span class="p">))</span>
  889. <span class="go">&lt;re.Match object; span=(0, 4), match=&#39;From&#39;&gt;</span>
  890. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;^From&#39;</span><span class="p">,</span> <span class="s1">&#39;Reciting From Memory&#39;</span><span class="p">))</span>
  891. <span class="go">None</span>
  892. </pre></div>
  893. </div>
  894. <p>To match a literal <code class="docutils literal notranslate"><span class="pre">'^'</span></code>, use <code class="docutils literal notranslate"><span class="pre">\^</span></code>.</p>
  895. </dd>
  896. <dt><code class="docutils literal notranslate"><span class="pre">$</span></code></dt><dd><p>Matches at the end of a line, which is defined as either the end of the string,
  897. or any location followed by a newline character.</p>
  898. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;}$&#39;</span><span class="p">,</span> <span class="s1">&#39;</span><span class="si">{block}</span><span class="s1">&#39;</span><span class="p">))</span>
  899. <span class="go">&lt;re.Match object; span=(6, 7), match=&#39;}&#39;&gt;</span>
  900. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;}$&#39;</span><span class="p">,</span> <span class="s1">&#39;</span><span class="si">{block}</span><span class="s1"> &#39;</span><span class="p">))</span>
  901. <span class="go">None</span>
  902. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;}$&#39;</span><span class="p">,</span> <span class="s1">&#39;</span><span class="si">{block}</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">))</span>
  903. <span class="go">&lt;re.Match object; span=(6, 7), match=&#39;}&#39;&gt;</span>
  904. </pre></div>
  905. </div>
  906. <p>To match a literal <code class="docutils literal notranslate"><span class="pre">'$'</span></code>, use <code class="docutils literal notranslate"><span class="pre">\$</span></code> or enclose it inside a character class,
  907. as in <code class="docutils literal notranslate"><span class="pre">[$]</span></code>.</p>
  908. </dd>
  909. <dt><code class="docutils literal notranslate"><span class="pre">\A</span></code></dt><dd><p>Matches only at the start of the string. When not in <a class="reference internal" href="../library/re.html#re.MULTILINE" title="re.MULTILINE"><code class="xref py py-const docutils literal notranslate"><span class="pre">MULTILINE</span></code></a> mode,
  910. <code class="docutils literal notranslate"><span class="pre">\A</span></code> and <code class="docutils literal notranslate"><span class="pre">^</span></code> are effectively the same. In <a class="reference internal" href="../library/re.html#re.MULTILINE" title="re.MULTILINE"><code class="xref py py-const docutils literal notranslate"><span class="pre">MULTILINE</span></code></a> mode, they’re
  911. different: <code class="docutils literal notranslate"><span class="pre">\A</span></code> still matches only at the beginning of the string, but <code class="docutils literal notranslate"><span class="pre">^</span></code>
  912. may match at any location inside the string that follows a newline character.</p>
  913. </dd>
  914. <dt><code class="docutils literal notranslate"><span class="pre">\Z</span></code></dt><dd><p>Matches only at the end of the string.</p>
  915. </dd>
  916. <dt><code class="docutils literal notranslate"><span class="pre">\b</span></code></dt><dd><p>Word boundary. This is a zero-width assertion that matches only at the
  917. beginning or end of a word. A word is defined as a sequence of alphanumeric
  918. characters, so the end of a word is indicated by whitespace or a
  919. non-alphanumeric character.</p>
  920. <p>The following example matches <code class="docutils literal notranslate"><span class="pre">class</span></code> only when it’s a complete word; it won’t
  921. match when it’s contained inside another word.</p>
  922. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;\bclass\b&#39;</span><span class="p">)</span>
  923. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;no class at all&#39;</span><span class="p">))</span>
  924. <span class="go">&lt;re.Match object; span=(3, 8), match=&#39;class&#39;&gt;</span>
  925. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;the declassified algorithm&#39;</span><span class="p">))</span>
  926. <span class="go">None</span>
  927. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;one subclass is&#39;</span><span class="p">))</span>
  928. <span class="go">None</span>
  929. </pre></div>
  930. </div>
  931. <p>There are two subtleties you should remember when using this special sequence.
  932. First, this is the worst collision between Python’s string literals and regular
  933. expression sequences. In Python’s string literals, <code class="docutils literal notranslate"><span class="pre">\b</span></code> is the backspace
  934. character, ASCII value 8. If you’re not using raw strings, then Python will
  935. convert the <code class="docutils literal notranslate"><span class="pre">\b</span></code> to a backspace, and your RE won’t match as you expect it to.
  936. The following example looks the same as our previous RE, but omits the <code class="docutils literal notranslate"><span class="pre">'r'</span></code>
  937. in front of the RE string.</p>
  938. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">&#39;</span><span class="se">\b</span><span class="s1">class</span><span class="se">\b</span><span class="s1">&#39;</span><span class="p">)</span>
  939. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;no class at all&#39;</span><span class="p">))</span>
  940. <span class="go">None</span>
  941. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;</span><span class="se">\b</span><span class="s1">&#39;</span> <span class="o">+</span> <span class="s1">&#39;class&#39;</span> <span class="o">+</span> <span class="s1">&#39;</span><span class="se">\b</span><span class="s1">&#39;</span><span class="p">))</span>
  942. <span class="go">&lt;re.Match object; span=(0, 7), match=&#39;\x08class\x08&#39;&gt;</span>
  943. </pre></div>
  944. </div>
  945. <p>Second, inside a character class, where there’s no use for this assertion,
  946. <code class="docutils literal notranslate"><span class="pre">\b</span></code> represents the backspace character, for compatibility with Python’s
  947. string literals.</p>
  948. </dd>
  949. <dt><code class="docutils literal notranslate"><span class="pre">\B</span></code></dt><dd><p>Another zero-width assertion, this is the opposite of <code class="docutils literal notranslate"><span class="pre">\b</span></code>, only matching when
  950. the current position is not at a word boundary.</p>
  951. </dd>
  952. </dl>
  953. </section>
  954. <section id="grouping">
  955. <h3>Grouping<a class="headerlink" href="#grouping" title="Link to this heading">¶</a></h3>
  956. <p>Frequently you need to obtain more information than just whether the RE matched
  957. or not. Regular expressions are often used to dissect strings by writing a RE
  958. divided into several subgroups which match different components of interest.
  959. For example, an RFC-822 header line is divided into a header name and a value,
  960. separated by a <code class="docutils literal notranslate"><span class="pre">':'</span></code>, like this:</p>
  961. <div class="highlight-none notranslate"><div class="highlight"><pre><span></span>From: author@example.com
  962. User-Agent: Thunderbird 1.5.0.9 (X11/20061227)
  963. MIME-Version: 1.0
  964. To: editor@example.com
  965. </pre></div>
  966. </div>
  967. <p>This can be handled by writing a regular expression which matches an entire
  968. header line, and has one group which matches the header name, and another group
  969. which matches the header’s value.</p>
  970. <p>Groups are marked by the <code class="docutils literal notranslate"><span class="pre">'('</span></code>, <code class="docutils literal notranslate"><span class="pre">')'</span></code> metacharacters. <code class="docutils literal notranslate"><span class="pre">'('</span></code> and <code class="docutils literal notranslate"><span class="pre">')'</span></code>
  971. have much the same meaning as they do in mathematical expressions; they group
  972. together the expressions contained inside them, and you can repeat the contents
  973. of a group with a quantifier, such as <code class="docutils literal notranslate"><span class="pre">*</span></code>, <code class="docutils literal notranslate"><span class="pre">+</span></code>, <code class="docutils literal notranslate"><span class="pre">?</span></code>, or
  974. <code class="docutils literal notranslate"><span class="pre">{m,n}</span></code>. For example, <code class="docutils literal notranslate"><span class="pre">(ab)*</span></code> will match zero or more repetitions of
  975. <code class="docutils literal notranslate"><span class="pre">ab</span></code>.</p>
  976. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">&#39;(ab)*&#39;</span><span class="p">)</span>
  977. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s1">&#39;ababababab&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">span</span><span class="p">())</span>
  978. <span class="go">(0, 10)</span>
  979. </pre></div>
  980. </div>
  981. <p>Groups indicated with <code class="docutils literal notranslate"><span class="pre">'('</span></code>, <code class="docutils literal notranslate"><span class="pre">')'</span></code> also capture the starting and ending
  982. index of the text that they match; this can be retrieved by passing an argument
  983. to <a class="reference internal" href="../library/re.html#re.Match.group" title="re.Match.group"><code class="xref py py-meth docutils literal notranslate"><span class="pre">group()</span></code></a>, <a class="reference internal" href="../library/re.html#re.Match.start" title="re.Match.start"><code class="xref py py-meth docutils literal notranslate"><span class="pre">start()</span></code></a>, <a class="reference internal" href="../library/re.html#re.Match.end" title="re.Match.end"><code class="xref py py-meth docutils literal notranslate"><span class="pre">end()</span></code></a>, and
  984. <a class="reference internal" href="../library/re.html#re.Match.span" title="re.Match.span"><code class="xref py py-meth docutils literal notranslate"><span class="pre">span()</span></code></a>. Groups are
  985. numbered starting with 0. Group 0 is always present; it’s the whole RE, so
  986. <a class="reference internal" href="../library/re.html#match-objects"><span class="std std-ref">match object</span></a> methods all have group 0 as their default
  987. argument. Later we’ll see how to express groups that don’t capture the span
  988. of text that they match.</p>
  989. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">&#39;(a)b&#39;</span><span class="p">)</span>
  990. <span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s1">&#39;ab&#39;</span><span class="p">)</span>
  991. <span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">()</span>
  992. <span class="go">&#39;ab&#39;</span>
  993. <span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
  994. <span class="go">&#39;ab&#39;</span>
  995. </pre></div>
  996. </div>
  997. <p>Subgroups are numbered from left to right, from 1 upward. Groups can be nested;
  998. to determine the number, just count the opening parenthesis characters, going
  999. from left to right.</p>
  1000. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">&#39;(a(b)c)d&#39;</span><span class="p">)</span>
  1001. <span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s1">&#39;abcd&#39;</span><span class="p">)</span>
  1002. <span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
  1003. <span class="go">&#39;abcd&#39;</span>
  1004. <span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
  1005. <span class="go">&#39;abc&#39;</span>
  1006. <span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>
  1007. <span class="go">&#39;b&#39;</span>
  1008. </pre></div>
  1009. </div>
  1010. <p><a class="reference internal" href="../library/re.html#re.Match.group" title="re.Match.group"><code class="xref py py-meth docutils literal notranslate"><span class="pre">group()</span></code></a> can be passed multiple group numbers at a time, in which case it
  1011. will return a tuple containing the corresponding values for those groups.</p>
  1012. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">)</span>
  1013. <span class="go">(&#39;b&#39;, &#39;abc&#39;, &#39;b&#39;)</span>
  1014. </pre></div>
  1015. </div>
  1016. <p>The <a class="reference internal" href="../library/re.html#re.Match.groups" title="re.Match.groups"><code class="xref py py-meth docutils literal notranslate"><span class="pre">groups()</span></code></a> method returns a tuple containing the strings for all the
  1017. subgroups, from 1 up to however many there are.</p>
  1018. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">groups</span><span class="p">()</span>
  1019. <span class="go">(&#39;abc&#39;, &#39;b&#39;)</span>
  1020. </pre></div>
  1021. </div>
  1022. <p>Backreferences in a pattern allow you to specify that the contents of an earlier
  1023. capturing group must also be found at the current location in the string. For
  1024. example, <code class="docutils literal notranslate"><span class="pre">\1</span></code> will succeed if the exact contents of group 1 can be found at
  1025. the current position, and fails otherwise. Remember that Python’s string
  1026. literals also use a backslash followed by numbers to allow including arbitrary
  1027. characters in a string, so be sure to use a raw string when incorporating
  1028. backreferences in a RE.</p>
  1029. <p>For example, the following RE detects doubled words in a string.</p>
  1030. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;\b(\w+)\s+\1\b&#39;</span><span class="p">)</span>
  1031. <span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;Paris in the the spring&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">group</span><span class="p">()</span>
  1032. <span class="go">&#39;the the&#39;</span>
  1033. </pre></div>
  1034. </div>
  1035. <p>Backreferences like this aren’t often useful for just searching through a string
  1036. — there are few text formats which repeat data in this way — but you’ll soon
  1037. find out that they’re <em>very</em> useful when performing string substitutions.</p>
  1038. </section>
  1039. <section id="non-capturing-and-named-groups">
  1040. <h3>Non-capturing and Named Groups<a class="headerlink" href="#non-capturing-and-named-groups" title="Link to this heading">¶</a></h3>
  1041. <p>Elaborate REs may use many groups, both to capture substrings of interest, and
  1042. to group and structure the RE itself. In complex REs, it becomes difficult to
  1043. keep track of the group numbers. There are two features which help with this
  1044. problem. Both of them use a common syntax for regular expression extensions, so
  1045. we’ll look at that first.</p>
  1046. <p>Perl 5 is well known for its powerful additions to standard regular expressions.
  1047. For these new features the Perl developers couldn’t choose new single-keystroke metacharacters
  1048. or new special sequences beginning with <code class="docutils literal notranslate"><span class="pre">\</span></code> without making Perl’s regular
  1049. expressions confusingly different from standard REs. If they chose <code class="docutils literal notranslate"><span class="pre">&amp;</span></code> as a
  1050. new metacharacter, for example, old expressions would be assuming that <code class="docutils literal notranslate"><span class="pre">&amp;</span></code> was
  1051. a regular character and wouldn’t have escaped it by writing <code class="docutils literal notranslate"><span class="pre">\&amp;</span></code> or <code class="docutils literal notranslate"><span class="pre">[&amp;]</span></code>.</p>
  1052. <p>The solution chosen by the Perl developers was to use <code class="docutils literal notranslate"><span class="pre">(?...)</span></code> as the
  1053. extension syntax. <code class="docutils literal notranslate"><span class="pre">?</span></code> immediately after a parenthesis was a syntax error
  1054. because the <code class="docutils literal notranslate"><span class="pre">?</span></code> would have nothing to repeat, so this didn’t introduce any
  1055. compatibility problems. The characters immediately after the <code class="docutils literal notranslate"><span class="pre">?</span></code> indicate
  1056. what extension is being used, so <code class="docutils literal notranslate"><span class="pre">(?=foo)</span></code> is one thing (a positive lookahead
  1057. assertion) and <code class="docutils literal notranslate"><span class="pre">(?:foo)</span></code> is something else (a non-capturing group containing
  1058. the subexpression <code class="docutils literal notranslate"><span class="pre">foo</span></code>).</p>
  1059. <p>Python supports several of Perl’s extensions and adds an extension
  1060. syntax to Perl’s extension syntax. If the first character after the
  1061. question mark is a <code class="docutils literal notranslate"><span class="pre">P</span></code>, you know that it’s an extension that’s
  1062. specific to Python.</p>
  1063. <p>Now that we’ve looked at the general extension syntax, we can return
  1064. to the features that simplify working with groups in complex REs.</p>
  1065. <p>Sometimes you’ll want to use a group to denote a part of a regular expression,
  1066. but aren’t interested in retrieving the group’s contents. You can make this fact
  1067. explicit by using a non-capturing group: <code class="docutils literal notranslate"><span class="pre">(?:...)</span></code>, where you can replace the
  1068. <code class="docutils literal notranslate"><span class="pre">...</span></code> with any other regular expression.</p>
  1069. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;([abc])+&quot;</span><span class="p">,</span> <span class="s2">&quot;abc&quot;</span><span class="p">)</span>
  1070. <span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">groups</span><span class="p">()</span>
  1071. <span class="go">(&#39;c&#39;,)</span>
  1072. <span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;(?:[abc])+&quot;</span><span class="p">,</span> <span class="s2">&quot;abc&quot;</span><span class="p">)</span>
  1073. <span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">groups</span><span class="p">()</span>
  1074. <span class="go">()</span>
  1075. </pre></div>
  1076. </div>
  1077. <p>Except for the fact that you can’t retrieve the contents of what the group
  1078. matched, a non-capturing group behaves exactly the same as a capturing group;
  1079. you can put anything inside it, repeat it with a repetition metacharacter such
  1080. as <code class="docutils literal notranslate"><span class="pre">*</span></code>, and nest it within other groups (capturing or non-capturing).
  1081. <code class="docutils literal notranslate"><span class="pre">(?:...)</span></code> is particularly useful when modifying an existing pattern, since you
  1082. can add new groups without changing how all the other groups are numbered. It
  1083. should be mentioned that there’s no performance difference in searching between
  1084. capturing and non-capturing groups; neither form is any faster than the other.</p>
  1085. <p>A more significant feature is named groups: instead of referring to them by
  1086. numbers, groups can be referenced by a name.</p>
  1087. <p>The syntax for a named group is one of the Python-specific extensions:
  1088. <code class="docutils literal notranslate"><span class="pre">(?P&lt;name&gt;...)</span></code>. <em>name</em> is, obviously, the name of the group. Named groups
  1089. behave exactly like capturing groups, and additionally associate a name
  1090. with a group. The <a class="reference internal" href="../library/re.html#match-objects"><span class="std std-ref">match object</span></a> methods that deal with
  1091. capturing groups all accept either integers that refer to the group by number
  1092. or strings that contain the desired group’s name. Named groups are still
  1093. given numbers, so you can retrieve information about a group in two ways:</p>
  1094. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;(?P&lt;word&gt;\b\w+\b)&#39;</span><span class="p">)</span>
  1095. <span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">search</span><span class="p">(</span> <span class="s1">&#39;(((( Lots of punctuation )))&#39;</span> <span class="p">)</span>
  1096. <span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="s1">&#39;word&#39;</span><span class="p">)</span>
  1097. <span class="go">&#39;Lots&#39;</span>
  1098. <span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
  1099. <span class="go">&#39;Lots&#39;</span>
  1100. </pre></div>
  1101. </div>
  1102. <p>Additionally, you can retrieve named groups as a dictionary with
  1103. <a class="reference internal" href="../library/re.html#re.Match.groupdict" title="re.Match.groupdict"><code class="xref py py-meth docutils literal notranslate"><span class="pre">groupdict()</span></code></a>:</p>
  1104. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;(?P&lt;first&gt;\w+) (?P&lt;last&gt;\w+)&#39;</span><span class="p">,</span> <span class="s1">&#39;Jane Doe&#39;</span><span class="p">)</span>
  1105. <span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">groupdict</span><span class="p">()</span>
  1106. <span class="go">{&#39;first&#39;: &#39;Jane&#39;, &#39;last&#39;: &#39;Doe&#39;}</span>
  1107. </pre></div>
  1108. </div>
  1109. <p>Named groups are handy because they let you use easily remembered names, instead
  1110. 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)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">imaplib</span></code></a>
  1111. module:</p>
  1112. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><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="sa">r</span><span class="s1">&#39;INTERNALDATE &quot;&#39;</span>
  1113. <span class="sa">r</span><span class="s1">&#39;(?P&lt;day&gt;[ 123][0-9])-(?P&lt;mon&gt;[A-Z][a-z][a-z])-&#39;</span>
  1114. <span class="sa">r</span><span class="s1">&#39;(?P&lt;year&gt;[0-9][0-9][0-9][0-9])&#39;</span>
  1115. <span class="sa">r</span><span class="s1">&#39; (?P&lt;hour&gt;[0-9][0-9]):(?P&lt;min&gt;[0-9][0-9]):(?P&lt;sec&gt;[0-9][0-9])&#39;</span>
  1116. <span class="sa">r</span><span class="s1">&#39; (?P&lt;zonen&gt;[-+])(?P&lt;zoneh&gt;[0-9][0-9])(?P&lt;zonem&gt;[0-9][0-9])&#39;</span>
  1117. <span class="sa">r</span><span class="s1">&#39;&quot;&#39;</span><span class="p">)</span>
  1118. </pre></div>
  1119. </div>
  1120. <p>It’s obviously much easier to retrieve <code class="docutils literal notranslate"><span class="pre">m.group('zonem')</span></code>, instead of having
  1121. to remember to retrieve group 9.</p>
  1122. <p>The syntax for backreferences in an expression such as <code class="docutils literal notranslate"><span class="pre">(...)\1</span></code> refers to the
  1123. number of the group. There’s naturally a variant that uses the group name
  1124. instead of the number. This is another Python extension: <code class="docutils literal notranslate"><span class="pre">(?P=name)</span></code> indicates
  1125. that the contents of the group called <em>name</em> should again be matched at the
  1126. current point. The regular expression for finding doubled words,
  1127. <code class="docutils literal notranslate"><span class="pre">\b(\w+)\s+\1\b</span></code> can also be written as <code class="docutils literal notranslate"><span class="pre">\b(?P&lt;word&gt;\w+)\s+(?P=word)\b</span></code>:</p>
  1128. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;\b(?P&lt;word&gt;\w+)\s+(?P=word)\b&#39;</span><span class="p">)</span>
  1129. <span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;Paris in the the spring&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">group</span><span class="p">()</span>
  1130. <span class="go">&#39;the the&#39;</span>
  1131. </pre></div>
  1132. </div>
  1133. </section>
  1134. <section id="lookahead-assertions">
  1135. <h3>Lookahead Assertions<a class="headerlink" href="#lookahead-assertions" title="Link to this heading">¶</a></h3>
  1136. <p>Another zero-width assertion is the lookahead assertion. Lookahead assertions
  1137. are available in both positive and negative form, and look like this:</p>
  1138. <dl class="simple">
  1139. <dt><code class="docutils literal notranslate"><span class="pre">(?=...)</span></code></dt><dd><p>Positive lookahead assertion. This succeeds if the contained regular
  1140. expression, represented here by <code class="docutils literal notranslate"><span class="pre">...</span></code>, successfully matches at the current
  1141. location, and fails otherwise. But, once the contained expression has been
  1142. tried, the matching engine doesn’t advance at all; the rest of the pattern is
  1143. tried right where the assertion started.</p>
  1144. </dd>
  1145. <dt><code class="docutils literal notranslate"><span class="pre">(?!...)</span></code></dt><dd><p>Negative lookahead assertion. This is the opposite of the positive assertion;
  1146. it succeeds if the contained expression <em>doesn’t</em> match at the current position
  1147. in the string.</p>
  1148. </dd>
  1149. </dl>
  1150. <p>To make this concrete, let’s look at a case where a lookahead is useful.
  1151. Consider a simple pattern to match a filename and split it apart into a base
  1152. name and an extension, separated by a <code class="docutils literal notranslate"><span class="pre">.</span></code>. For example, in <code class="docutils literal notranslate"><span class="pre">news.rc</span></code>,
  1153. <code class="docutils literal notranslate"><span class="pre">news</span></code> is the base name, and <code class="docutils literal notranslate"><span class="pre">rc</span></code> is the filename’s extension.</p>
  1154. <p>The pattern to match this is quite simple:</p>
  1155. <p><code class="docutils literal notranslate"><span class="pre">.*[.].*$</span></code></p>
  1156. <p>Notice that the <code class="docutils literal notranslate"><span class="pre">.</span></code> needs to be treated specially because it’s a
  1157. metacharacter, so it’s inside a character class to only match that
  1158. specific character. Also notice the trailing <code class="docutils literal notranslate"><span class="pre">$</span></code>; this is added to
  1159. ensure that all the rest of the string must be included in the
  1160. extension. This regular expression matches <code class="docutils literal notranslate"><span class="pre">foo.bar</span></code> and
  1161. <code class="docutils literal notranslate"><span class="pre">autoexec.bat</span></code> and <code class="docutils literal notranslate"><span class="pre">sendmail.cf</span></code> and <code class="docutils literal notranslate"><span class="pre">printers.conf</span></code>.</p>
  1162. <p>Now, consider complicating the problem a bit; what if you want to match
  1163. filenames where the extension is not <code class="docutils literal notranslate"><span class="pre">bat</span></code>? Some incorrect attempts:</p>
  1164. <p><code class="docutils literal notranslate"><span class="pre">.*[.][^b].*$</span></code> The first attempt above tries to exclude <code class="docutils literal notranslate"><span class="pre">bat</span></code> by requiring
  1165. that the first character of the extension is not a <code class="docutils literal notranslate"><span class="pre">b</span></code>. This is wrong,
  1166. because the pattern also doesn’t match <code class="docutils literal notranslate"><span class="pre">foo.bar</span></code>.</p>
  1167. <p><code class="docutils literal notranslate"><span class="pre">.*[.]([^b]..|.[^a].|..[^t])$</span></code></p>
  1168. <p>The expression gets messier when you try to patch up the first solution by
  1169. requiring one of the following cases to match: the first character of the
  1170. extension isn’t <code class="docutils literal notranslate"><span class="pre">b</span></code>; the second character isn’t <code class="docutils literal notranslate"><span class="pre">a</span></code>; or the third character
  1171. isn’t <code class="docutils literal notranslate"><span class="pre">t</span></code>. This accepts <code class="docutils literal notranslate"><span class="pre">foo.bar</span></code> and rejects <code class="docutils literal notranslate"><span class="pre">autoexec.bat</span></code>, but it
  1172. requires a three-letter extension and won’t accept a filename with a two-letter
  1173. extension such as <code class="docutils literal notranslate"><span class="pre">sendmail.cf</span></code>. We’ll complicate the pattern again in an
  1174. effort to fix it.</p>
  1175. <p><code class="docutils literal notranslate"><span class="pre">.*[.]([^b].?.?|.[^a]?.?|..?[^t]?)$</span></code></p>
  1176. <p>In the third attempt, the second and third letters are all made optional in
  1177. order to allow matching extensions shorter than three characters, such as
  1178. <code class="docutils literal notranslate"><span class="pre">sendmail.cf</span></code>.</p>
  1179. <p>The pattern’s getting really complicated now, which makes it hard to read and
  1180. understand. Worse, if the problem changes and you want to exclude both <code class="docutils literal notranslate"><span class="pre">bat</span></code>
  1181. and <code class="docutils literal notranslate"><span class="pre">exe</span></code> as extensions, the pattern would get even more complicated and
  1182. confusing.</p>
  1183. <p>A negative lookahead cuts through all this confusion:</p>
  1184. <p><code class="docutils literal notranslate"><span class="pre">.*[.](?!bat$)[^.]*$</span></code> The negative lookahead means: if the expression <code class="docutils literal notranslate"><span class="pre">bat</span></code>
  1185. doesn’t match at this point, try the rest of the pattern; if <code class="docutils literal notranslate"><span class="pre">bat$</span></code> does
  1186. match, the whole pattern will fail. The trailing <code class="docutils literal notranslate"><span class="pre">$</span></code> is required to ensure
  1187. that something like <code class="docutils literal notranslate"><span class="pre">sample.batch</span></code>, where the extension only starts with
  1188. <code class="docutils literal notranslate"><span class="pre">bat</span></code>, will be allowed. The <code class="docutils literal notranslate"><span class="pre">[^.]*</span></code> makes sure that the pattern works
  1189. when there are multiple dots in the filename.</p>
  1190. <p>Excluding another filename extension is now easy; simply add it as an
  1191. alternative inside the assertion. The following pattern excludes filenames that
  1192. end in either <code class="docutils literal notranslate"><span class="pre">bat</span></code> or <code class="docutils literal notranslate"><span class="pre">exe</span></code>:</p>
  1193. <p><code class="docutils literal notranslate"><span class="pre">.*[.](?!bat$|exe$)[^.]*$</span></code></p>
  1194. </section>
  1195. </section>
  1196. <section id="modifying-strings">
  1197. <h2>Modifying Strings<a class="headerlink" href="#modifying-strings" title="Link to this heading">¶</a></h2>
  1198. <p>Up to this point, we’ve simply performed searches against a static string.
  1199. Regular expressions are also commonly used to modify strings in various ways,
  1200. using the following pattern methods:</p>
  1201. <table class="docutils align-default">
  1202. <thead>
  1203. <tr class="row-odd"><th class="head"><p>Method/Attribute</p></th>
  1204. <th class="head"><p>Purpose</p></th>
  1205. </tr>
  1206. </thead>
  1207. <tbody>
  1208. <tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">split()</span></code></p></td>
  1209. <td><p>Split the string into a list, splitting it
  1210. wherever the RE matches</p></td>
  1211. </tr>
  1212. <tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">sub()</span></code></p></td>
  1213. <td><p>Find all substrings where the RE matches, and
  1214. replace them with a different string</p></td>
  1215. </tr>
  1216. <tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">subn()</span></code></p></td>
  1217. <td><p>Does the same thing as <code class="xref py py-meth docutils literal notranslate"><span class="pre">sub()</span></code>, but
  1218. returns the new string and the number of
  1219. replacements</p></td>
  1220. </tr>
  1221. </tbody>
  1222. </table>
  1223. <section id="splitting-strings">
  1224. <h3>Splitting Strings<a class="headerlink" href="#splitting-strings" title="Link to this heading">¶</a></h3>
  1225. <p>The <a class="reference internal" href="../library/re.html#re.Pattern.split" title="re.Pattern.split"><code class="xref py py-meth docutils literal notranslate"><span class="pre">split()</span></code></a> method of a pattern splits a string apart
  1226. wherever the RE matches, returning a list of the pieces. It’s similar to the
  1227. <a class="reference internal" href="../library/stdtypes.html#str.split" title="str.split"><code class="xref py py-meth docutils literal notranslate"><span class="pre">split()</span></code></a> method of strings but provides much more generality in the
  1228. delimiters that you can split by; string <code class="xref py py-meth docutils literal notranslate"><span class="pre">split()</span></code> only supports splitting by
  1229. whitespace or by a fixed string. As you’d expect, there’s a module-level
  1230. <a class="reference internal" href="../library/re.html#re.split" title="re.split"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.split()</span></code></a> function, too.</p>
  1231. <dl class="py method">
  1232. <dt class="sig sig-object py">
  1233. <span class="sig-prename descclassname"><span class="pre">.</span></span><span class="sig-name descname"><span class="pre">split</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">string</span></span></em><span class="optional">[</span>, <em class="sig-param"><span class="n"><span class="pre">maxsplit=0</span></span></em><span class="optional">]</span><span class="sig-paren">)</span></dt>
  1234. <dd><p>Split <em>string</em> by the matches of the regular expression. If capturing
  1235. parentheses are used in the RE, then their contents will also be returned as
  1236. part of the resulting list. If <em>maxsplit</em> is nonzero, at most <em>maxsplit</em> splits
  1237. are performed.</p>
  1238. </dd></dl>
  1239. <p>You can limit the number of splits made, by passing a value for <em>maxsplit</em>.
  1240. When <em>maxsplit</em> is nonzero, at most <em>maxsplit</em> splits will be made, and the
  1241. remainder of the string is returned as the final element of the list. In the
  1242. following example, the delimiter is any sequence of non-alphanumeric characters.</p>
  1243. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;\W+&#39;</span><span class="p">)</span>
  1244. <span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">&#39;This is a test, short and sweet, of split().&#39;</span><span class="p">)</span>
  1245. <span class="go">[&#39;This&#39;, &#39;is&#39;, &#39;a&#39;, &#39;test&#39;, &#39;short&#39;, &#39;and&#39;, &#39;sweet&#39;, &#39;of&#39;, &#39;split&#39;, &#39;&#39;]</span>
  1246. <span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">&#39;This is a test, short and sweet, of split().&#39;</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
  1247. <span class="go">[&#39;This&#39;, &#39;is&#39;, &#39;a&#39;, &#39;test, short and sweet, of split().&#39;]</span>
  1248. </pre></div>
  1249. </div>
  1250. <p>Sometimes you’re not only interested in what the text between delimiters is, but
  1251. also need to know what the delimiter was. If capturing parentheses are used in
  1252. the RE, then their values are also returned as part of the list. Compare the
  1253. following calls:</p>
  1254. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;\W+&#39;</span><span class="p">)</span>
  1255. <span class="gp">&gt;&gt;&gt; </span><span class="n">p2</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;(\W+)&#39;</span><span class="p">)</span>
  1256. <span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">&#39;This... is a test.&#39;</span><span class="p">)</span>
  1257. <span class="go">[&#39;This&#39;, &#39;is&#39;, &#39;a&#39;, &#39;test&#39;, &#39;&#39;]</span>
  1258. <span class="gp">&gt;&gt;&gt; </span><span class="n">p2</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">&#39;This... is a test.&#39;</span><span class="p">)</span>
  1259. <span class="go">[&#39;This&#39;, &#39;... &#39;, &#39;is&#39;, &#39; &#39;, &#39;a&#39;, &#39; &#39;, &#39;test&#39;, &#39;.&#39;, &#39;&#39;]</span>
  1260. </pre></div>
  1261. </div>
  1262. <p>The module-level function <a class="reference internal" href="../library/re.html#re.split" title="re.split"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.split()</span></code></a> adds the RE to be used as the first
  1263. argument, but is otherwise the same.</p>
  1264. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;[\W]+&#39;</span><span class="p">,</span> <span class="s1">&#39;Words, words, words.&#39;</span><span class="p">)</span>
  1265. <span class="go">[&#39;Words&#39;, &#39;words&#39;, &#39;words&#39;, &#39;&#39;]</span>
  1266. <span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;([\W]+)&#39;</span><span class="p">,</span> <span class="s1">&#39;Words, words, words.&#39;</span><span class="p">)</span>
  1267. <span class="go">[&#39;Words&#39;, &#39;, &#39;, &#39;words&#39;, &#39;, &#39;, &#39;words&#39;, &#39;.&#39;, &#39;&#39;]</span>
  1268. <span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;[\W]+&#39;</span><span class="p">,</span> <span class="s1">&#39;Words, words, words.&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
  1269. <span class="go">[&#39;Words&#39;, &#39;words, words.&#39;]</span>
  1270. </pre></div>
  1271. </div>
  1272. </section>
  1273. <section id="search-and-replace">
  1274. <h3>Search and Replace<a class="headerlink" href="#search-and-replace" title="Link to this heading">¶</a></h3>
  1275. <p>Another common task is to find all the matches for a pattern, and replace them
  1276. with a different string. The <a class="reference internal" href="../library/re.html#re.Pattern.sub" title="re.Pattern.sub"><code class="xref py py-meth docutils literal notranslate"><span class="pre">sub()</span></code></a> method takes a replacement value,
  1277. which can be either a string or a function, and the string to be processed.</p>
  1278. <dl class="py method">
  1279. <dt class="sig sig-object py">
  1280. <span class="sig-prename descclassname"><span class="pre">.</span></span><span class="sig-name descname"><span class="pre">sub</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">replacement</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">string</span></span></em><span class="optional">[</span>, <em class="sig-param"><span class="n"><span class="pre">count=0</span></span></em><span class="optional">]</span><span class="sig-paren">)</span></dt>
  1281. <dd><p>Returns the string obtained by replacing the leftmost non-overlapping
  1282. occurrences of the RE in <em>string</em> by the replacement <em>replacement</em>. If the
  1283. pattern isn’t found, <em>string</em> is returned unchanged.</p>
  1284. <p>The optional argument <em>count</em> is the maximum number of pattern occurrences to be
  1285. replaced; <em>count</em> must be a non-negative integer. The default value of 0 means
  1286. to replace all occurrences.</p>
  1287. </dd></dl>
  1288. <p>Here’s a simple example of using the <a class="reference internal" href="../library/re.html#re.Pattern.sub" title="re.Pattern.sub"><code class="xref py py-meth docutils literal notranslate"><span class="pre">sub()</span></code></a> method. It replaces colour
  1289. names with the word <code class="docutils literal notranslate"><span class="pre">colour</span></code>:</p>
  1290. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">&#39;(blue|white|red)&#39;</span><span class="p">)</span>
  1291. <span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="s1">&#39;colour&#39;</span><span class="p">,</span> <span class="s1">&#39;blue socks and red shoes&#39;</span><span class="p">)</span>
  1292. <span class="go">&#39;colour socks and colour shoes&#39;</span>
  1293. <span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="s1">&#39;colour&#39;</span><span class="p">,</span> <span class="s1">&#39;blue socks and red shoes&#39;</span><span class="p">,</span> <span class="n">count</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
  1294. <span class="go">&#39;colour socks and red shoes&#39;</span>
  1295. </pre></div>
  1296. </div>
  1297. <p>The <a class="reference internal" href="../library/re.html#re.Pattern.subn" title="re.Pattern.subn"><code class="xref py py-meth docutils literal notranslate"><span class="pre">subn()</span></code></a> method does the same work, but returns a 2-tuple containing the
  1298. new string value and the number of replacements that were performed:</p>
  1299. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">&#39;(blue|white|red)&#39;</span><span class="p">)</span>
  1300. <span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">subn</span><span class="p">(</span><span class="s1">&#39;colour&#39;</span><span class="p">,</span> <span class="s1">&#39;blue socks and red shoes&#39;</span><span class="p">)</span>
  1301. <span class="go">(&#39;colour socks and colour shoes&#39;, 2)</span>
  1302. <span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">subn</span><span class="p">(</span><span class="s1">&#39;colour&#39;</span><span class="p">,</span> <span class="s1">&#39;no colours at all&#39;</span><span class="p">)</span>
  1303. <span class="go">(&#39;no colours at all&#39;, 0)</span>
  1304. </pre></div>
  1305. </div>
  1306. <p>Empty matches are replaced only when they’re not adjacent to a previous empty match.</p>
  1307. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">&#39;x*&#39;</span><span class="p">)</span>
  1308. <span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="s1">&#39;-&#39;</span><span class="p">,</span> <span class="s1">&#39;abxd&#39;</span><span class="p">)</span>
  1309. <span class="go">&#39;-a-b--d-&#39;</span>
  1310. </pre></div>
  1311. </div>
  1312. <p>If <em>replacement</em> is a string, any backslash escapes in it are processed. That
  1313. is, <code class="docutils literal notranslate"><span class="pre">\n</span></code> is converted to a single newline character, <code class="docutils literal notranslate"><span class="pre">\r</span></code> is converted to a
  1314. carriage return, and so forth. Unknown escapes such as <code class="docutils literal notranslate"><span class="pre">\&amp;</span></code> are left alone.
  1315. Backreferences, such as <code class="docutils literal notranslate"><span class="pre">\6</span></code>, are replaced with the substring matched by the
  1316. corresponding group in the RE. This lets you incorporate portions of the
  1317. original text in the resulting replacement string.</p>
  1318. <p>This example matches the word <code class="docutils literal notranslate"><span class="pre">section</span></code> followed by a string enclosed in
  1319. <code class="docutils literal notranslate"><span class="pre">{</span></code>, <code class="docutils literal notranslate"><span class="pre">}</span></code>, and changes <code class="docutils literal notranslate"><span class="pre">section</span></code> to <code class="docutils literal notranslate"><span class="pre">subsection</span></code>:</p>
  1320. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">&#39;section{ ( [^}]* ) }&#39;</span><span class="p">,</span> <span class="n">re</span><span class="o">.</span><span class="n">VERBOSE</span><span class="p">)</span>
  1321. <span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;subsection{\1}&#39;</span><span class="p">,</span><span class="s1">&#39;section</span><span class="si">{First}</span><span class="s1"> section</span><span class="si">{second}</span><span class="s1">&#39;</span><span class="p">)</span>
  1322. <span class="go">&#39;subsection{First} subsection{second}&#39;</span>
  1323. </pre></div>
  1324. </div>
  1325. <p>There’s also a syntax for referring to named groups as defined by the
  1326. <code class="docutils literal notranslate"><span class="pre">(?P&lt;name&gt;...)</span></code> syntax. <code class="docutils literal notranslate"><span class="pre">\g&lt;name&gt;</span></code> will use the substring matched by the
  1327. group named <code class="docutils literal notranslate"><span class="pre">name</span></code>, and <code class="docutils literal notranslate"><span class="pre">\g&lt;number&gt;</span></code> uses the corresponding group number.
  1328. <code class="docutils literal notranslate"><span class="pre">\g&lt;2&gt;</span></code> is therefore equivalent to <code class="docutils literal notranslate"><span class="pre">\2</span></code>, but isn’t ambiguous in a
  1329. replacement string such as <code class="docutils literal notranslate"><span class="pre">\g&lt;2&gt;0</span></code>. (<code class="docutils literal notranslate"><span class="pre">\20</span></code> would be interpreted as a
  1330. reference to group 20, not a reference to group 2 followed by the literal
  1331. character <code class="docutils literal notranslate"><span class="pre">'0'</span></code>.) The following substitutions are all equivalent, but use all
  1332. three variations of the replacement string.</p>
  1333. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">&#39;section{ (?P&lt;name&gt; [^}]* ) }&#39;</span><span class="p">,</span> <span class="n">re</span><span class="o">.</span><span class="n">VERBOSE</span><span class="p">)</span>
  1334. <span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;subsection{\1}&#39;</span><span class="p">,</span><span class="s1">&#39;section</span><span class="si">{First}</span><span class="s1">&#39;</span><span class="p">)</span>
  1335. <span class="go">&#39;subsection{First}&#39;</span>
  1336. <span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;subsection{\g&lt;1&gt;}&#39;</span><span class="p">,</span><span class="s1">&#39;section</span><span class="si">{First}</span><span class="s1">&#39;</span><span class="p">)</span>
  1337. <span class="go">&#39;subsection{First}&#39;</span>
  1338. <span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;subsection{\g&lt;name&gt;}&#39;</span><span class="p">,</span><span class="s1">&#39;section</span><span class="si">{First}</span><span class="s1">&#39;</span><span class="p">)</span>
  1339. <span class="go">&#39;subsection{First}&#39;</span>
  1340. </pre></div>
  1341. </div>
  1342. <p><em>replacement</em> can also be a function, which gives you even more control. If
  1343. <em>replacement</em> is a function, the function is called for every non-overlapping
  1344. occurrence of <em>pattern</em>. On each call, the function is passed a
  1345. <a class="reference internal" href="../library/re.html#match-objects"><span class="std std-ref">match object</span></a> argument for the match and can use this
  1346. information to compute the desired replacement string and return it.</p>
  1347. <p>In the following example, the replacement function translates decimals into
  1348. hexadecimal:</p>
  1349. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">hexrepl</span><span class="p">(</span><span class="n">match</span><span class="p">):</span>
  1350. <span class="gp">... </span> <span class="s2">&quot;Return the hex string for a decimal number&quot;</span>
  1351. <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>
  1352. <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>
  1353. <span class="gp">...</span>
  1354. <span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;\d+&#39;</span><span class="p">)</span>
  1355. <span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="n">hexrepl</span><span class="p">,</span> <span class="s1">&#39;Call 65490 for printing, 49152 for user code.&#39;</span><span class="p">)</span>
  1356. <span class="go">&#39;Call 0xffd2 for printing, 0xc000 for user code.&#39;</span>
  1357. </pre></div>
  1358. </div>
  1359. <p>When using the module-level <a class="reference internal" href="../library/re.html#re.sub" title="re.sub"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.sub()</span></code></a> function, the pattern is passed as
  1360. the first argument. The pattern may be provided as an object or as a string; if
  1361. you need to specify regular expression flags, you must either use a
  1362. pattern object as the first parameter, or use embedded modifiers in the
  1363. pattern string, e.g. <code class="docutils literal notranslate"><span class="pre">sub(&quot;(?i)b+&quot;,</span> <span class="pre">&quot;x&quot;,</span> <span class="pre">&quot;bbbb</span> <span class="pre">BBBB&quot;)</span></code> returns <code class="docutils literal notranslate"><span class="pre">'x</span> <span class="pre">x'</span></code>.</p>
  1364. </section>
  1365. </section>
  1366. <section id="common-problems">
  1367. <h2>Common Problems<a class="headerlink" href="#common-problems" title="Link to this heading">¶</a></h2>
  1368. <p>Regular expressions are a powerful tool for some applications, but in some ways
  1369. their behaviour isn’t intuitive and at times they don’t behave the way you may
  1370. expect them to. This section will point out some of the most common pitfalls.</p>
  1371. <section id="use-string-methods">
  1372. <h3>Use String Methods<a class="headerlink" href="#use-string-methods" title="Link to this heading">¶</a></h3>
  1373. <p>Sometimes using the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module is a mistake. If you’re matching a fixed
  1374. 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."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> features
  1375. such as the <a class="reference internal" href="../library/re.html#re.IGNORECASE" title="re.IGNORECASE"><code class="xref py py-const docutils literal notranslate"><span class="pre">IGNORECASE</span></code></a> flag, then the full power of regular expressions
  1376. may not be required. Strings have several methods for performing operations with
  1377. fixed strings and they’re usually much faster, because the implementation is a
  1378. single small C loop that’s been optimized for the purpose, instead of the large,
  1379. more generalized regular expression engine.</p>
  1380. <p>One example might be replacing a single fixed string with another one; for
  1381. example, you might replace <code class="docutils literal notranslate"><span class="pre">word</span></code> with <code class="docutils literal notranslate"><span class="pre">deed</span></code>. <a class="reference internal" href="../library/re.html#re.sub" title="re.sub"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.sub()</span></code></a> seems like the
  1382. function to use for this, but consider the <a class="reference internal" href="../library/stdtypes.html#str.replace" title="str.replace"><code class="xref py py-meth docutils literal notranslate"><span class="pre">replace()</span></code></a> method. Note that
  1383. <code class="xref py py-meth docutils literal notranslate"><span class="pre">replace()</span></code> will also replace <code class="docutils literal notranslate"><span class="pre">word</span></code> inside words, turning <code class="docutils literal notranslate"><span class="pre">swordfish</span></code>
  1384. into <code class="docutils literal notranslate"><span class="pre">sdeedfish</span></code>, but the naive RE <code class="docutils literal notranslate"><span class="pre">word</span></code> would have done that, too. (To
  1385. avoid performing the substitution on parts of words, the pattern would have to
  1386. be <code class="docutils literal notranslate"><span class="pre">\bword\b</span></code>, in order to require that <code class="docutils literal notranslate"><span class="pre">word</span></code> have a word boundary on
  1387. either side. This takes the job beyond <code class="xref py py-meth docutils literal notranslate"><span class="pre">replace()</span></code>’s abilities.)</p>
  1388. <p>Another common task is deleting every occurrence of a single character from a
  1389. string or replacing it with another single character. You might do this with
  1390. something like <code class="docutils literal notranslate"><span class="pre">re.sub('\n',</span> <span class="pre">'</span> <span class="pre">',</span> <span class="pre">S)</span></code>, but <a class="reference internal" href="../library/stdtypes.html#str.translate" title="str.translate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">translate()</span></code></a> is capable of
  1391. doing both tasks and will be faster than any regular expression operation can
  1392. be.</p>
  1393. <p>In short, before turning to the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module, consider whether your problem
  1394. can be solved with a faster and simpler string method.</p>
  1395. </section>
  1396. <section id="match-versus-search">
  1397. <h3>match() versus search()<a class="headerlink" href="#match-versus-search" title="Link to this heading">¶</a></h3>
  1398. <p>The <a class="reference internal" href="../library/re.html#re.match" title="re.match"><code class="xref py py-func docutils literal notranslate"><span class="pre">match()</span></code></a> function only checks if the RE matches at the beginning of the
  1399. string while <a class="reference internal" href="../library/re.html#re.search" title="re.search"><code class="xref py py-func docutils literal notranslate"><span class="pre">search()</span></code></a> will scan forward through the string for a match.
  1400. It’s important to keep this distinction in mind. Remember, <code class="xref py py-func docutils literal notranslate"><span class="pre">match()</span></code> will
  1401. only report a successful match which will start at 0; if the match wouldn’t
  1402. start at zero, <code class="xref py py-func docutils literal notranslate"><span class="pre">match()</span></code> will <em>not</em> report it.</p>
  1403. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s1">&#39;super&#39;</span><span class="p">,</span> <span class="s1">&#39;superstition&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">span</span><span class="p">())</span>
  1404. <span class="go">(0, 5)</span>
  1405. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s1">&#39;super&#39;</span><span class="p">,</span> <span class="s1">&#39;insuperable&#39;</span><span class="p">))</span>
  1406. <span class="go">None</span>
  1407. </pre></div>
  1408. </div>
  1409. <p>On the other hand, <a class="reference internal" href="../library/re.html#re.search" title="re.search"><code class="xref py py-func docutils literal notranslate"><span class="pre">search()</span></code></a> will scan forward through the string,
  1410. reporting the first match it finds.</p>
  1411. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;super&#39;</span><span class="p">,</span> <span class="s1">&#39;superstition&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">span</span><span class="p">())</span>
  1412. <span class="go">(0, 5)</span>
  1413. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;super&#39;</span><span class="p">,</span> <span class="s1">&#39;insuperable&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">span</span><span class="p">())</span>
  1414. <span class="go">(2, 7)</span>
  1415. </pre></div>
  1416. </div>
  1417. <p>Sometimes you’ll be tempted to keep using <a class="reference internal" href="../library/re.html#re.match" title="re.match"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.match()</span></code></a>, and just add <code class="docutils literal notranslate"><span class="pre">.*</span></code>
  1418. to the front of your RE. Resist this temptation and use <a class="reference internal" href="../library/re.html#re.search" title="re.search"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.search()</span></code></a>
  1419. instead. The regular expression compiler does some analysis of REs in order to
  1420. speed up the process of looking for a match. One such analysis figures out what
  1421. the first character of a match must be; for example, a pattern starting with
  1422. <code class="docutils literal notranslate"><span class="pre">Crow</span></code> must match starting with a <code class="docutils literal notranslate"><span class="pre">'C'</span></code>. The analysis lets the engine
  1423. quickly scan through the string looking for the starting character, only trying
  1424. the full match if a <code class="docutils literal notranslate"><span class="pre">'C'</span></code> is found.</p>
  1425. <p>Adding <code class="docutils literal notranslate"><span class="pre">.*</span></code> defeats this optimization, requiring scanning to the end of the
  1426. string and then backtracking to find a match for the rest of the RE. Use
  1427. <a class="reference internal" href="../library/re.html#re.search" title="re.search"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.search()</span></code></a> instead.</p>
  1428. </section>
  1429. <section id="greedy-versus-non-greedy">
  1430. <h3>Greedy versus Non-Greedy<a class="headerlink" href="#greedy-versus-non-greedy" title="Link to this heading">¶</a></h3>
  1431. <p>When repeating a regular expression, as in <code class="docutils literal notranslate"><span class="pre">a*</span></code>, the resulting action is to
  1432. consume as much of the pattern as possible. This fact often bites you when
  1433. you’re trying to match a pair of balanced delimiters, such as the angle brackets
  1434. surrounding an HTML tag. The naive pattern for matching a single HTML tag
  1435. doesn’t work because of the greedy nature of <code class="docutils literal notranslate"><span class="pre">.*</span></code>.</p>
  1436. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;&lt;html&gt;&lt;head&gt;&lt;title&gt;Title&lt;/title&gt;&#39;</span>
  1437. <span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
  1438. <span class="go">32</span>
  1439. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s1">&#39;&lt;.*&gt;&#39;</span><span class="p">,</span> <span class="n">s</span><span class="p">)</span><span class="o">.</span><span class="n">span</span><span class="p">())</span>
  1440. <span class="go">(0, 32)</span>
  1441. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s1">&#39;&lt;.*&gt;&#39;</span><span class="p">,</span> <span class="n">s</span><span class="p">)</span><span class="o">.</span><span class="n">group</span><span class="p">())</span>
  1442. <span class="go">&lt;html&gt;&lt;head&gt;&lt;title&gt;Title&lt;/title&gt;</span>
  1443. </pre></div>
  1444. </div>
  1445. <p>The RE matches the <code class="docutils literal notranslate"><span class="pre">'&lt;'</span></code> in <code class="docutils literal notranslate"><span class="pre">'&lt;html&gt;'</span></code>, and the <code class="docutils literal notranslate"><span class="pre">.*</span></code> consumes the rest of
  1446. the string. There’s still more left in the RE, though, and the <code class="docutils literal notranslate"><span class="pre">&gt;</span></code> can’t
  1447. match at the end of the string, so the regular expression engine has to
  1448. backtrack character by character until it finds a match for the <code class="docutils literal notranslate"><span class="pre">&gt;</span></code>. The
  1449. final match extends from the <code class="docutils literal notranslate"><span class="pre">'&lt;'</span></code> in <code class="docutils literal notranslate"><span class="pre">'&lt;html&gt;'</span></code> to the <code class="docutils literal notranslate"><span class="pre">'&gt;'</span></code> in
  1450. <code class="docutils literal notranslate"><span class="pre">'&lt;/title&gt;'</span></code>, which isn’t what you want.</p>
  1451. <p>In this case, the solution is to use the non-greedy quantifiers <code class="docutils literal notranslate"><span class="pre">*?</span></code>, <code class="docutils literal notranslate"><span class="pre">+?</span></code>,
  1452. <code class="docutils literal notranslate"><span class="pre">??</span></code>, or <code class="docutils literal notranslate"><span class="pre">{m,n}?</span></code>, which match as <em>little</em> text as possible. In the above
  1453. example, the <code class="docutils literal notranslate"><span class="pre">'&gt;'</span></code> is tried immediately after the first <code class="docutils literal notranslate"><span class="pre">'&lt;'</span></code> matches, and
  1454. when it fails, the engine advances a character at a time, retrying the <code class="docutils literal notranslate"><span class="pre">'&gt;'</span></code>
  1455. at every step. This produces just the right result:</p>
  1456. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s1">&#39;&lt;.*?&gt;&#39;</span><span class="p">,</span> <span class="n">s</span><span class="p">)</span><span class="o">.</span><span class="n">group</span><span class="p">())</span>
  1457. <span class="go">&lt;html&gt;</span>
  1458. </pre></div>
  1459. </div>
  1460. <p>(Note that parsing HTML or XML with regular expressions is painful.
  1461. Quick-and-dirty patterns will handle common cases, but HTML and XML have special
  1462. cases that will break the obvious regular expression; by the time you’ve written
  1463. a regular expression that handles all of the possible cases, the patterns will
  1464. be <em>very</em> complicated. Use an HTML or XML parser module for such tasks.)</p>
  1465. </section>
  1466. <section id="using-re-verbose">
  1467. <h3>Using re.VERBOSE<a class="headerlink" href="#using-re-verbose" title="Link to this heading">¶</a></h3>
  1468. <p>By now you’ve probably noticed that regular expressions are a very compact
  1469. notation, but they’re not terribly readable. REs of moderate complexity can
  1470. become lengthy collections of backslashes, parentheses, and metacharacters,
  1471. making them difficult to read and understand.</p>
  1472. <p>For such REs, specifying the <a class="reference internal" href="../library/re.html#re.VERBOSE" title="re.VERBOSE"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.VERBOSE</span></code></a> flag when compiling the regular
  1473. expression can be helpful, because it allows you to format the regular
  1474. expression more clearly.</p>
  1475. <p>The <code class="docutils literal notranslate"><span class="pre">re.VERBOSE</span></code> flag has several effects. Whitespace in the regular
  1476. expression that <em>isn’t</em> inside a character class is ignored. This means that an
  1477. expression such as <code class="docutils literal notranslate"><span class="pre">dog</span> <span class="pre">|</span> <span class="pre">cat</span></code> is equivalent to the less readable <code class="docutils literal notranslate"><span class="pre">dog|cat</span></code>,
  1478. but <code class="docutils literal notranslate"><span class="pre">[a</span> <span class="pre">b]</span></code> will still match the characters <code class="docutils literal notranslate"><span class="pre">'a'</span></code>, <code class="docutils literal notranslate"><span class="pre">'b'</span></code>, or a space. In
  1479. addition, you can also put comments inside a RE; comments extend from a <code class="docutils literal notranslate"><span class="pre">#</span></code>
  1480. character to the next newline. When used with triple-quoted strings, this
  1481. enables REs to be formatted more neatly:</p>
  1482. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><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="sa">r</span><span class="s2">&quot;&quot;&quot;</span>
  1483. <span class="s2"> \s* # Skip leading whitespace</span>
  1484. <span class="s2"> (?P&lt;header&gt;[^:]+) # Header name</span>
  1485. <span class="s2"> \s* : # Whitespace, and a colon</span>
  1486. <span class="s2"> (?P&lt;value&gt;.*?) # The header&#39;s value -- *? used to</span>
  1487. <span class="s2"> # lose the following trailing whitespace</span>
  1488. <span class="s2"> \s*$ # Trailing whitespace to end-of-line</span>
  1489. <span class="s2">&quot;&quot;&quot;</span><span class="p">,</span> <span class="n">re</span><span class="o">.</span><span class="n">VERBOSE</span><span class="p">)</span>
  1490. </pre></div>
  1491. </div>
  1492. <p>This is far more readable than:</p>
  1493. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><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="sa">r</span><span class="s2">&quot;\s*(?P&lt;header&gt;[^:]+)\s*:(?P&lt;value&gt;.*?)\s*$&quot;</span><span class="p">)</span>
  1494. </pre></div>
  1495. </div>
  1496. </section>
  1497. </section>
  1498. <section id="feedback">
  1499. <h2>Feedback<a class="headerlink" href="#feedback" title="Link to this heading">¶</a></h2>
  1500. <p>Regular expressions are a complicated topic. Did this document help you
  1501. understand them? Were there parts that were unclear, or Problems you
  1502. encountered that weren’t covered here? If so, please send suggestions for
  1503. improvements to the author.</p>
  1504. <p>The most complete book on regular expressions is almost certainly Jeffrey
  1505. Friedl’s Mastering Regular Expressions, published by O’Reilly. Unfortunately,
  1506. it exclusively concentrates on Perl and Java’s flavours of regular expressions,
  1507. and doesn’t contain any Python material at all, so it won’t be useful as a
  1508. reference for programming in Python. (The first edition covered Python’s
  1509. now-removed <code class="xref py py-mod docutils literal notranslate"><span class="pre">regex</span></code> module, which won’t help you much.) Consider checking
  1510. it out from your library.</p>
  1511. </section>
  1512. </section>
  1513. <div class="clearer"></div>
  1514. </div>
  1515. </div>
  1516. </div>
  1517. <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
  1518. <div class="sphinxsidebarwrapper">
  1519. <div>
  1520. <h3><a href="../contents.html">Table of Contents</a></h3>
  1521. <ul>
  1522. <li><a class="reference internal" href="#">Regular Expression HOWTO</a><ul>
  1523. <li><a class="reference internal" href="#introduction">Introduction</a></li>
  1524. <li><a class="reference internal" href="#simple-patterns">Simple Patterns</a><ul>
  1525. <li><a class="reference internal" href="#matching-characters">Matching Characters</a></li>
  1526. <li><a class="reference internal" href="#repeating-things">Repeating Things</a></li>
  1527. </ul>
  1528. </li>
  1529. <li><a class="reference internal" href="#using-regular-expressions">Using Regular Expressions</a><ul>
  1530. <li><a class="reference internal" href="#compiling-regular-expressions">Compiling Regular Expressions</a></li>
  1531. <li><a class="reference internal" href="#the-backslash-plague">The Backslash Plague</a></li>
  1532. <li><a class="reference internal" href="#performing-matches">Performing Matches</a></li>
  1533. <li><a class="reference internal" href="#module-level-functions">Module-Level Functions</a></li>
  1534. <li><a class="reference internal" href="#compilation-flags">Compilation Flags</a></li>
  1535. </ul>
  1536. </li>
  1537. <li><a class="reference internal" href="#more-pattern-power">More Pattern Power</a><ul>
  1538. <li><a class="reference internal" href="#more-metacharacters">More Metacharacters</a></li>
  1539. <li><a class="reference internal" href="#grouping">Grouping</a></li>
  1540. <li><a class="reference internal" href="#non-capturing-and-named-groups">Non-capturing and Named Groups</a></li>
  1541. <li><a class="reference internal" href="#lookahead-assertions">Lookahead Assertions</a></li>
  1542. </ul>
  1543. </li>
  1544. <li><a class="reference internal" href="#modifying-strings">Modifying Strings</a><ul>
  1545. <li><a class="reference internal" href="#splitting-strings">Splitting Strings</a></li>
  1546. <li><a class="reference internal" href="#search-and-replace">Search and Replace</a></li>
  1547. </ul>
  1548. </li>
  1549. <li><a class="reference internal" href="#common-problems">Common Problems</a><ul>
  1550. <li><a class="reference internal" href="#use-string-methods">Use String Methods</a></li>
  1551. <li><a class="reference internal" href="#match-versus-search">match() versus search()</a></li>
  1552. <li><a class="reference internal" href="#greedy-versus-non-greedy">Greedy versus Non-Greedy</a></li>
  1553. <li><a class="reference internal" href="#using-re-verbose">Using re.VERBOSE</a></li>
  1554. </ul>
  1555. </li>
  1556. <li><a class="reference internal" href="#feedback">Feedback</a></li>
  1557. </ul>
  1558. </li>
  1559. </ul>
  1560. </div>
  1561. <div>
  1562. <h4>Previous topic</h4>
  1563. <p class="topless"><a href="logging-cookbook.html"
  1564. title="previous chapter">Logging Cookbook</a></p>
  1565. </div>
  1566. <div>
  1567. <h4>Next topic</h4>
  1568. <p class="topless"><a href="sockets.html"
  1569. title="next chapter">Socket Programming HOWTO</a></p>
  1570. </div>
  1571. <div role="note" aria-label="source link">
  1572. <h3>This Page</h3>
  1573. <ul class="this-page-menu">
  1574. <li><a href="../bugs.html">Report a Bug</a></li>
  1575. <li>
  1576. <a href="https://github.com/python/cpython/blob/main/Doc/howto/regex.rst"
  1577. rel="nofollow">Show Source
  1578. </a>
  1579. </li>
  1580. </ul>
  1581. </div>
  1582. </div>
  1583. <div id="sidebarbutton" title="Collapse sidebar">
  1584. <span>«</span>
  1585. </div>
  1586. </div>
  1587. <div class="clearer"></div>
  1588. </div>
  1589. <div class="related" role="navigation" aria-label="related navigation">
  1590. <h3>Navigation</h3>
  1591. <ul>
  1592. <li class="right" style="margin-right: 10px">
  1593. <a href="../genindex.html" title="General Index"
  1594. >index</a></li>
  1595. <li class="right" >
  1596. <a href="../py-modindex.html" title="Python Module Index"
  1597. >modules</a> |</li>
  1598. <li class="right" >
  1599. <a href="sockets.html" title="Socket Programming HOWTO"
  1600. >next</a> |</li>
  1601. <li class="right" >
  1602. <a href="logging-cookbook.html" title="Logging Cookbook"
  1603. >previous</a> |</li>
  1604. <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  1605. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  1606. <li class="switchers">
  1607. <div class="language_switcher_placeholder"></div>
  1608. <div class="version_switcher_placeholder"></div>
  1609. </li>
  1610. <li>
  1611. </li>
  1612. <li id="cpython-language-and-version">
  1613. <a href="../index.html">3.12.3 Documentation</a> &#187;
  1614. </li>
  1615. <li class="nav-item nav-item-1"><a href="index.html" >Python HOWTOs</a> &#187;</li>
  1616. <li class="nav-item nav-item-this"><a href="">Regular Expression HOWTO</a></li>
  1617. <li class="right">
  1618. <div class="inline-search" role="search">
  1619. <form class="inline-search" action="../search.html" method="get">
  1620. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
  1621. <input type="submit" value="Go" />
  1622. </form>
  1623. </div>
  1624. |
  1625. </li>
  1626. <li class="right">
  1627. <label class="theme-selector-label">
  1628. Theme
  1629. <select class="theme-selector" oninput="activateTheme(this.value)">
  1630. <option value="auto" selected>Auto</option>
  1631. <option value="light">Light</option>
  1632. <option value="dark">Dark</option>
  1633. </select>
  1634. </label> |</li>
  1635. </ul>
  1636. </div>
  1637. <div class="footer">
  1638. &copy;
  1639. <a href="../copyright.html">
  1640. Copyright
  1641. </a>
  1642. 2001-2024, Python Software Foundation.
  1643. <br />
  1644. This page is licensed under the Python Software Foundation License Version 2.
  1645. <br />
  1646. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
  1647. <br />
  1648. See <a href="/license.html">History and License</a> for more information.<br />
  1649. <br />
  1650. The Python Software Foundation is a non-profit corporation.
  1651. <a href="https://www.python.org/psf/donations/">Please donate.</a>
  1652. <br />
  1653. <br />
  1654. Last updated on Apr 09, 2024 (13:47 UTC).
  1655. <a href="/bugs.html">Found a bug</a>?
  1656. <br />
  1657. Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 7.2.6.
  1658. </div>
  1659. </body>
  1660. </html>
上海开阖软件有限公司 沪ICP备12045867号-1