1 .. _regex-howto: 2 3 **************************** 4 Regular Expression HOWTO 5 **************************** 6 7 :Author: A.M. Kuchling <amk@amk.ca> 8 9 .. TODO: 10 Document lookbehind assertions 11 Better way of displaying a RE, a string, and what it matches 12 Mention optional argument to match.groups() 13 Unicode (at least a reference) 14 15 16 .. topic:: Abstract 17 18 This document is an introductory tutorial to using regular expressions in Python 19 with the :mod:`re` module. It provides a gentler introduction than the 20 corresponding section in the Library Reference. 21 22 23 Introduction 24 ============ 25 26 Regular expressions (called REs, or regexes, or regex patterns) are essentially 27 a tiny, highly specialized programming language embedded inside Python and made 28 available through the :mod:`re` module. Using this little language, you specify 29 the rules for the set of possible strings that you want to match; this set might 30 contain English sentences, or e-mail addresses, or TeX commands, or anything you 31 like. You can then ask questions such as "Does this string match the pattern?", 32 or "Is there a match for the pattern anywhere in this string?". You can also 33 use REs to modify a string or to split it apart in various ways. 34 35 Regular expression patterns are compiled into a series of bytecodes which are 36 then executed by a matching engine written in C. For advanced use, it may be 37 necessary to pay careful attention to how the engine will execute a given RE, 38 and write the RE in a certain way in order to produce bytecode that runs faster. 39 Optimization isn't covered in this document, because it requires that you have a 40 good understanding of the matching engine's internals. 41 42 The regular expression language is relatively small and restricted, so not all 43 possible string processing tasks can be done using regular expressions. There 44 are also tasks that *can* be done with regular expressions, but the expressions 45 turn out to be very complicated. In these cases, you may be better off writing 46 Python code to do the processing; while Python code will be slower than an 47 elaborate regular expression, it will also probably be more understandable. 48 49 50 Simple Patterns 51 =============== 52 53 We'll start by learning about the simplest possible regular expressions. Since 54 regular expressions are used to operate on strings, we'll begin with the most 55 common task: matching characters. 56 57 For a detailed explanation of the computer science underlying regular 58 expressions (deterministic and non-deterministic finite automata), you can refer 59 to almost any textbook on writing compilers. 60 61 62 Matching Characters 63 ------------------- 64 65 Most letters and characters will simply match themselves. For example, the 66 regular expression ``test`` will match the string ``test`` exactly. (You can 67 enable a case-insensitive mode that would let this RE match ``Test`` or ``TEST`` 68 as well; more about this later.) 69 70 There are exceptions to this rule; some characters are special 71 :dfn:`metacharacters`, and don't match themselves. Instead, they signal that 72 some out-of-the-ordinary thing should be matched, or they affect other portions 73 of the RE by repeating them or changing their meaning. Much of this document is 74 devoted to discussing various metacharacters and what they do. 75 76 Here's a complete list of the metacharacters; their meanings will be discussed 77 in the rest of this HOWTO. 78 79 .. code-block:: none 80 81 . ^ $ * + ? { } [ ] \ | ( ) 82 83 The first metacharacters we'll look at are ``[`` and ``]``. They're used for 84 specifying a character class, which is a set of characters that you wish to 85 match. Characters can be listed individually, or a range of characters can be 86 indicated by giving two characters and separating them by a ``'-'``. For 87 example, ``[abc]`` will match any of the characters ``a``, ``b``, or ``c``; this 88 is the same as ``[a-c]``, which uses a range to express the same set of 89 characters. If you wanted to match only lowercase letters, your RE would be 90 ``[a-z]``. 91 92 Metacharacters are not active inside classes. For example, ``[akm$]`` will 93 match any of the characters ``'a'``, ``'k'``, ``'m'``, or ``'$'``; ``'$'`` is 94 usually a metacharacter, but inside a character class it's stripped of its 95 special nature. 96 97 You can match the characters not listed within the class by :dfn:`complementing` 98 the set. This is indicated by including a ``'^'`` as the first character of the 99 class; ``'^'`` outside a character class will simply match the ``'^'`` 100 character. For example, ``[^5]`` will match any character except ``'5'``. 101 102 Perhaps the most important metacharacter is the backslash, ``\``. As in Python 103 string literals, the backslash can be followed by various characters to signal 104 various special sequences. It's also used to escape all the metacharacters so 105 you can still match them in patterns; for example, if you need to match a ``[`` 106 or ``\``, you can precede them with a backslash to remove their special 107 meaning: ``\[`` or ``\\``. 108 109 Some of the special sequences beginning with ``'\'`` represent 110 predefined sets of characters that are often useful, such as the set 111 of digits, the set of letters, or the set of anything that isn't 112 whitespace. 113 114 Let's take an example: ``\w`` matches any alphanumeric character. If 115 the regex pattern is expressed in bytes, this is equivalent to the 116 class ``[a-zA-Z0-9_]``. If the regex pattern is a string, ``\w`` will 117 match all the characters marked as letters in the Unicode database 118 provided by the :mod:`unicodedata` module. You can use the more 119 restricted definition of ``\w`` in a string pattern by supplying the 120 :const:`re.ASCII` flag when compiling the regular expression. 121 122 The following list of special sequences isn't complete. For a complete 123 list of sequences and expanded class definitions for Unicode string 124 patterns, see the last part of :ref:`Regular Expression Syntax 125 <re-syntax>` in the Standard Library reference. In general, the 126 Unicode versions match any character that's in the appropriate 127 category in the Unicode database. 128 129 ``\d`` 130 Matches any decimal digit; this is equivalent to the class ``[0-9]``. 131 132 ``\D`` 133 Matches any non-digit character; this is equivalent to the class ``[^0-9]``. 134 135 ``\s`` 136 Matches any whitespace character; this is equivalent to the class ``[ 137 \t\n\r\f\v]``. 138 139 ``\S`` 140 Matches any non-whitespace character; this is equivalent to the class ``[^ 141 \t\n\r\f\v]``. 142 143 ``\w`` 144 Matches any alphanumeric character; this is equivalent to the class 145 ``[a-zA-Z0-9_]``. 146 147 ``\W`` 148 Matches any non-alphanumeric character; this is equivalent to the class 149 ``[^a-zA-Z0-9_]``. 150 151 These sequences can be included inside a character class. For example, 152 ``[\s,.]`` is a character class that will match any whitespace character, or 153 ``','`` or ``'.'``. 154 155 The final metacharacter in this section is ``.``. It matches anything except a 156 newline character, and there's an alternate mode (``re.DOTALL``) where it will 157 match even a newline. ``'.'`` is often used where you want to match "any 158 character". 159 160 161 Repeating Things 162 ---------------- 163 164 Being able to match varying sets of characters is the first thing regular 165 expressions can do that isn't already possible with the methods available on 166 strings. However, if that was the only additional capability of regexes, they 167 wouldn't be much of an advance. Another capability is that you can specify that 168 portions of the RE must be repeated a certain number of times. 169 170 The first metacharacter for repeating things that we'll look at is ``*``. ``*`` 171 doesn't match the literal character ``*``; instead, it specifies that the 172 previous character can be matched zero or more times, instead of exactly once. 173 174 For example, ``ca*t`` will match ``ct`` (0 ``a`` characters), ``cat`` (1 ``a``), 175 ``caaat`` (3 ``a`` characters), and so forth. The RE engine has various 176 internal limitations stemming from the size of C's ``int`` type that will 177 prevent it from matching over 2 billion ``a`` characters; patterns 178 are usually not written to match that much data. 179 180 Repetitions such as ``*`` are :dfn:`greedy`; when repeating a RE, the matching 181 engine will try to repeat it as many times as possible. If later portions of the 182 pattern don't match, the matching engine will then back up and try again with 183 fewer repetitions. 184 185 A step-by-step example will make this more obvious. Let's consider the 186 expression ``a[bcd]*b``. This matches the letter ``'a'``, zero or more letters 187 from the class ``[bcd]``, and finally ends with a ``'b'``. Now imagine matching 188 this RE against the string ``abcbd``. 189 190 +------+-----------+---------------------------------+ 191 | Step | Matched | Explanation | 192 +======+===========+=================================+ 193 | 1 | ``a`` | The ``a`` in the RE matches. | 194 +------+-----------+---------------------------------+ 195 | 2 | ``abcbd`` | The engine matches ``[bcd]*``, | 196 | | | going as far as it can, which | 197 | | | is to the end of the string. | 198 +------+-----------+---------------------------------+ 199 | 3 | *Failure* | The engine tries to match | 200 | | | ``b``, but the current position | 201 | | | is at the end of the string, so | 202 | | | it fails. | 203 +------+-----------+---------------------------------+ 204 | 4 | ``abcb`` | Back up, so that ``[bcd]*`` | 205 | | | matches one less character. | 206 +------+-----------+---------------------------------+ 207 | 5 | *Failure* | Try ``b`` again, but the | 208 | | | current position is at the last | 209 | | | character, which is a ``'d'``. | 210 +------+-----------+---------------------------------+ 211 | 6 | ``abc`` | Back up again, so that | 212 | | | ``[bcd]*`` is only matching | 213 | | | ``bc``. | 214 +------+-----------+---------------------------------+ 215 | 6 | ``abcb`` | Try ``b`` again. This time | 216 | | | the character at the | 217 | | | current position is ``'b'``, so | 218 | | | it succeeds. | 219 +------+-----------+---------------------------------+ 220 221 The end of the RE has now been reached, and it has matched ``abcb``. This 222 demonstrates how the matching engine goes as far as it can at first, and if no 223 match is found it will then progressively back up and retry the rest of the RE 224 again and again. It will back up until it has tried zero matches for 225 ``[bcd]*``, and if that subsequently fails, the engine will conclude that the 226 string doesn't match the RE at all. 227 228 Another repeating metacharacter is ``+``, which matches one or more times. Pay 229 careful attention to the difference between ``*`` and ``+``; ``*`` matches 230 *zero* or more times, so whatever's being repeated may not be present at all, 231 while ``+`` requires at least *one* occurrence. To use a similar example, 232 ``ca+t`` will match ``cat`` (1 ``a``), ``caaat`` (3 ``a``'s), but won't match 233 ``ct``. 234 235 There are two more repeating qualifiers. The question mark character, ``?``, 236 matches either once or zero times; you can think of it as marking something as 237 being optional. For example, ``home-?brew`` matches either ``homebrew`` or 238 ``home-brew``. 239 240 The most complicated repeated qualifier is ``{m,n}``, where *m* and *n* are 241 decimal integers. This qualifier means there must be at least *m* repetitions, 242 and at most *n*. For example, ``a/{1,3}b`` will match ``a/b``, ``a//b``, and 243 ``a///b``. It won't match ``ab``, which has no slashes, or ``a////b``, which 244 has four. 245 246 You can omit either *m* or *n*; in that case, a reasonable value is assumed for 247 the missing value. Omitting *m* is interpreted as a lower limit of 0, while 248 omitting *n* results in an upper bound of infinity --- actually, the upper bound 249 is the 2-billion limit mentioned earlier, but that might as well be infinity. 250 251 Readers of a reductionist bent may notice that the three other qualifiers can 252 all be expressed using this notation. ``{0,}`` is the same as ``*``, ``{1,}`` 253 is equivalent to ``+``, and ``{0,1}`` is the same as ``?``. It's better to use 254 ``*``, ``+``, or ``?`` when you can, simply because they're shorter and easier 255 to read. 256 257 258 Using Regular Expressions 259 ========================= 260 261 Now that we've looked at some simple regular expressions, how do we actually use 262 them in Python? The :mod:`re` module provides an interface to the regular 263 expression engine, allowing you to compile REs into objects and then perform 264 matches with them. 265 266 267 Compiling Regular Expressions 268 ----------------------------- 269 270 Regular expressions are compiled into pattern objects, which have 271 methods for various operations such as searching for pattern matches or 272 performing string substitutions. :: 273 274 >>> import re 275 >>> p = re.compile('ab*') 276 >>> p 277 re.compile('ab*') 278 279 :func:`re.compile` also accepts an optional *flags* argument, used to enable 280 various special features and syntax variations. We'll go over the available 281 settings later, but for now a single example will do:: 282 283 >>> p = re.compile('ab*', re.IGNORECASE) 284 285 The RE is passed to :func:`re.compile` as a string. REs are handled as strings 286 because regular expressions aren't part of the core Python language, and no 287 special syntax was created for expressing them. (There are applications that 288 don't need REs at all, so there's no need to bloat the language specification by 289 including them.) Instead, the :mod:`re` module is simply a C extension module 290 included with Python, just like the :mod:`socket` or :mod:`zlib` modules. 291 292 Putting REs in strings keeps the Python language simpler, but has one 293 disadvantage which is the topic of the next section. 294 295 296 The Backslash Plague 297 -------------------- 298 299 As stated earlier, regular expressions use the backslash character (``'\'``) to 300 indicate special forms or to allow special characters to be used without 301 invoking their special meaning. This conflicts with Python's usage of the same 302 character for the same purpose in string literals. 303 304 Let's say you want to write a RE that matches the string ``\section``, which 305 might be found in a LaTeX file. To figure out what to write in the program 306 code, start with the desired string to be matched. Next, you must escape any 307 backslashes and other metacharacters by preceding them with a backslash, 308 resulting in the string ``\\section``. The resulting string that must be passed 309 to :func:`re.compile` must be ``\\section``. However, to express this as a 310 Python string literal, both backslashes must be escaped *again*. 311 312 +-------------------+------------------------------------------+ 313 | Characters | Stage | 314 +===================+==========================================+ 315 | ``\section`` | Text string to be matched | 316 +-------------------+------------------------------------------+ 317 | ``\\section`` | Escaped backslash for :func:`re.compile` | 318 +-------------------+------------------------------------------+ 319 | ``"\\\\section"`` | Escaped backslashes for a string literal | 320 +-------------------+------------------------------------------+ 321 322 In short, to match a literal backslash, one has to write ``'\\\\'`` as the RE 323 string, because the regular expression must be ``\\``, and each backslash must 324 be expressed as ``\\`` inside a regular Python string literal. In REs that 325 feature backslashes repeatedly, this leads to lots of repeated backslashes and 326 makes the resulting strings difficult to understand. 327 328 The solution is to use Python's raw string notation for regular expressions; 329 backslashes are not handled in any special way in a string literal prefixed with 330 ``'r'``, so ``r"\n"`` is a two-character string containing ``'\'`` and ``'n'``, 331 while ``"\n"`` is a one-character string containing a newline. Regular 332 expressions will often be written in Python code using this raw string notation. 333 334 +-------------------+------------------+ 335 | Regular String | Raw string | 336 +===================+==================+ 337 | ``"ab*"`` | ``r"ab*"`` | 338 +-------------------+------------------+ 339 | ``"\\\\section"`` | ``r"\\section"`` | 340 +-------------------+------------------+ 341 | ``"\\w+\\s+\\1"`` | ``r"\w+\s+\1"`` | 342 +-------------------+------------------+ 343 344 345 Performing Matches 346 ------------------ 347 348 Once you have an object representing a compiled regular expression, what do you 349 do with it? Pattern objects have several methods and attributes. 350 Only the most significant ones will be covered here; consult the :mod:`re` docs 351 for a complete listing. 352 353 +------------------+-----------------------------------------------+ 354 | Method/Attribute | Purpose | 355 +==================+===============================================+ 356 | ``match()`` | Determine if the RE matches at the beginning | 357 | | of the string. | 358 +------------------+-----------------------------------------------+ 359 | ``search()`` | Scan through a string, looking for any | 360 | | location where this RE matches. | 361 +------------------+-----------------------------------------------+ 362 | ``findall()`` | Find all substrings where the RE matches, and | 363 | | returns them as a list. | 364 +------------------+-----------------------------------------------+ 365 | ``finditer()`` | Find all substrings where the RE matches, and | 366 | | returns them as an :term:`iterator`. | 367 +------------------+-----------------------------------------------+ 368 369 :meth:`~re.regex.match` and :meth:`~re.regex.search` return ``None`` if no match can be found. If 370 they're successful, a :ref:`match object <match-objects>` instance is returned, 371 containing information about the match: where it starts and ends, the substring 372 it matched, and more. 373 374 You can learn about this by interactively experimenting with the :mod:`re` 375 module. If you have :mod:`tkinter` available, you may also want to look at 376 :source:`Tools/demo/redemo.py`, a demonstration program included with the 377 Python distribution. It allows you to enter REs and strings, and displays 378 whether the RE matches or fails. :file:`redemo.py` can be quite useful when 379 trying to debug a complicated RE. 380 381 This HOWTO uses the standard Python interpreter for its examples. First, run the 382 Python interpreter, import the :mod:`re` module, and compile a RE:: 383 384 >>> import re 385 >>> p = re.compile('[a-z]+') 386 >>> p 387 re.compile('[a-z]+') 388 389 Now, you can try matching various strings against the RE ``[a-z]+``. An empty 390 string shouldn't match at all, since ``+`` means 'one or more repetitions'. 391 :meth:`match` should return ``None`` in this case, which will cause the 392 interpreter to print no output. You can explicitly print the result of 393 :meth:`match` to make this clear. :: 394 395 >>> p.match("") 396 >>> print(p.match("")) 397 None 398 399 Now, let's try it on a string that it should match, such as ``tempo``. In this 400 case, :meth:`match` will return a :ref:`match object <match-objects>`, so you 401 should store the result in a variable for later use. :: 402 403 >>> m = p.match('tempo') 404 >>> m #doctest: +ELLIPSIS 405 <_sre.SRE_Match object; span=(0, 5), match='tempo'> 406 407 Now you can query the :ref:`match object <match-objects>` for information 408 about the matching string. :ref:`match object <match-objects>` instances 409 also have several methods and attributes; the most important ones are: 410 411 +------------------+--------------------------------------------+ 412 | Method/Attribute | Purpose | 413 +==================+============================================+ 414 | ``group()`` | Return the string matched by the RE | 415 +------------------+--------------------------------------------+ 416 | ``start()`` | Return the starting position of the match | 417 +------------------+--------------------------------------------+ 418 | ``end()`` | Return the ending position of the match | 419 +------------------+--------------------------------------------+ 420 | ``span()`` | Return a tuple containing the (start, end) | 421 | | positions of the match | 422 +------------------+--------------------------------------------+ 423 424 Trying these methods will soon clarify their meaning:: 425 426 >>> m.group() 427 'tempo' 428 >>> m.start(), m.end() 429 (0, 5) 430 >>> m.span() 431 (0, 5) 432 433 :meth:`~re.match.group` returns the substring that was matched by the RE. :meth:`~re.match.start` 434 and :meth:`~re.match.end` return the starting and ending index of the match. :meth:`~re.match.span` 435 returns both start and end indexes in a single tuple. Since the :meth:`match` 436 method only checks if the RE matches at the start of a string, :meth:`start` 437 will always be zero. However, the :meth:`search` method of patterns 438 scans through the string, so the match may not start at zero in that 439 case. :: 440 441 >>> print(p.match('::: message')) 442 None 443 >>> m = p.search('::: message'); print(m) #doctest: +ELLIPSIS 444 <_sre.SRE_Match object; span=(4, 11), match='message'> 445 >>> m.group() 446 'message' 447 >>> m.span() 448 (4, 11) 449 450 In actual programs, the most common style is to store the 451 :ref:`match object <match-objects>` in a variable, and then check if it was 452 ``None``. This usually looks like:: 453 454 p = re.compile( ... ) 455 m = p.match( 'string goes here' ) 456 if m: 457 print('Match found: ', m.group()) 458 else: 459 print('No match') 460 461 Two pattern methods return all of the matches for a pattern. 462 :meth:`~re.regex.findall` returns a list of matching strings:: 463 464 >>> p = re.compile('\d+') 465 >>> p.findall('12 drummers drumming, 11 pipers piping, 10 lords a-leaping') 466 ['12', '11', '10'] 467 468 :meth:`findall` has to create the entire list before it can be returned as the 469 result. The :meth:`~re.regex.finditer` method returns a sequence of 470 :ref:`match object <match-objects>` instances as an :term:`iterator`:: 471 472 >>> iterator = p.finditer('12 drummers drumming, 11 ... 10 ...') 473 >>> iterator #doctest: +ELLIPSIS 474 <callable_iterator object at 0x...> 475 >>> for match in iterator: 476 ... print(match.span()) 477 ... 478 (0, 2) 479 (22, 24) 480 (29, 31) 481 482 483 Module-Level Functions 484 ---------------------- 485 486 You don't have to create a pattern object and call its methods; the 487 :mod:`re` module also provides top-level functions called :func:`~re.match`, 488 :func:`~re.search`, :func:`~re.findall`, :func:`~re.sub`, and so forth. These functions 489 take the same arguments as the corresponding pattern method with 490 the RE string added as the first argument, and still return either ``None`` or a 491 :ref:`match object <match-objects>` instance. :: 492 493 >>> print(re.match(r'From\s+', 'Fromage amk')) 494 None 495 >>> re.match(r'From\s+', 'From amk Thu May 14 19:12:10 1998') #doctest: +ELLIPSIS 496 <_sre.SRE_Match object; span=(0, 5), match='From '> 497 498 Under the hood, these functions simply create a pattern object for you 499 and call the appropriate method on it. They also store the compiled 500 object in a cache, so future calls using the same RE won't need to 501 parse the pattern again and again. 502 503 Should you use these module-level functions, or should you get the 504 pattern and call its methods yourself? If you're accessing a regex 505 within a loop, pre-compiling it will save a few function calls. 506 Outside of loops, there's not much difference thanks to the internal 507 cache. 508 509 510 Compilation Flags 511 ----------------- 512 513 Compilation flags let you modify some aspects of how regular expressions work. 514 Flags are available in the :mod:`re` module under two names, a long name such as 515 :const:`IGNORECASE` and a short, one-letter form such as :const:`I`. (If you're 516 familiar with Perl's pattern modifiers, the one-letter forms use the same 517 letters; the short form of :const:`re.VERBOSE` is :const:`re.X`, for example.) 518 Multiple flags can be specified by bitwise OR-ing them; ``re.I | re.M`` sets 519 both the :const:`I` and :const:`M` flags, for example. 520 521 Here's a table of the available flags, followed by a more detailed explanation 522 of each one. 523 524 +---------------------------------+--------------------------------------------+ 525 | Flag | Meaning | 526 +=================================+============================================+ 527 | :const:`ASCII`, :const:`A` | Makes several escapes like ``\w``, ``\b``, | 528 | | ``\s`` and ``\d`` match only on ASCII | 529 | | characters with the respective property. | 530 +---------------------------------+--------------------------------------------+ 531 | :const:`DOTALL`, :const:`S` | Make ``.`` match any character, including | 532 | | newlines | 533 +---------------------------------+--------------------------------------------+ 534 | :const:`IGNORECASE`, :const:`I` | Do case-insensitive matches | 535 +---------------------------------+--------------------------------------------+ 536 | :const:`LOCALE`, :const:`L` | Do a locale-aware match | 537 +---------------------------------+--------------------------------------------+ 538 | :const:`MULTILINE`, :const:`M` | Multi-line matching, affecting ``^`` and | 539 | | ``$`` | 540 +---------------------------------+--------------------------------------------+ 541 | :const:`VERBOSE`, :const:`X` | Enable verbose REs, which can be organized | 542 | (for 'extended') | more cleanly and understandably. | 543 +---------------------------------+--------------------------------------------+ 544 545 546 .. data:: I 547 IGNORECASE 548 :noindex: 549 550 Perform case-insensitive matching; character class and literal strings will 551 match letters by ignoring case. For example, ``[A-Z]`` will match lowercase 552 letters, too, and ``Spam`` will match ``Spam``, ``spam``, or ``spAM``. This 553 lowercasing doesn't take the current locale into account; it will if you also 554 set the :const:`LOCALE` flag. 555 556 557 .. data:: L 558 LOCALE 559 :noindex: 560 561 Make ``\w``, ``\W``, ``\b``, and ``\B``, dependent on the current locale 562 instead of the Unicode database. 563 564 Locales are a feature of the C library intended to help in writing programs that 565 take account of language differences. For example, if you're processing French 566 text, you'd want to be able to write ``\w+`` to match words, but ``\w`` only 567 matches the character class ``[A-Za-z]``; it won't match ``'é'`` or ``'ç'``. If 568 your system is configured properly and a French locale is selected, certain C 569 functions will tell the program that ``'é'`` should also be considered a letter. 570 Setting the :const:`LOCALE` flag when compiling a regular expression will cause 571 the resulting compiled object to use these C functions for ``\w``; this is 572 slower, but also enables ``\w+`` to match French words as you'd expect. 573 574 575 .. data:: M 576 MULTILINE 577 :noindex: 578 579 (``^`` and ``$`` haven't been explained yet; they'll be introduced in section 580 :ref:`more-metacharacters`.) 581 582 Usually ``^`` matches only at the beginning of the string, and ``$`` matches 583 only at the end of the string and immediately before the newline (if any) at the 584 end of the string. When this flag is specified, ``^`` matches at the beginning 585 of the string and at the beginning of each line within the string, immediately 586 following each newline. Similarly, the ``$`` metacharacter matches either at 587 the end of the string and at the end of each line (immediately preceding each 588 newline). 589 590 591 .. data:: S 592 DOTALL 593 :noindex: 594 595 Makes the ``'.'`` special character match any character at all, including a 596 newline; without this flag, ``'.'`` will match anything *except* a newline. 597 598 599 .. data:: A 600 ASCII 601 :noindex: 602 603 Make ``\w``, ``\W``, ``\b``, ``\B``, ``\s`` and ``\S`` perform ASCII-only 604 matching instead of full Unicode matching. This is only meaningful for 605 Unicode patterns, and is ignored for byte patterns. 606 607 608 .. data:: X 609 VERBOSE 610 :noindex: 611 612 This flag allows you to write regular expressions that are more readable by 613 granting you more flexibility in how you can format them. When this flag has 614 been specified, whitespace within the RE string is ignored, except when the 615 whitespace is in a character class or preceded by an unescaped backslash; this 616 lets you organize and indent the RE more clearly. This flag also lets you put 617 comments within a RE that will be ignored by the engine; comments are marked by 618 a ``'#'`` that's neither in a character class or preceded by an unescaped 619 backslash. 620 621 For example, here's a RE that uses :const:`re.VERBOSE`; see how much easier it 622 is to read? :: 623 624 charref = re.compile(r""" 625 &[#] # Start of a numeric entity reference 626 ( 627 0[0-7]+ # Octal form 628 | [0-9]+ # Decimal form 629 | x[0-9a-fA-F]+ # Hexadecimal form 630 ) 631 ; # Trailing semicolon 632 """, re.VERBOSE) 633 634 Without the verbose setting, the RE would look like this:: 635 636 charref = re.compile("&#(0[0-7]+" 637 "|[0-9]+" 638 "|x[0-9a-fA-F]+);") 639 640 In the above example, Python's automatic concatenation of string literals has 641 been used to break up the RE into smaller pieces, but it's still more difficult 642 to understand than the version using :const:`re.VERBOSE`. 643 644 645 More Pattern Power 646 ================== 647 648 So far we've only covered a part of the features of regular expressions. In 649 this section, we'll cover some new metacharacters, and how to use groups to 650 retrieve portions of the text that was matched. 651 652 653 .. _more-metacharacters: 654 655 More Metacharacters 656 ------------------- 657 658 There are some metacharacters that we haven't covered yet. Most of them will be 659 covered in this section. 660 661 Some of the remaining metacharacters to be discussed are :dfn:`zero-width 662 assertions`. They don't cause the engine to advance through the string; 663 instead, they consume no characters at all, and simply succeed or fail. For 664 example, ``\b`` is an assertion that the current position is located at a word 665 boundary; the position isn't changed by the ``\b`` at all. This means that 666 zero-width assertions should never be repeated, because if they match once at a 667 given location, they can obviously be matched an infinite number of times. 668 669 ``|`` 670 Alternation, or the "or" operator. If A and B are regular expressions, 671 ``A|B`` will match any string that matches either ``A`` or ``B``. ``|`` has very 672 low precedence in order to make it work reasonably when you're alternating 673 multi-character strings. ``Crow|Servo`` will match either ``Crow`` or ``Servo``, 674 not ``Cro``, a ``'w'`` or an ``'S'``, and ``ervo``. 675 676 To match a literal ``'|'``, use ``\|``, or enclose it inside a character class, 677 as in ``[|]``. 678 679 ``^`` 680 Matches at the beginning of lines. Unless the :const:`MULTILINE` flag has been 681 set, this will only match at the beginning of the string. In :const:`MULTILINE` 682 mode, this also matches immediately after each newline within the string. 683 684 For example, if you wish to match the word ``From`` only at the beginning of a 685 line, the RE to use is ``^From``. :: 686 687 >>> print(re.search('^From', 'From Here to Eternity')) #doctest: +ELLIPSIS 688 <_sre.SRE_Match object; span=(0, 4), match='From'> 689 >>> print(re.search('^From', 'Reciting From Memory')) 690 None 691 692 .. To match a literal \character{\^}, use \regexp{\e\^} or enclose it 693 .. inside a character class, as in \regexp{[{\e}\^]}. 694 695 ``$`` 696 Matches at the end of a line, which is defined as either the end of the string, 697 or any location followed by a newline character. :: 698 699 >>> print(re.search('}$', '{block}')) #doctest: +ELLIPSIS 700 <_sre.SRE_Match object; span=(6, 7), match='}'> 701 >>> print(re.search('}$', '{block} ')) 702 None 703 >>> print(re.search('}$', '{block}\n')) #doctest: +ELLIPSIS 704 <_sre.SRE_Match object; span=(6, 7), match='}'> 705 706 To match a literal ``'$'``, use ``\$`` or enclose it inside a character class, 707 as in ``[$]``. 708 709 ``\A`` 710 Matches only at the start of the string. When not in :const:`MULTILINE` mode, 711 ``\A`` and ``^`` are effectively the same. In :const:`MULTILINE` mode, they're 712 different: ``\A`` still matches only at the beginning of the string, but ``^`` 713 may match at any location inside the string that follows a newline character. 714 715 ``\Z`` 716 Matches only at the end of the string. 717 718 ``\b`` 719 Word boundary. This is a zero-width assertion that matches only at the 720 beginning or end of a word. A word is defined as a sequence of alphanumeric 721 characters, so the end of a word is indicated by whitespace or a 722 non-alphanumeric character. 723 724 The following example matches ``class`` only when it's a complete word; it won't 725 match when it's contained inside another word. :: 726 727 >>> p = re.compile(r'\bclass\b') 728 >>> print(p.search('no class at all')) #doctest: +ELLIPSIS 729 <_sre.SRE_Match object; span=(3, 8), match='class'> 730 >>> print(p.search('the declassified algorithm')) 731 None 732 >>> print(p.search('one subclass is')) 733 None 734 735 There are two subtleties you should remember when using this special sequence. 736 First, this is the worst collision between Python's string literals and regular 737 expression sequences. In Python's string literals, ``\b`` is the backspace 738 character, ASCII value 8. If you're not using raw strings, then Python will 739 convert the ``\b`` to a backspace, and your RE won't match as you expect it to. 740 The following example looks the same as our previous RE, but omits the ``'r'`` 741 in front of the RE string. :: 742 743 >>> p = re.compile('\bclass\b') 744 >>> print(p.search('no class at all')) 745 None 746 >>> print(p.search('\b' + 'class' + '\b')) #doctest: +ELLIPSIS 747 <_sre.SRE_Match object; span=(0, 7), match='\x08class\x08'> 748 749 Second, inside a character class, where there's no use for this assertion, 750 ``\b`` represents the backspace character, for compatibility with Python's 751 string literals. 752 753 ``\B`` 754 Another zero-width assertion, this is the opposite of ``\b``, only matching when 755 the current position is not at a word boundary. 756 757 758 Grouping 759 -------- 760 761 Frequently you need to obtain more information than just whether the RE matched 762 or not. Regular expressions are often used to dissect strings by writing a RE 763 divided into several subgroups which match different components of interest. 764 For example, an RFC-822 header line is divided into a header name and a value, 765 separated by a ``':'``, like this:: 766 767 From: author@example.com 768 User-Agent: Thunderbird 1.5.0.9 (X11/20061227) 769 MIME-Version: 1.0 770 To: editor@example.com 771 772 This can be handled by writing a regular expression which matches an entire 773 header line, and has one group which matches the header name, and another group 774 which matches the header's value. 775 776 Groups are marked by the ``'('``, ``')'`` metacharacters. ``'('`` and ``')'`` 777 have much the same meaning as they do in mathematical expressions; they group 778 together the expressions contained inside them, and you can repeat the contents 779 of a group with a repeating qualifier, such as ``*``, ``+``, ``?``, or 780 ``{m,n}``. For example, ``(ab)*`` will match zero or more repetitions of 781 ``ab``. :: 782 783 >>> p = re.compile('(ab)*') 784 >>> print(p.match('ababababab').span()) 785 (0, 10) 786 787 Groups indicated with ``'('``, ``')'`` also capture the starting and ending 788 index of the text that they match; this can be retrieved by passing an argument 789 to :meth:`group`, :meth:`start`, :meth:`end`, and :meth:`span`. Groups are 790 numbered starting with 0. Group 0 is always present; it's the whole RE, so 791 :ref:`match object <match-objects>` methods all have group 0 as their default 792 argument. Later we'll see how to express groups that don't capture the span 793 of text that they match. :: 794 795 >>> p = re.compile('(a)b') 796 >>> m = p.match('ab') 797 >>> m.group() 798 'ab' 799 >>> m.group(0) 800 'ab' 801 802 Subgroups are numbered from left to right, from 1 upward. Groups can be nested; 803 to determine the number, just count the opening parenthesis characters, going 804 from left to right. :: 805 806 >>> p = re.compile('(a(b)c)d') 807 >>> m = p.match('abcd') 808 >>> m.group(0) 809 'abcd' 810 >>> m.group(1) 811 'abc' 812 >>> m.group(2) 813 'b' 814 815 :meth:`group` can be passed multiple group numbers at a time, in which case it 816 will return a tuple containing the corresponding values for those groups. :: 817 818 >>> m.group(2,1,2) 819 ('b', 'abc', 'b') 820 821 The :meth:`groups` method returns a tuple containing the strings for all the 822 subgroups, from 1 up to however many there are. :: 823 824 >>> m.groups() 825 ('abc', 'b') 826 827 Backreferences in a pattern allow you to specify that the contents of an earlier 828 capturing group must also be found at the current location in the string. For 829 example, ``\1`` will succeed if the exact contents of group 1 can be found at 830 the current position, and fails otherwise. Remember that Python's string 831 literals also use a backslash followed by numbers to allow including arbitrary 832 characters in a string, so be sure to use a raw string when incorporating 833 backreferences in a RE. 834 835 For example, the following RE detects doubled words in a string. :: 836 837 >>> p = re.compile(r'(\b\w+)\s+\1') 838 >>> p.search('Paris in the the spring').group() 839 'the the' 840 841 Backreferences like this aren't often useful for just searching through a string 842 --- there are few text formats which repeat data in this way --- but you'll soon 843 find out that they're *very* useful when performing string substitutions. 844 845 846 Non-capturing and Named Groups 847 ------------------------------ 848 849 Elaborate REs may use many groups, both to capture substrings of interest, and 850 to group and structure the RE itself. In complex REs, it becomes difficult to 851 keep track of the group numbers. There are two features which help with this 852 problem. Both of them use a common syntax for regular expression extensions, so 853 we'll look at that first. 854 855 Perl 5 is well known for its powerful additions to standard regular expressions. 856 For these new features the Perl developers couldn't choose new single-keystroke metacharacters 857 or new special sequences beginning with ``\`` without making Perl's regular 858 expressions confusingly different from standard REs. If they chose ``&`` as a 859 new metacharacter, for example, old expressions would be assuming that ``&`` was 860 a regular character and wouldn't have escaped it by writing ``\&`` or ``[&]``. 861 862 The solution chosen by the Perl developers was to use ``(?...)`` as the 863 extension syntax. ``?`` immediately after a parenthesis was a syntax error 864 because the ``?`` would have nothing to repeat, so this didn't introduce any 865 compatibility problems. The characters immediately after the ``?`` indicate 866 what extension is being used, so ``(?=foo)`` is one thing (a positive lookahead 867 assertion) and ``(?:foo)`` is something else (a non-capturing group containing 868 the subexpression ``foo``). 869 870 Python supports several of Perl's extensions and adds an extension 871 syntax to Perl's extension syntax. If the first character after the 872 question mark is a ``P``, you know that it's an extension that's 873 specific to Python. 874 875 Now that we've looked at the general extension syntax, we can return 876 to the features that simplify working with groups in complex REs. 877 878 Sometimes you'll want to use a group to denote a part of a regular expression, 879 but aren't interested in retrieving the group's contents. You can make this fact 880 explicit by using a non-capturing group: ``(?:...)``, where you can replace the 881 ``...`` with any other regular expression. :: 882 883 >>> m = re.match("([abc])+", "abc") 884 >>> m.groups() 885 ('c',) 886 >>> m = re.match("(?:[abc])+", "abc") 887 >>> m.groups() 888 () 889 890 Except for the fact that you can't retrieve the contents of what the group 891 matched, a non-capturing group behaves exactly the same as a capturing group; 892 you can put anything inside it, repeat it with a repetition metacharacter such 893 as ``*``, and nest it within other groups (capturing or non-capturing). 894 ``(?:...)`` is particularly useful when modifying an existing pattern, since you 895 can add new groups without changing how all the other groups are numbered. It 896 should be mentioned that there's no performance difference in searching between 897 capturing and non-capturing groups; neither form is any faster than the other. 898 899 A more significant feature is named groups: instead of referring to them by 900 numbers, groups can be referenced by a name. 901 902 The syntax for a named group is one of the Python-specific extensions: 903 ``(?P<name>...)``. *name* is, obviously, the name of the group. Named groups 904 behave exactly like capturing groups, and additionally associate a name 905 with a group. The :ref:`match object <match-objects>` methods that deal with 906 capturing groups all accept either integers that refer to the group by number 907 or strings that contain the desired group's name. Named groups are still 908 given numbers, so you can retrieve information about a group in two ways:: 909 910 >>> p = re.compile(r'(?P<word>\b\w+\b)') 911 >>> m = p.search( '(((( Lots of punctuation )))' ) 912 >>> m.group('word') 913 'Lots' 914 >>> m.group(1) 915 'Lots' 916 917 Named groups are handy because they let you use easily-remembered names, instead 918 of having to remember numbers. Here's an example RE from the :mod:`imaplib` 919 module:: 920 921 InternalDate = re.compile(r'INTERNALDATE "' 922 r'(?P<day>[ 123][0-9])-(?P<mon>[A-Z][a-z][a-z])-' 923 r'(?P<year>[0-9][0-9][0-9][0-9])' 924 r' (?P<hour>[0-9][0-9]):(?P<min>[0-9][0-9]):(?P<sec>[0-9][0-9])' 925 r' (?P<zonen>[-+])(?P<zoneh>[0-9][0-9])(?P<zonem>[0-9][0-9])' 926 r'"') 927 928 It's obviously much easier to retrieve ``m.group('zonem')``, instead of having 929 to remember to retrieve group 9. 930 931 The syntax for backreferences in an expression such as ``(...)\1`` refers to the 932 number of the group. There's naturally a variant that uses the group name 933 instead of the number. This is another Python extension: ``(?P=name)`` indicates 934 that the contents of the group called *name* should again be matched at the 935 current point. The regular expression for finding doubled words, 936 ``(\b\w+)\s+\1`` can also be written as ``(?P<word>\b\w+)\s+(?P=word)``:: 937 938 >>> p = re.compile(r'(?P<word>\b\w+)\s+(?P=word)') 939 >>> p.search('Paris in the the spring').group() 940 'the the' 941 942 943 Lookahead Assertions 944 -------------------- 945 946 Another zero-width assertion is the lookahead assertion. Lookahead assertions 947 are available in both positive and negative form, and look like this: 948 949 ``(?=...)`` 950 Positive lookahead assertion. This succeeds if the contained regular 951 expression, represented here by ``...``, successfully matches at the current 952 location, and fails otherwise. But, once the contained expression has been 953 tried, the matching engine doesn't advance at all; the rest of the pattern is 954 tried right where the assertion started. 955 956 ``(?!...)`` 957 Negative lookahead assertion. This is the opposite of the positive assertion; 958 it succeeds if the contained expression *doesn't* match at the current position 959 in the string. 960 961 To make this concrete, let's look at a case where a lookahead is useful. 962 Consider a simple pattern to match a filename and split it apart into a base 963 name and an extension, separated by a ``.``. For example, in ``news.rc``, 964 ``news`` is the base name, and ``rc`` is the filename's extension. 965 966 The pattern to match this is quite simple: 967 968 ``.*[.].*$`` 969 970 Notice that the ``.`` needs to be treated specially because it's a 971 metacharacter, so it's inside a character class to only match that 972 specific character. Also notice the trailing ``$``; this is added to 973 ensure that all the rest of the string must be included in the 974 extension. This regular expression matches ``foo.bar`` and 975 ``autoexec.bat`` and ``sendmail.cf`` and ``printers.conf``. 976 977 Now, consider complicating the problem a bit; what if you want to match 978 filenames where the extension is not ``bat``? Some incorrect attempts: 979 980 ``.*[.][^b].*$`` The first attempt above tries to exclude ``bat`` by requiring 981 that the first character of the extension is not a ``b``. This is wrong, 982 because the pattern also doesn't match ``foo.bar``. 983 984 ``.*[.]([^b]..|.[^a].|..[^t])$`` 985 986 The expression gets messier when you try to patch up the first solution by 987 requiring one of the following cases to match: the first character of the 988 extension isn't ``b``; the second character isn't ``a``; or the third character 989 isn't ``t``. This accepts ``foo.bar`` and rejects ``autoexec.bat``, but it 990 requires a three-letter extension and won't accept a filename with a two-letter 991 extension such as ``sendmail.cf``. We'll complicate the pattern again in an 992 effort to fix it. 993 994 ``.*[.]([^b].?.?|.[^a]?.?|..?[^t]?)$`` 995 996 In the third attempt, the second and third letters are all made optional in 997 order to allow matching extensions shorter than three characters, such as 998 ``sendmail.cf``. 999 1000 The pattern's getting really complicated now, which makes it hard to read and 1001 understand. Worse, if the problem changes and you want to exclude both ``bat`` 1002 and ``exe`` as extensions, the pattern would get even more complicated and 1003 confusing. 1004 1005 A negative lookahead cuts through all this confusion: 1006 1007 ``.*[.](?!bat$)[^.]*$`` The negative lookahead means: if the expression ``bat`` 1008 doesn't match at this point, try the rest of the pattern; if ``bat$`` does 1009 match, the whole pattern will fail. The trailing ``$`` is required to ensure 1010 that something like ``sample.batch``, where the extension only starts with 1011 ``bat``, will be allowed. The ``[^.]*`` makes sure that the pattern works 1012 when there are multiple dots in the filename. 1013 1014 Excluding another filename extension is now easy; simply add it as an 1015 alternative inside the assertion. The following pattern excludes filenames that 1016 end in either ``bat`` or ``exe``: 1017 1018 ``.*[.](?!bat$|exe$)[^.]*$`` 1019 1020 1021 Modifying Strings 1022 ================= 1023 1024 Up to this point, we've simply performed searches against a static string. 1025 Regular expressions are also commonly used to modify strings in various ways, 1026 using the following pattern methods: 1027 1028 +------------------+-----------------------------------------------+ 1029 | Method/Attribute | Purpose | 1030 +==================+===============================================+ 1031 | ``split()`` | Split the string into a list, splitting it | 1032 | | wherever the RE matches | 1033 +------------------+-----------------------------------------------+ 1034 | ``sub()`` | Find all substrings where the RE matches, and | 1035 | | replace them with a different string | 1036 +------------------+-----------------------------------------------+ 1037 | ``subn()`` | Does the same thing as :meth:`sub`, but | 1038 | | returns the new string and the number of | 1039 | | replacements | 1040 +------------------+-----------------------------------------------+ 1041 1042 1043 Splitting Strings 1044 ----------------- 1045 1046 The :meth:`split` method of a pattern splits a string apart 1047 wherever the RE matches, returning a list of the pieces. It's similar to the 1048 :meth:`split` method of strings but provides much more generality in the 1049 delimiters that you can split by; string :meth:`split` only supports splitting by 1050 whitespace or by a fixed string. As you'd expect, there's a module-level 1051 :func:`re.split` function, too. 1052 1053 1054 .. method:: .split(string [, maxsplit=0]) 1055 :noindex: 1056 1057 Split *string* by the matches of the regular expression. If capturing 1058 parentheses are used in the RE, then their contents will also be returned as 1059 part of the resulting list. If *maxsplit* is nonzero, at most *maxsplit* splits 1060 are performed. 1061 1062 You can limit the number of splits made, by passing a value for *maxsplit*. 1063 When *maxsplit* is nonzero, at most *maxsplit* splits will be made, and the 1064 remainder of the string is returned as the final element of the list. In the 1065 following example, the delimiter is any sequence of non-alphanumeric characters. 1066 :: 1067 1068 >>> p = re.compile(r'\W+') 1069 >>> p.split('This is a test, short and sweet, of split().') 1070 ['This', 'is', 'a', 'test', 'short', 'and', 'sweet', 'of', 'split', ''] 1071 >>> p.split('This is a test, short and sweet, of split().', 3) 1072 ['This', 'is', 'a', 'test, short and sweet, of split().'] 1073 1074 Sometimes you're not only interested in what the text between delimiters is, but 1075 also need to know what the delimiter was. If capturing parentheses are used in 1076 the RE, then their values are also returned as part of the list. Compare the 1077 following calls:: 1078 1079 >>> p = re.compile(r'\W+') 1080 >>> p2 = re.compile(r'(\W+)') 1081 >>> p.split('This... is a test.') 1082 ['This', 'is', 'a', 'test', ''] 1083 >>> p2.split('This... is a test.') 1084 ['This', '... ', 'is', ' ', 'a', ' ', 'test', '.', ''] 1085 1086 The module-level function :func:`re.split` adds the RE to be used as the first 1087 argument, but is otherwise the same. :: 1088 1089 >>> re.split('[\W]+', 'Words, words, words.') 1090 ['Words', 'words', 'words', ''] 1091 >>> re.split('([\W]+)', 'Words, words, words.') 1092 ['Words', ', ', 'words', ', ', 'words', '.', ''] 1093 >>> re.split('[\W]+', 'Words, words, words.', 1) 1094 ['Words', 'words, words.'] 1095 1096 1097 Search and Replace 1098 ------------------ 1099 1100 Another common task is to find all the matches for a pattern, and replace them 1101 with a different string. The :meth:`sub` method takes a replacement value, 1102 which can be either a string or a function, and the string to be processed. 1103 1104 .. method:: .sub(replacement, string[, count=0]) 1105 :noindex: 1106 1107 Returns the string obtained by replacing the leftmost non-overlapping 1108 occurrences of the RE in *string* by the replacement *replacement*. If the 1109 pattern isn't found, *string* is returned unchanged. 1110 1111 The optional argument *count* is the maximum number of pattern occurrences to be 1112 replaced; *count* must be a non-negative integer. The default value of 0 means 1113 to replace all occurrences. 1114 1115 Here's a simple example of using the :meth:`sub` method. It replaces colour 1116 names with the word ``colour``:: 1117 1118 >>> p = re.compile('(blue|white|red)') 1119 >>> p.sub('colour', 'blue socks and red shoes') 1120 'colour socks and colour shoes' 1121 >>> p.sub('colour', 'blue socks and red shoes', count=1) 1122 'colour socks and red shoes' 1123 1124 The :meth:`subn` method does the same work, but returns a 2-tuple containing the 1125 new string value and the number of replacements that were performed:: 1126 1127 >>> p = re.compile('(blue|white|red)') 1128 >>> p.subn('colour', 'blue socks and red shoes') 1129 ('colour socks and colour shoes', 2) 1130 >>> p.subn('colour', 'no colours at all') 1131 ('no colours at all', 0) 1132 1133 Empty matches are replaced only when they're not adjacent to a previous match. 1134 :: 1135 1136 >>> p = re.compile('x*') 1137 >>> p.sub('-', 'abxd') 1138 '-a-b-d-' 1139 1140 If *replacement* is a string, any backslash escapes in it are processed. That 1141 is, ``\n`` is converted to a single newline character, ``\r`` is converted to a 1142 carriage return, and so forth. Unknown escapes such as ``\&`` are left alone. 1143 Backreferences, such as ``\6``, are replaced with the substring matched by the 1144 corresponding group in the RE. This lets you incorporate portions of the 1145 original text in the resulting replacement string. 1146 1147 This example matches the word ``section`` followed by a string enclosed in 1148 ``{``, ``}``, and changes ``section`` to ``subsection``:: 1149 1150 >>> p = re.compile('section{ ( [^}]* ) }', re.VERBOSE) 1151 >>> p.sub(r'subsection{\1}','section{First} section{second}') 1152 'subsection{First} subsection{second}' 1153 1154 There's also a syntax for referring to named groups as defined by the 1155 ``(?P<name>...)`` syntax. ``\g<name>`` will use the substring matched by the 1156 group named ``name``, and ``\g<number>`` uses the corresponding group number. 1157 ``\g<2>`` is therefore equivalent to ``\2``, but isn't ambiguous in a 1158 replacement string such as ``\g<2>0``. (``\20`` would be interpreted as a 1159 reference to group 20, not a reference to group 2 followed by the literal 1160 character ``'0'``.) The following substitutions are all equivalent, but use all 1161 three variations of the replacement string. :: 1162 1163 >>> p = re.compile('section{ (?P<name> [^}]* ) }', re.VERBOSE) 1164 >>> p.sub(r'subsection{\1}','section{First}') 1165 'subsection{First}' 1166 >>> p.sub(r'subsection{\g<1>}','section{First}') 1167 'subsection{First}' 1168 >>> p.sub(r'subsection{\g<name>}','section{First}') 1169 'subsection{First}' 1170 1171 *replacement* can also be a function, which gives you even more control. If 1172 *replacement* is a function, the function is called for every non-overlapping 1173 occurrence of *pattern*. On each call, the function is passed a 1174 :ref:`match object <match-objects>` argument for the match and can use this 1175 information to compute the desired replacement string and return it. 1176 1177 In the following example, the replacement function translates decimals into 1178 hexadecimal:: 1179 1180 >>> def hexrepl(match): 1181 ... "Return the hex string for a decimal number" 1182 ... value = int(match.group()) 1183 ... return hex(value) 1184 ... 1185 >>> p = re.compile(r'\d+') 1186 >>> p.sub(hexrepl, 'Call 65490 for printing, 49152 for user code.') 1187 'Call 0xffd2 for printing, 0xc000 for user code.' 1188 1189 When using the module-level :func:`re.sub` function, the pattern is passed as 1190 the first argument. The pattern may be provided as an object or as a string; if 1191 you need to specify regular expression flags, you must either use a 1192 pattern object as the first parameter, or use embedded modifiers in the 1193 pattern string, e.g. ``sub("(?i)b+", "x", "bbbb BBBB")`` returns ``'x x'``. 1194 1195 1196 Common Problems 1197 =============== 1198 1199 Regular expressions are a powerful tool for some applications, but in some ways 1200 their behaviour isn't intuitive and at times they don't behave the way you may 1201 expect them to. This section will point out some of the most common pitfalls. 1202 1203 1204 Use String Methods 1205 ------------------ 1206 1207 Sometimes using the :mod:`re` module is a mistake. If you're matching a fixed 1208 string, or a single character class, and you're not using any :mod:`re` features 1209 such as the :const:`IGNORECASE` flag, then the full power of regular expressions 1210 may not be required. Strings have several methods for performing operations with 1211 fixed strings and they're usually much faster, because the implementation is a 1212 single small C loop that's been optimized for the purpose, instead of the large, 1213 more generalized regular expression engine. 1214 1215 One example might be replacing a single fixed string with another one; for 1216 example, you might replace ``word`` with ``deed``. ``re.sub()`` seems like the 1217 function to use for this, but consider the :meth:`replace` method. Note that 1218 :func:`replace` will also replace ``word`` inside words, turning ``swordfish`` 1219 into ``sdeedfish``, but the naive RE ``word`` would have done that, too. (To 1220 avoid performing the substitution on parts of words, the pattern would have to 1221 be ``\bword\b``, in order to require that ``word`` have a word boundary on 1222 either side. This takes the job beyond :meth:`replace`'s abilities.) 1223 1224 Another common task is deleting every occurrence of a single character from a 1225 string or replacing it with another single character. You might do this with 1226 something like ``re.sub('\n', ' ', S)``, but :meth:`translate` is capable of 1227 doing both tasks and will be faster than any regular expression operation can 1228 be. 1229 1230 In short, before turning to the :mod:`re` module, consider whether your problem 1231 can be solved with a faster and simpler string method. 1232 1233 1234 match() versus search() 1235 ----------------------- 1236 1237 The :func:`match` function only checks if the RE matches at the beginning of the 1238 string while :func:`search` will scan forward through the string for a match. 1239 It's important to keep this distinction in mind. Remember, :func:`match` will 1240 only report a successful match which will start at 0; if the match wouldn't 1241 start at zero, :func:`match` will *not* report it. :: 1242 1243 >>> print(re.match('super', 'superstition').span()) 1244 (0, 5) 1245 >>> print(re.match('super', 'insuperable')) 1246 None 1247 1248 On the other hand, :func:`search` will scan forward through the string, 1249 reporting the first match it finds. :: 1250 1251 >>> print(re.search('super', 'superstition').span()) 1252 (0, 5) 1253 >>> print(re.search('super', 'insuperable').span()) 1254 (2, 7) 1255 1256 Sometimes you'll be tempted to keep using :func:`re.match`, and just add ``.*`` 1257 to the front of your RE. Resist this temptation and use :func:`re.search` 1258 instead. The regular expression compiler does some analysis of REs in order to 1259 speed up the process of looking for a match. One such analysis figures out what 1260 the first character of a match must be; for example, a pattern starting with 1261 ``Crow`` must match starting with a ``'C'``. The analysis lets the engine 1262 quickly scan through the string looking for the starting character, only trying 1263 the full match if a ``'C'`` is found. 1264 1265 Adding ``.*`` defeats this optimization, requiring scanning to the end of the 1266 string and then backtracking to find a match for the rest of the RE. Use 1267 :func:`re.search` instead. 1268 1269 1270 Greedy versus Non-Greedy 1271 ------------------------ 1272 1273 When repeating a regular expression, as in ``a*``, the resulting action is to 1274 consume as much of the pattern as possible. This fact often bites you when 1275 you're trying to match a pair of balanced delimiters, such as the angle brackets 1276 surrounding an HTML tag. The naive pattern for matching a single HTML tag 1277 doesn't work because of the greedy nature of ``.*``. :: 1278 1279 >>> s = '<html><head><title>Title</title>' 1280 >>> len(s) 1281 32 1282 >>> print(re.match('<.*>', s).span()) 1283 (0, 32) 1284 >>> print(re.match('<.*>', s).group()) 1285 <html><head><title>Title</title> 1286 1287 The RE matches the ``'<'`` in ``<html>``, and the ``.*`` consumes the rest of 1288 the string. There's still more left in the RE, though, and the ``>`` can't 1289 match at the end of the string, so the regular expression engine has to 1290 backtrack character by character until it finds a match for the ``>``. The 1291 final match extends from the ``'<'`` in ``<html>`` to the ``'>'`` in 1292 ``</title>``, which isn't what you want. 1293 1294 In this case, the solution is to use the non-greedy qualifiers ``*?``, ``+?``, 1295 ``??``, or ``{m,n}?``, which match as *little* text as possible. In the above 1296 example, the ``'>'`` is tried immediately after the first ``'<'`` matches, and 1297 when it fails, the engine advances a character at a time, retrying the ``'>'`` 1298 at every step. This produces just the right result:: 1299 1300 >>> print(re.match('<.*?>', s).group()) 1301 <html> 1302 1303 (Note that parsing HTML or XML with regular expressions is painful. 1304 Quick-and-dirty patterns will handle common cases, but HTML and XML have special 1305 cases that will break the obvious regular expression; by the time you've written 1306 a regular expression that handles all of the possible cases, the patterns will 1307 be *very* complicated. Use an HTML or XML parser module for such tasks.) 1308 1309 1310 Using re.VERBOSE 1311 ---------------- 1312 1313 By now you've probably noticed that regular expressions are a very compact 1314 notation, but they're not terribly readable. REs of moderate complexity can 1315 become lengthy collections of backslashes, parentheses, and metacharacters, 1316 making them difficult to read and understand. 1317 1318 For such REs, specifying the ``re.VERBOSE`` flag when compiling the regular 1319 expression can be helpful, because it allows you to format the regular 1320 expression more clearly. 1321 1322 The ``re.VERBOSE`` flag has several effects. Whitespace in the regular 1323 expression that *isn't* inside a character class is ignored. This means that an 1324 expression such as ``dog | cat`` is equivalent to the less readable ``dog|cat``, 1325 but ``[a b]`` will still match the characters ``'a'``, ``'b'``, or a space. In 1326 addition, you can also put comments inside a RE; comments extend from a ``#`` 1327 character to the next newline. When used with triple-quoted strings, this 1328 enables REs to be formatted more neatly:: 1329 1330 pat = re.compile(r""" 1331 \s* # Skip leading whitespace 1332 (?P<header>[^:]+) # Header name 1333 \s* : # Whitespace, and a colon 1334 (?P<value>.*?) # The header's value -- *? used to 1335 # lose the following trailing whitespace 1336 \s*$ # Trailing whitespace to end-of-line 1337 """, re.VERBOSE) 1338 1339 This is far more readable than:: 1340 1341 pat = re.compile(r"\s*(?P<header>[^:]+)\s*:(?P<value>.*?)\s*$") 1342 1343 1344 Feedback 1345 ======== 1346 1347 Regular expressions are a complicated topic. Did this document help you 1348 understand them? Were there parts that were unclear, or Problems you 1349 encountered that weren't covered here? If so, please send suggestions for 1350 improvements to the author. 1351 1352 The most complete book on regular expressions is almost certainly Jeffrey 1353 Friedl's Mastering Regular Expressions, published by O'Reilly. Unfortunately, 1354 it exclusively concentrates on Perl and Java's flavours of regular expressions, 1355 and doesn't contain any Python material at all, so it won't be useful as a 1356 reference for programming in Python. (The first edition covered Python's 1357 now-removed :mod:`regex` module, which won't help you much.) Consider checking 1358 it out from your library. 1359