1<refentry id="glib-regex-syntax" revision="11 Jul 2006"> 2<refmeta> 3<refentrytitle>Regular expression syntax</refentrytitle> 4</refmeta> 5 6<!-- 7Based on the man page for pcrepattern. 8 9Remember to sync this document with the file docs/pcrepattern.3 in the 10pcre package when upgrading to a newer version of pcre. 11 12In sync with PCRE 7.0 13--> 14 15<refnamediv> 16<refname>Regular expression syntax</refname> 17<refpurpose> 18Syntax and semantics of the regular expressions supported by GRegex 19</refpurpose> 20</refnamediv> 21 22<refsect1> 23<title>GRegex regular expression details</title> 24<para> 25A regular expression is a pattern that is matched against a 26string from left to right. Most characters stand for themselves in a 27pattern, and match the corresponding characters in the string. As a 28trivial example, the pattern 29</para> 30 31<programlisting> 32The quick brown fox 33</programlisting> 34 35<para> 36matches a portion of a string that is identical to itself. When 37caseless matching is specified (the <varname>G_REGEX_CASELESS</varname> flag), letters are 38matched independently of case. 39</para> 40 41<para> 42The power of regular expressions comes from the ability to include 43alternatives and repetitions in the pattern. These are encoded in the 44pattern by the use of metacharacters, which do not stand for themselves 45but instead are interpreted in some special way. 46</para> 47 48<para> 49There are two different sets of metacharacters: those that are recognized 50anywhere in the pattern except within square brackets, and those 51that are recognized in square brackets. Outside square brackets, the 52metacharacters are as follows: 53</para> 54 55<table frame="all" colsep="1" rowsep="1"> 56<title>Metacharacters outside square brackets</title> 57<tgroup cols="2"> 58<colspec colnum="1" align="center"/> 59<thead> 60 <row> 61 <entry>Character</entry> 62 <entry>Meaning</entry> 63 </row> 64</thead> 65<tbody> 66 <row> 67 <entry>\</entry> 68 <entry>general escape character with several uses</entry> 69 </row> 70 <row> 71 <entry>^</entry> 72 <entry>assert start of string (or line, in multiline mode)</entry> 73 </row> 74 <row> 75 <entry>$</entry> 76 <entry>assert end of string (or line, in multiline mode)</entry> 77 </row> 78 <row> 79 <entry>.</entry> 80 <entry>match any character except newline (by default)</entry> 81 </row> 82 <row> 83 <entry>[</entry> 84 <entry>start character class definition</entry> 85 </row> 86 <row> 87 <entry>|</entry> 88 <entry>start of alternative branch</entry> 89 </row> 90 <row> 91 <entry>(</entry> 92 <entry>start subpattern</entry> 93 </row> 94 <row> 95 <entry>)</entry> 96 <entry>end subpattern</entry> 97 </row> 98 <row> 99 <entry>?</entry> 100 <entry>extends the meaning of (, or 0/1 quantifier, or quantifier minimizer</entry> 101 </row> 102 <row> 103 <entry>*</entry> 104 <entry>0 or more quantifier</entry> 105 </row> 106 <row> 107 <entry>+</entry> 108 <entry>1 or more quantifier, also "possessive quantifier"</entry> 109 </row> 110 <row> 111 <entry>{</entry> 112 <entry>start min/max quantifier</entry> 113 </row> 114</tbody> 115</tgroup> 116</table> 117 118<para> 119Part of a pattern that is in square brackets is called a "character 120class". In a character class the only metacharacters are: 121</para> 122 123<table frame="all" colsep="1" rowsep="1"> 124<title>Metacharacters inside square brackets</title> 125<tgroup cols="2"> 126<colspec colnum="1" align="center"/> 127<thead> 128 <row> 129 <entry>Character</entry> 130 <entry>Meaning</entry> 131 </row> 132</thead> 133<tbody> 134 <row> 135 <entry>\</entry> 136 <entry>general escape character</entry> 137 </row> 138 <row> 139 <entry>^</entry> 140 <entry>negate the class, but only if the first character</entry> 141 </row> 142 <row> 143 <entry>-</entry> 144 <entry>indicates character range</entry> 145 </row> 146 <row> 147 <entry>[</entry> 148 <entry>POSIX character class (only if followed by POSIX syntax)</entry> 149 </row> 150 <row> 151 <entry>]</entry> 152 <entry>terminates the character class</entry> 153 </row> 154</tbody> 155</tgroup> 156</table> 157</refsect1> 158 159<refsect1> 160<title>Backslash</title> 161<para> 162The backslash character has several uses. Firstly, if it is followed by 163a non-alphanumeric character, it takes away any special meaning that 164character may have. This use of backslash as an escape character 165applies both inside and outside character classes. 166</para> 167 168<para> 169For example, if you want to match a * character, you write \* in the 170pattern. This escaping action applies whether or not the following 171character would otherwise be interpreted as a metacharacter, so it is 172always safe to precede a non-alphanumeric with backslash to specify 173that it stands for itself. In particular, if you want to match a 174backslash, you write \\. 175</para> 176 177<para> 178If a pattern is compiled with the <varname>G_REGEX_EXTENDED</varname> 179option, whitespace in the pattern (other than in a character class) and 180characters between a # outside a character class and the next newline 181are ignored. 182An escaping backslash can be used to include a whitespace or # character 183as part of the pattern. 184</para> 185 186<para> 187If you want to remove the special meaning from a sequence of characters, 188you can do so by putting them between \Q and \E. 189The \Q...\E sequence is recognized both inside and outside character 190classes. 191</para> 192 193<refsect2> 194<title>Non-printing characters</title> 195<para> 196A second use of backslash provides a way of encoding non-printing 197characters in patterns in a visible manner. There is no restriction on the 198appearance of non-printing characters, apart from the binary zero that 199terminates a pattern, but when a pattern is being prepared by text 200editing, it is usually easier to use one of the following escape 201sequences than the binary character it represents: 202</para> 203 204<table frame="all" colsep="1" rowsep="1"> 205<title>Non-printing characters</title> 206<tgroup cols="2"> 207<colspec colnum="1" align="center"/> 208<thead> 209 <row> 210 <entry>Escape</entry> 211 <entry>Meaning</entry> 212 </row> 213</thead> 214<tbody> 215 <row> 216 <entry>\a</entry> 217 <entry>alarm, that is, the BEL character (hex 07)</entry> 218 </row> 219 <row> 220 <entry>\cx</entry> 221 <entry>"control-x", where x is any character</entry> 222 </row> 223 <row> 224 <entry>\e</entry> 225 <entry>escape (hex 1B)</entry> 226 </row> 227 <row> 228 <entry>\f</entry> 229 <entry>formfeed (hex 0C)</entry> 230 </row> 231 <row> 232 <entry>\n</entry> 233 <entry>newline (hex 0A)</entry> 234 </row> 235 <row> 236 <entry>\r</entry> 237 <entry>carriage return (hex 0D)</entry> 238 </row> 239 <row> 240 <entry>\t</entry> 241 <entry>tab (hex 09)</entry> 242 </row> 243 <row> 244 <entry>\ddd</entry> 245 <entry>character with octal code ddd, or backreference</entry> 246 </row> 247 <row> 248 <entry>\xhh</entry> 249 <entry>character with hex code hh</entry> 250 </row> 251 <row> 252 <entry>\x{hhh..}</entry> 253 <entry>character with hex code hhh..</entry> 254 </row> 255</tbody> 256</tgroup> 257</table> 258 259<para> 260The precise effect of \cx is as follows: if x is a lower case letter, 261it is converted to upper case. Then bit 6 of the character (hex 40) is 262inverted. Thus \cz becomes hex 1A, but \c{ becomes hex 3B, while \c; 263becomes hex 7B. 264</para> 265 266<para> 267After \x, from zero to two hexadecimal digits are read (letters can be 268in upper or lower case). Any number of hexadecimal digits may appear 269between \x{ and }, but the value of the character code 270must be less than 2**31 (that is, the maximum hexadecimal value is 2717FFFFFFF). If characters other than hexadecimal digits appear between 272\x{ and }, or if there is no terminating }, this form of escape is not 273recognized. Instead, the initial \x will be interpreted as a basic hexadecimal 274escape, with no following digits, giving a character whose 275value is zero. 276</para> 277 278<para> 279Characters whose value is less than 256 can be defined by either of the 280two syntaxes for \x. There is no difference 281in the way they are handled. For example, \xdc is exactly the same as 282\x{dc}. 283</para> 284 285<para> 286After \0 up to two further octal digits are read. If there are fewer 287than two digits, just those that are present are used. 288Thus the sequence \0\x\07 specifies two binary zeros followed by a BEL 289character (code value 7). Make sure you supply two digits after the 290initial zero if the pattern character that follows is itself an octal 291digit. 292</para> 293 294<para> 295The handling of a backslash followed by a digit other than 0 is complicated. 296Outside a character class, GRegex reads it and any following digits as a 297decimal number. If the number is less than 10, or if there 298have been at least that many previous capturing left parentheses in the 299expression, the entire sequence is taken as a back reference. A 300description of how this works is given later, following the discussion 301of parenthesized subpatterns. 302</para> 303 304<para> 305Inside a character class, or if the decimal number is greater than 9 306and there have not been that many capturing subpatterns, GRegex re-reads 307up to three octal digits following the backslash, and uses them to generate 308a data character. Any subsequent digits stand for themselves. For example: 309</para> 310 311<table frame="all" colsep="1" rowsep="1"> 312<title>Non-printing characters</title> 313<tgroup cols="2"> 314<colspec colnum="1" align="center"/> 315<thead> 316 <row> 317 <entry>Escape</entry> 318 <entry>Meaning</entry> 319 </row> 320</thead> 321<tbody> 322 <row> 323 <entry>\040</entry> 324 <entry>is another way of writing a space</entry> 325 </row> 326 <row> 327 <entry>\40</entry> 328 <entry>is the same, provided there are fewer than 40 previous capturing subpatterns</entry> 329 </row> 330 <row> 331 <entry>\7</entry> 332 <entry>is always a back reference</entry> 333 </row> 334 <row> 335 <entry>\11</entry> 336 <entry>might be a back reference, or another way of writing a tab</entry> 337 </row> 338 <row> 339 <entry>\011</entry> 340 <entry>is always a tab</entry> 341 </row> 342 <row> 343 <entry>\0113</entry> 344 <entry>is a tab followed by the character "3"</entry> 345 </row> 346 <row> 347 <entry>\113</entry> 348 <entry>might be a back reference, otherwise the character with octal code 113</entry> 349 </row> 350 <row> 351 <entry>\377</entry> 352 <entry>might be a back reference, otherwise the byte consisting entirely of 1 bits</entry> 353 </row> 354 <row> 355 <entry>\81</entry> 356 <entry>is either a back reference, or a binary zero followed by the two characters "8" and "1"</entry> 357 </row> 358</tbody> 359</tgroup> 360</table> 361 362<para> 363Note that octal values of 100 or greater must not be introduced by a 364leading zero, because no more than three octal digits are ever read. 365</para> 366 367<para> 368All the sequences that define a single character can be used both inside 369and outside character classes. In addition, inside a character class, the 370sequence \b is interpreted as the backspace character (hex 08), and the 371sequences \R and \X are interpreted as the characters "R" and "X", respectively. 372Outside a character class, these sequences have different meanings (see below). 373</para> 374</refsect2> 375 376<refsect2> 377<title>Absolute and relative back references</title> 378<para> 379The sequence \g followed by a positive or negative number, optionally enclosed 380in braces, is an absolute or relative back reference. Back references are 381discussed later, following the discussion of parenthesized subpatterns. 382</para> 383</refsect2> 384 385<refsect2> 386<title>Generic character types</title> 387 388<para> 389Another use of backslash is for specifying generic character types. 390The following are always recognized: 391</para> 392 393<table frame="all" colsep="1" rowsep="1"> 394<title>Generic characters</title> 395<tgroup cols="2"> 396<colspec colnum="1" align="center"/> 397<thead> 398 <row> 399 <entry>Escape</entry> 400 <entry>Meaning</entry> 401 </row> 402</thead> 403<tbody> 404 <row> 405 <entry>\d</entry> 406 <entry>any decimal digit</entry> 407 </row> 408 <row> 409 <entry>\D</entry> 410 <entry>any character that is not a decimal digit</entry> 411 </row> 412 <row> 413 <entry>\s</entry> 414 <entry>any whitespace character</entry> 415 </row> 416 <row> 417 <entry>\S</entry> 418 <entry>any character that is not a whitespace character</entry> 419 </row> 420 <row> 421 <entry>\w</entry> 422 <entry>any "word" character</entry> 423 </row> 424 <row> 425 <entry>\W</entry> 426 <entry>any "non-word" character</entry> 427 </row> 428</tbody> 429</tgroup> 430</table> 431 432<para> 433Each pair of escape sequences partitions the complete set of characters 434into two disjoint sets. Any given character matches one, and only one, 435of each pair. 436</para> 437 438<para> 439These character type sequences can appear both inside and outside character 440classes. They each match one character of the appropriate type. 441If the current matching point is at the end of the passed string, all 442of them fail, since there is no character to match. 443</para> 444 445<para> 446For compatibility with Perl, \s does not match the VT character (code 44711). This makes it different from the the POSIX "space" class. The \s 448characters are HT (9), LF (10), FF (12), CR (13), and space (32). 449</para> 450 451<para> 452A "word" character is an underscore or any character less than 256 that 453is a letter or digit.</para> 454 455<para> 456Characters with values greater than 128 never match \d, 457\s, or \w, and always match \D, \S, and \W. 458</para> 459</refsect2> 460 461<refsect2> 462<title>Newline sequences</title> 463<para>Outside a character class, the escape sequence \R matches any Unicode 464newline sequence. 465This particular group matches either the two-character sequence CR followed by 466LF, or one of the single characters LF (linefeed, U+000A), VT (vertical tab, 467U+000B), FF (formfeed, U+000C), CR (carriage return, U+000D), NEL (next 468line, U+0085), LS (line separator, U+2028), or PS (paragraph separator, U+2029). 469The two-character sequence is treated as a single unit that 470cannot be split. Inside a character class, \R matches the letter "R".</para> 471</refsect2> 472 473<refsect2> 474<title>Unicode character properties</title> 475<para> 476To support generic character types there are three additional escape 477sequences, they are: 478</para> 479 480<table frame="all" colsep="1" rowsep="1"> 481<title>Generic character types</title> 482<tgroup cols="2"> 483<colspec colnum="1" align="center"/> 484<thead> 485 <row> 486 <entry>Escape</entry> 487 <entry>Meaning</entry> 488 </row> 489</thead> 490<tbody> 491 <row> 492 <entry>\p{xx}</entry> 493 <entry>a character with the xx property</entry> 494 </row> 495 <row> 496 <entry>\P{xx}</entry> 497 <entry>a character without the xx property</entry> 498 </row> 499 <row> 500 <entry>\X</entry> 501 <entry>an extended Unicode sequence</entry> 502 </row> 503</tbody> 504</tgroup> 505</table> 506 507<para> 508The property names represented by xx above are limited to the Unicode 509script names, the general category properties, and "Any", which matches 510any character (including newline). Other properties such as "InMusicalSymbols" 511are not currently supported. Note that \P{Any} does not match any characters, 512so always causes a match failure. 513</para> 514 515<para> 516Sets of Unicode characters are defined as belonging to certain scripts. A 517character from one of these sets can be matched using a script name. For 518example, \p{Greek} or \P{Han}. 519</para> 520 521<para> 522Those that are not part of an identified script are lumped together as 523"Common". The current list of scripts is: 524</para> 525 526<itemizedlist> 527<listitem><para>Arabic</para></listitem> 528<listitem><para>Armenian</para></listitem> 529<listitem><para>Balinese</para></listitem> 530<listitem><para>Bengali</para></listitem> 531<listitem><para>Bopomofo</para></listitem> 532<listitem><para>Braille</para></listitem> 533<listitem><para>Buginese</para></listitem> 534<listitem><para>Buhid</para></listitem> 535<listitem><para>Canadian_Aboriginal</para></listitem> 536<listitem><para>Cherokee</para></listitem> 537<listitem><para>Common</para></listitem> 538<listitem><para>Coptic</para></listitem> 539<listitem><para>Cuneiform</para></listitem> 540<listitem><para>Cypriot</para></listitem> 541<listitem><para>Cyrillic</para></listitem> 542<listitem><para>Deseret</para></listitem> 543<listitem><para>Devanagari</para></listitem> 544<listitem><para>Ethiopic</para></listitem> 545<listitem><para>Georgian</para></listitem> 546<listitem><para>Glagolitic</para></listitem> 547<listitem><para>Gothic</para></listitem> 548<listitem><para>Greek</para></listitem> 549<listitem><para>Gujarati</para></listitem> 550<listitem><para>Gurmukhi</para></listitem> 551<listitem><para>Han</para></listitem> 552<listitem><para>Hangul</para></listitem> 553<listitem><para>Hanunoo</para></listitem> 554<listitem><para>Hebrew</para></listitem> 555<listitem><para>Hiragana</para></listitem> 556<listitem><para>Inherited</para></listitem> 557<listitem><para>Kannada</para></listitem> 558<listitem><para>Katakana</para></listitem> 559<listitem><para>Kharoshthi</para></listitem> 560<listitem><para>Khmer</para></listitem> 561<listitem><para>Lao</para></listitem> 562<listitem><para>Latin</para></listitem> 563<listitem><para>Limbu</para></listitem> 564<listitem><para>Linear_B</para></listitem> 565<listitem><para>Malayalam</para></listitem> 566<listitem><para>Mongolian</para></listitem> 567<listitem><para>Myanmar</para></listitem> 568<listitem><para>New_Tai_Lue</para></listitem> 569<listitem><para>Nko</para></listitem> 570<listitem><para>Ogham</para></listitem> 571<listitem><para>Old_Italic</para></listitem> 572<listitem><para>Old_Persian</para></listitem> 573<listitem><para>Oriya</para></listitem> 574<listitem><para>Osmanya</para></listitem> 575<listitem><para>Phags_Pa</para></listitem> 576<listitem><para>Phoenician</para></listitem> 577<listitem><para>Runic</para></listitem> 578<listitem><para>Shavian</para></listitem> 579<listitem><para>Sinhala</para></listitem> 580<listitem><para>Syloti_Nagri</para></listitem> 581<listitem><para>Syriac</para></listitem> 582<listitem><para>Tagalog</para></listitem> 583<listitem><para>Tagbanwa</para></listitem> 584<listitem><para>Tai_Le</para></listitem> 585<listitem><para>Tamil</para></listitem> 586<listitem><para>Telugu</para></listitem> 587<listitem><para>Thaana</para></listitem> 588<listitem><para>Thai</para></listitem> 589<listitem><para>Tibetan</para></listitem> 590<listitem><para>Tifinagh</para></listitem> 591<listitem><para>Ugaritic</para></listitem> 592<listitem><para>Yi</para></listitem> 593</itemizedlist> 594 595<para> 596Each character has exactly one general category property, specified by a 597two-letter abbreviation. For compatibility with Perl, negation can be specified 598by including a circumflex between the opening brace and the property name. For 599example, \p{^Lu} is the same as \P{Lu}. 600</para> 601 602<para> 603If only one letter is specified with \p or \P, it includes all the general 604category properties that start with that letter. In this case, in the absence 605of negation, the curly brackets in the escape sequence are optional; these two 606examples have the same effect: 607</para> 608 609<programlisting> 610\p{L} 611\pL 612</programlisting> 613 614<para> 615The following general category property codes are supported: 616</para> 617 618<table frame="all" colsep="1" rowsep="1"> 619<title>Property codes</title> 620<tgroup cols="2"> 621<colspec colnum="1" align="center"/> 622<thead> 623 <row> 624 <entry>Code</entry> 625 <entry>Meaning</entry> 626 </row> 627</thead> 628<tbody> 629 <row> 630 <entry>C</entry> 631 <entry>Other</entry> 632 </row> 633 <row> 634 <entry>Cc</entry> 635 <entry>Control</entry> 636 </row> 637 <row> 638 <entry>Cf</entry> 639 <entry>Format</entry> 640 </row> 641 <row> 642 <entry>Cn</entry> 643 <entry>Unassigned</entry> 644 </row> 645 <row> 646 <entry>Co</entry> 647 <entry>Private use</entry> 648 </row> 649 <row> 650 <entry>Cs</entry> 651 <entry>Surrogate</entry> 652 </row> 653 <row> 654 <entry>L</entry> 655 <entry>Letter</entry> 656 </row> 657 <row> 658 <entry>Ll</entry> 659 <entry>Lower case letter</entry> 660 </row> 661 <row> 662 <entry>Lm</entry> 663 <entry>Modifier letter</entry> 664 </row> 665 <row> 666 <entry>Lo</entry> 667 <entry>Other letter</entry> 668 </row> 669 <row> 670 <entry>Lt</entry> 671 <entry>Title case letter</entry> 672 </row> 673 <row> 674 <entry>Lu</entry> 675 <entry>Upper case letter</entry> 676 </row> 677 <row> 678 <entry>M</entry> 679 <entry>Mark</entry> 680 </row> 681 <row> 682 <entry>Mc</entry> 683 <entry>Spacing mark</entry> 684 </row> 685 <row> 686 <entry>Me</entry> 687 <entry>Enclosing mark</entry> 688 </row> 689 <row> 690 <entry>Mn</entry> 691 <entry>Non-spacing mark</entry> 692 </row> 693 <row> 694 <entry>N</entry> 695 <entry>Number</entry> 696 </row> 697 <row> 698 <entry>Nd</entry> 699 <entry>Decimal number</entry> 700 </row> 701 <row> 702 <entry>Nl</entry> 703 <entry>Letter number</entry> 704 </row> 705 <row> 706 <entry>No</entry> 707 <entry>Other number</entry> 708 </row> 709 <row> 710 <entry>P</entry> 711 <entry>Punctuation</entry> 712 </row> 713 <row> 714 <entry>Pc</entry> 715 <entry>Connector punctuation</entry> 716 </row> 717 <row> 718 <entry>Pd</entry> 719 <entry>Dash punctuation</entry> 720 </row> 721 <row> 722 <entry>Pe</entry> 723 <entry>Close punctuation</entry> 724 </row> 725 <row> 726 <entry>Pf</entry> 727 <entry>Final punctuation</entry> 728 </row> 729 <row> 730 <entry>Pi</entry> 731 <entry>Initial punctuation</entry> 732 </row> 733 <row> 734 <entry>Po</entry> 735 <entry>Other punctuation</entry> 736 </row> 737 <row> 738 <entry>Ps</entry> 739 <entry>Open punctuation</entry> 740 </row> 741 <row> 742 <entry>S</entry> 743 <entry>Symbol</entry> 744 </row> 745 <row> 746 <entry>Sc</entry> 747 <entry>Currency symbol</entry> 748 </row> 749 <row> 750 <entry>Sk</entry> 751 <entry>Modifier symbol</entry> 752 </row> 753 <row> 754 <entry>Sm</entry> 755 <entry>Mathematical symbol</entry> 756 </row> 757 <row> 758 <entry>So</entry> 759 <entry>Other symbol</entry> 760 </row> 761 <row> 762 <entry>Z</entry> 763 <entry>Separator</entry> 764 </row> 765 <row> 766 <entry>Zl</entry> 767 <entry>Line separator</entry> 768 </row> 769 <row> 770 <entry>Zp</entry> 771 <entry>Paragraph separator</entry> 772 </row> 773 <row> 774 <entry>Zs</entry> 775 <entry>Space separator</entry> 776 </row> 777</tbody> 778</tgroup> 779</table> 780 781<para> 782The special property L& is also supported: it matches a character that has 783the Lu, Ll, or Lt property, in other words, a letter that is not classified as 784a modifier or "other". 785</para> 786 787<para> 788The long synonyms for these properties that Perl supports (such as \ep{Letter}) 789are not supported by GRegex, nor is it permitted to prefix any of these 790properties with "Is". 791</para> 792 793<para> 794No character that is in the Unicode table has the Cn (unassigned) property. 795Instead, this property is assumed for any code point that is not in the 796Unicode table. 797</para> 798 799<para> 800Specifying caseless matching does not affect these escape sequences. 801For example, \p{Lu} always matches only upper case letters. 802</para> 803 804<para> 805The \X escape matches any number of Unicode characters that form an 806extended Unicode sequence. \X is equivalent to 807</para> 808 809<programlisting> 810(?>\PM\pM*) 811</programlisting> 812 813<para> 814That is, it matches a character without the "mark" property, followed 815by zero or more characters with the "mark" property, and treats the 816sequence as an atomic group (see below). Characters with the "mark" 817property are typically accents that affect the preceding character. 818</para> 819 820<para> 821Matching characters by Unicode property is not fast, because GRegex has 822to search a structure that contains data for over fifteen thousand 823characters. That is why the traditional escape sequences such as \d and 824\w do not use Unicode properties. 825</para> 826</refsect2> 827 828<refsect2> 829<title>Simple assertions</title> 830<para> 831The final use of backslash is for certain simple assertions. An 832assertion specifies a condition that has to be met at a particular point in 833a match, without consuming any characters from the string. The 834use of subpatterns for more complicated assertions is described below. 835The backslashed assertions are: 836</para> 837 838<table frame="all" colsep="1" rowsep="1"> 839<title>Simple assertions</title> 840<tgroup cols="2"> 841<colspec colnum="1" align="center"/> 842<thead> 843 <row> 844 <entry>Escape</entry> 845 <entry>Meaning</entry> 846 </row> 847</thead> 848<tbody> 849 <row> 850 <entry>\b</entry> 851 <entry>matches at a word boundary</entry> 852 </row> 853 <row> 854 <entry>\B</entry> 855 <entry>matches when not at a word boundary</entry> 856 </row> 857 <row> 858 <entry>\A</entry> 859 <entry>matches at the start of the string</entry> 860 </row> 861 <row> 862 <entry>\Z</entry> 863 <entry>matches at the end of the string or before a newline at the end of the string</entry> 864 </row> 865 <row> 866 <entry>\z</entry> 867 <entry>matches only at the end of the string</entry> 868 </row> 869 <row> 870 <entry>\G</entry> 871 <entry>matches at first matching position in the string</entry> 872 </row> 873</tbody> 874</tgroup> 875</table> 876 877<para> 878These assertions may not appear in character classes (but note that \b 879has a different meaning, namely the backspace character, inside a 880character class). 881</para> 882 883<para> 884A word boundary is a position in the string where the current 885character and the previous character do not both match \w or \W (i.e. 886one matches \w and the other matches \W), or the start or end of the 887string if the first or last character matches \w, respectively. 888</para> 889 890<para> 891The \A, \Z, and \z assertions differ from the traditional circumflex 892and dollar (described in the next section) in that they only ever match 893at the very start and end of the string, whatever options are 894set. Thus, they are independent of multiline mode. These three assertions 895are not affected by the <varname>G_REGEX_MATCH_NOTBOL</varname> or <varname>G_REGEX_MATCH_NOTEOL</varname> options, 896which affect only the behaviour of the circumflex and dollar metacharacters. 897However, if the start_position argument of a matching function is non-zero, 898indicating that matching is to start at a point other than the beginning of 899the string, \A can never match. The difference between \Z and \z is 900that \Z matches before a newline at the end of the string as well at the 901very end, whereas \z matches only at the end. 902</para> 903 904<para> 905The \G assertion is true only when the current matching position is at 906the start point of the match, as specified by the start_position argument 907to the matching functions. It differs from \A when the value of startoffset is 908non-zero. 909</para> 910 911<para> 912Note, however, that the interpretation of \G, as the start of the 913current match, is subtly different from Perl’s, which defines it as the 914end of the previous match. In Perl, these can be different when the 915previously matched string was empty. 916</para> 917 918<para> 919If all the alternatives of a pattern begin with \G, the expression is 920anchored to the starting match position, and the "anchored" flag is set 921in the compiled regular expression. 922</para> 923</refsect2> 924</refsect1> 925 926<refsect1> 927<title>Circumflex and dollar</title> 928<para> 929Outside a character class, in the default matching mode, the circumflex 930character is an assertion that is true only if the current matching 931point is at the start of the string. If the start_position argument to 932the matching functions is non-zero, circumflex can never match if the 933<varname>G_REGEX_MULTILINE</varname> option is unset. Inside a character class, circumflex 934has an entirely different meaning (see below). 935</para> 936 937<para> 938Circumflex need not be the first character of the pattern if a number 939of alternatives are involved, but it should be the first thing in each 940alternative in which it appears if the pattern is ever to match that 941branch. If all possible alternatives start with a circumflex, that is, 942if the pattern is constrained to match only at the start of the string, 943it is said to be an "anchored" pattern. (There are also other 944constructs that can cause a pattern to be anchored.) 945</para> 946 947<para> 948A dollar character is an assertion that is true only if the current 949matching point is at the end of the string, or immediately 950before a newline at the end of the string (by default). Dollar need not 951be the last character of the pattern if a number of alternatives are 952involved, but it should be the last item in any branch in which it 953appears. Dollar has no special meaning in a character class. 954</para> 955 956<para> 957The meaning of dollar can be changed so that it matches only at the 958very end of the string, by setting the <varname>G_REGEX_DOLLAR_ENDONLY</varname> option at 959compile time. This does not affect the \Z assertion. 960</para> 961 962<para> 963The meanings of the circumflex and dollar characters are changed if the 964<varname>G_REGEX_MULTILINE</varname> option is set. When this is the case, 965a circumflex matches immediately after internal newlines as well as at the 966start of the string. It does not match after a newline that ends the string. 967A dollar matches before any newlines in the string, as well as at the very 968end, when <varname>G_REGEX_MULTILINE</varname> is set. When newline is 969specified as the two-character sequence CRLF, isolated CR and LF characters 970do not indicate newlines. 971</para> 972 973<para> 974For example, the pattern /^abc$/ matches the string "def\nabc" (where 975\n represents a newline) in multiline mode, but not otherwise. Consequently, 976patterns that are anchored in single line mode because all branches start with 977^ are not anchored in multiline mode, and a match for circumflex is possible 978when the <varname>start_position</varname> argument of a matching function 979is non-zero. The <varname>G_REGEX_DOLLAR_ENDONLY</varname> option is ignored 980if <varname>G_REGEX_MULTILINE</varname> is set. 981</para> 982 983<para> 984Note that the sequences \A, \Z, and \z can be used to match the start and 985end of the string in both modes, and if all branches of a pattern start with 986\A it is always anchored, whether or not <varname>G_REGEX_MULTILINE</varname> 987is set. 988</para> 989</refsect1> 990 991<refsect1> 992<title>Full stop (period, dot)</title> 993<para> 994Outside a character class, a dot in the pattern matches any one character 995in the string, including a non-printing character, but not (by 996default) newline. In UTF-8 a character might be more than one byte long. 997</para> 998 999<para> 1000When a line ending is defined as a single character, dot never matches that 1001character; when the two-character sequence CRLF is used, dot does not match CR 1002if it is immediately followed by LF, but otherwise it matches all characters 1003(including isolated CRs and LFs). When any Unicode line endings are being 1004recognized, dot does not match CR or LF or any of the other line ending 1005characters. 1006</para> 1007 1008<para> 1009If the <varname>G_REGEX_DOTALL</varname> flag is set, dots match newlines 1010as well. The handling of dot is entirely independent of the handling of circumflex 1011and dollar, the only relationship being that they both involve newline 1012characters. Dot has no special meaning in a character class. 1013</para> 1014 1015<para> 1016The behaviour of dot with regard to newlines can be changed. If the 1017<varname>G_REGEX_DOTALL</varname> option is set, a dot matches any one 1018character, without exception. If newline is defined as the two-character 1019sequence CRLF, it takes two dots to match it. 1020</para> 1021 1022<para> 1023The handling of dot is entirely independent of the handling of circumflex and 1024dollar, the only relationship being that they both involve newlines. Dot has no 1025special meaning in a character class. 1026</para> 1027</refsect1> 1028 1029<refsect1> 1030<title>Matching a single byte</title> 1031<para> 1032Outside a character class, the escape sequence \C matches any one byte, 1033both in and out of UTF-8 mode. Unlike a dot, it always matches any line 1034ending characters. 1035The feature is provided in Perl in order to match individual bytes in 1036UTF-8 mode. Because it breaks up UTF-8 characters into individual 1037bytes, what remains in the string may be a malformed UTF-8 string. For 1038this reason, the \C escape sequence is best avoided. 1039</para> 1040 1041<para> 1042GRegex does not allow \C to appear in lookbehind assertions (described 1043below), because in UTF-8 mode this would make it impossible to calculate 1044the length of the lookbehind. 1045</para> 1046</refsect1> 1047 1048<refsect1> 1049<title>Square brackets and character classes</title> 1050<para> 1051An opening square bracket introduces a character class, terminated by a 1052closing square bracket. A closing square bracket on its own is not special. If a closing square bracket is required as a member of the class, 1053it should be the first data character in the class (after an initial 1054circumflex, if present) or escaped with a backslash. 1055</para> 1056 1057<para> 1058A character class matches a single character in the string. A matched character 1059must be in the set of characters defined by the class, unless the first 1060character in the class definition is a circumflex, in which case the 1061string character must not be in the set defined by the class. If a 1062circumflex is actually required as a member of the class, ensure it is 1063not the first character, or escape it with a backslash. 1064</para> 1065 1066<para> 1067For example, the character class [aeiou] matches any lower case vowel, 1068while [^aeiou] matches any character that is not a lower case vowel. 1069Note that a circumflex is just a convenient notation for specifying the 1070characters that are in the class by enumerating those that are not. A 1071class that starts with a circumflex is not an assertion: it still consumes 1072a character from the string, and therefore it fails if the current pointer 1073is at the end of the string. 1074</para> 1075 1076<para> 1077In UTF-8 mode, characters with values greater than 255 can be included 1078in a class as a literal string of bytes, or by using the \x{ escaping 1079mechanism. 1080</para> 1081 1082<para> 1083When caseless matching is set, any letters in a class represent both 1084their upper case and lower case versions, so for example, a caseless 1085[aeiou] matches "A" as well as "a", and a caseless [^aeiou] does not 1086match "A", whereas a caseful version would. 1087</para> 1088 1089<para> 1090Characters that might indicate line breaks are never treated 1091in any special way when matching character classes, whatever line-ending 1092sequence is in use, and whatever setting of the <varname>G_REGEX_DOTALL</varname> 1093and <varname>G_REGEX_MULTILINE</varname> options is used. A class such as [^a] 1094always matches one of these characters. 1095</para> 1096 1097<para> 1098The minus (hyphen) character can be used to specify a range of characters in 1099a character class. For example, [d-m] matches any letter 1100between d and m, inclusive. If a minus character is required in a 1101class, it must be escaped with a backslash or appear in a position 1102where it cannot be interpreted as indicating a range, typically as the 1103first or last character in the class. 1104</para> 1105 1106<para> 1107It is not possible to have the literal character "]" as the end character 1108of a range. A pattern such as [W-]46] is interpreted as a class of 1109two characters ("W" and "-") followed by a literal string "46]", so it 1110would match "W46]" or "-46]". However, if the "]" is escaped with a 1111backslash it is interpreted as the end of range, so [W-\]46] is interpreted 1112as a class containing a range followed by two other characters. 1113The octal or hexadecimal representation of "]" can also be used to end 1114a range. 1115</para> 1116 1117<para> 1118Ranges operate in the collating sequence of character values. They can 1119also be used for characters specified numerically, for example 1120[\000-\037]. In UTF-8 mode, ranges can include characters whose values 1121are greater than 255, for example [\x{100}-\x{2ff}]. 1122</para> 1123 1124<para> 1125The character types \d, \D, \p, \P, \s, \S, \w, and \W may also appear 1126in a character class, and add the characters that they match to the 1127class. For example, [\dABCDEF] matches any hexadecimal digit. A 1128circumflex can conveniently be used with the upper case character types to 1129specify a more restricted set of characters than the matching lower 1130case type. For example, the class [^\W_] matches any letter or digit, 1131but not underscore. 1132</para> 1133 1134<para> 1135The only metacharacters that are recognized in character classes are 1136backslash, hyphen (only where it can be interpreted as specifying a 1137range), circumflex (only at the start), opening square bracket (only 1138when it can be interpreted as introducing a POSIX class name - see the 1139next section), and the terminating closing square bracket. However, 1140escaping other non-alphanumeric characters does no harm. 1141</para> 1142</refsect1> 1143 1144<refsect1> 1145<title>Posix character classes</title> 1146<para> 1147GRegex supports the POSIX notation for character classes. This uses names 1148enclosed by [: and :] within the enclosing square brackets. For example, 1149</para> 1150 1151<programlisting> 1152[01[:alpha:]%] 1153</programlisting> 1154 1155<para> 1156matches "0", "1", any alphabetic character, or "%". The supported class 1157names are 1158</para> 1159 1160<table frame="all" colsep="1" rowsep="1"> 1161<title>Posix classes</title> 1162<tgroup cols="2"> 1163<colspec colnum="1" align="center"/> 1164<thead> 1165 <row> 1166 <entry>Name</entry> 1167 <entry>Meaning</entry> 1168 </row> 1169</thead> 1170<tbody> 1171 <row> 1172 <entry>alnum</entry> 1173 <entry>letters and digits</entry> 1174 </row> 1175 <row> 1176 <entry>alpha</entry> 1177 <entry>letters</entry> 1178 </row> 1179 <row> 1180 <entry>ascii</entry> 1181 <entry>character codes 0 - 127</entry> 1182 </row> 1183 <row> 1184 <entry>blank</entry> 1185 <entry>space or tab only</entry> 1186 </row> 1187 <row> 1188 <entry>cntrl</entry> 1189 <entry>control characters</entry> 1190 </row> 1191 <row> 1192 <entry>digit</entry> 1193 <entry>decimal digits (same as \d)</entry> 1194 </row> 1195 <row> 1196 <entry>graph</entry> 1197 <entry>printing characters, excluding space</entry> 1198 </row> 1199 <row> 1200 <entry>lower</entry> 1201 <entry>lower case letters</entry> 1202 </row> 1203 <row> 1204 <entry>print</entry> 1205 <entry>printing characters, including space</entry> 1206 </row> 1207 <row> 1208 <entry>punct</entry> 1209 <entry>printing characters, excluding letters and digits</entry> 1210 </row> 1211 <row> 1212 <entry>space</entry> 1213 <entry>white space (not quite the same as \s)</entry> 1214 </row> 1215 <row> 1216 <entry>upper</entry> 1217 <entry>upper case letters</entry> 1218 </row> 1219 <row> 1220 <entry>word</entry> 1221 <entry>"word" characters (same as \w)</entry> 1222 </row> 1223 <row> 1224 <entry>xdigit</entry> 1225 <entry>hexadecimal digits</entry> 1226 </row> 1227</tbody> 1228</tgroup> 1229</table> 1230 1231<para> 1232The "space" characters are HT (9), LF (10), VT (11), FF (12), CR (13), 1233and space (32). Notice that this list includes the VT character (code 123411). This makes "space" different to \s, which does not include VT (for 1235Perl compatibility). 1236</para> 1237 1238<para> 1239The name "word" is a Perl extension, and "blank" is a GNU extension. 1240Another Perl extension is negation, which is indicated by a ^ character 1241after the colon. For example, 1242</para> 1243 1244<programlisting> 1245[12[:^digit:]] 1246</programlisting> 1247 1248<para> 1249matches "1", "2", or any non-digit. GRegex also recognize the 1250POSIX syntax [.ch.] and [=ch=] where "ch" is a "collating element", but 1251these are not supported, and an error is given if they are encountered. 1252</para> 1253 1254<para> 1255In UTF-8 mode, characters with values greater than 128 do not match any 1256of the POSIX character classes. 1257</para> 1258</refsect1> 1259 1260<refsect1> 1261<title>Vertical bar</title> 1262<para> 1263Vertical bar characters are used to separate alternative patterns. For 1264example, the pattern 1265</para> 1266 1267<programlisting> 1268 gilbert|sullivan 1269</programlisting> 1270 1271<para> 1272matches either "gilbert" or "sullivan". Any number of alternatives may 1273appear, and an empty alternative is permitted (matching the empty 1274string). The matching process tries each alternative in turn, from 1275left to right, and the first one that succeeds is used. If the alternatives are within a subpattern (defined below), "succeeds" means matching the rest of the main pattern as well as the alternative in the subpattern. 1276</para> 1277</refsect1> 1278 1279<refsect1> 1280<title>Internal option setting</title> 1281<para> 1282The settings of the <varname>G_REGEX_CASELESS</varname>, <varname>G_REGEX_MULTILINE</varname>, <varname>G_REGEX_MULTILINE</varname>, 1283and <varname>G_REGEX_EXTENDED</varname> options can be changed from within the pattern by a 1284sequence of Perl-style option letters enclosed between "(?" and ")". The 1285option letters are 1286</para> 1287 1288<table frame="all" colsep="1" rowsep="1"> 1289<title>Option settings</title> 1290<tgroup cols="2"> 1291<colspec colnum="1" align="center"/> 1292<thead> 1293 <row> 1294 <entry>Option</entry> 1295 <entry>Flag</entry> 1296 </row> 1297</thead> 1298<tbody> 1299 <row> 1300 <entry>i</entry> 1301 <entry><varname>G_REGEX_CASELESS</varname></entry> 1302 </row> 1303 <row> 1304 <entry>m</entry> 1305 <entry><varname>G_REGEX_MULTILINE</varname></entry> 1306 </row> 1307 <row> 1308 <entry>s</entry> 1309 <entry><varname>G_REGEX_DOTALL</varname></entry> 1310 </row> 1311 <row> 1312 <entry>x</entry> 1313 <entry><varname>G_REGEX_EXTENDED</varname></entry> 1314 </row> 1315</tbody> 1316</tgroup> 1317</table> 1318 1319<para> 1320For example, (?im) sets caseless, multiline matching. It is also 1321possible to unset these options by preceding the letter with a hyphen, and a 1322combined setting and unsetting such as (?im-sx), which sets <varname>G_REGEX_CASELESS</varname> 1323and <varname>G_REGEX_MULTILINE</varname> while unsetting <varname>G_REGEX_DOTALL</varname> and <varname>G_REGEX_EXTENDED</varname>, 1324is also permitted. If a letter appears both before and after the 1325hyphen, the option is unset. 1326</para> 1327 1328<para> 1329When an option change occurs at top level (that is, not inside subpattern 1330parentheses), the change applies to the remainder of the pattern 1331that follows. 1332</para> 1333 1334<para> 1335An option change within a subpattern (see below for a description of subpatterns) 1336affects only that part of the current pattern that follows it, so 1337</para> 1338 1339<programlisting> 1340(a(?i)b)c 1341</programlisting> 1342 1343<para> 1344matches abc and aBc and no other strings (assuming <varname>G_REGEX_CASELESS</varname> is not 1345used). By this means, options can be made to have different settings 1346in different parts of the pattern. Any changes made in one alternative 1347do carry on into subsequent branches within the same subpattern. For 1348example, 1349</para> 1350 1351<programlisting> 1352(a(?i)b|c) 1353</programlisting> 1354 1355<para> 1356matches "ab", "aB", "c", and "C", even though when matching "C" the 1357first branch is abandoned before the option setting. This is because 1358the effects of option settings happen at compile time. There would be 1359some very weird behaviour otherwise. 1360</para> 1361 1362<para> 1363The options <varname>G_REGEX_UNGREEDY</varname> and 1364<varname>G_REGEX_EXTRA</varname> and <varname>G_REGEX_DUPNAMES</varname> 1365can be changed in the same way as the Perl-compatible options by using 1366the characters U, X and J respectively. 1367</para> 1368</refsect1> 1369 1370<refsect1> 1371<title>Subpatterns</title> 1372<para> 1373Subpatterns are delimited by parentheses (round brackets), which can be 1374nested. Turning part of a pattern into a subpattern does two things: 1375</para> 1376 1377<itemizedlist> 1378<listitem><para> 1379It localizes a set of alternatives. For example, the pattern 1380cat(aract|erpillar|) matches one of the words "cat", "cataract", or 1381"caterpillar". Without the parentheses, it would match "cataract", 1382"erpillar" or an empty string. 1383</para></listitem> 1384<listitem><para> 1385It sets up the subpattern as a capturing subpattern. This means 1386that, when the whole pattern matches, that portion of the 1387string that matched the subpattern can be obtained using <function>g_regex_fetch()</function>. 1388Opening parentheses are counted from left to right (starting from 1, as 1389subpattern 0 is the whole matched string) to obtain numbers for the 1390capturing subpatterns. 1391</para></listitem> 1392</itemizedlist> 1393 1394<para> 1395For example, if the string "the red king" is matched against the pattern 1396</para> 1397 1398<programlisting> 1399the ((red|white) (king|queen)) 1400</programlisting> 1401 1402<para> 1403the captured substrings are "red king", "red", and "king", and are numbered 1, 2, and 3, respectively. 1404</para> 1405 1406<para> 1407The fact that plain parentheses fulfil two functions is not always 1408helpful. There are often times when a grouping subpattern is required 1409without a capturing requirement. If an opening parenthesis is followed 1410by a question mark and a colon, the subpattern does not do any capturing, 1411and is not counted when computing the number of any subsequent 1412capturing subpatterns. For example, if the string "the white queen" is 1413matched against the pattern 1414</para> 1415 1416<programlisting> 1417the ((?:red|white) (king|queen)) 1418</programlisting> 1419 1420<para> 1421the captured substrings are "white queen" and "queen", and are numbered 14221 and 2. The maximum number of capturing subpatterns is 65535. 1423</para> 1424 1425<para> 1426As a convenient shorthand, if any option settings are required at the 1427start of a non-capturing subpattern, the option letters may appear 1428between the "?" and the ":". Thus the two patterns 1429</para> 1430 1431<programlisting> 1432(?i:saturday|sunday) 1433(?:(?i)saturday|sunday) 1434</programlisting> 1435 1436<para> 1437match exactly the same set of strings. Because alternative branches are 1438tried from left to right, and options are not reset until the end of 1439the subpattern is reached, an option setting in one branch does affect 1440subsequent branches, so the above patterns match "SUNDAY" as well as 1441"Saturday". 1442</para> 1443</refsect1> 1444 1445<refsect1> 1446<title>Named subpatterns</title> 1447<para> 1448Identifying capturing parentheses by number is simple, but it can be 1449very hard to keep track of the numbers in complicated regular expressions. 1450Furthermore, if an expression is modified, the numbers may 1451change. To help with this difficulty, GRegex supports the naming of 1452subpatterns. A subpattern can be named in one of three ways: (?<name>...) or 1453(?'name'...) as in Perl, or (?P<name>...) as in Python. 1454References to capturing parentheses from other 1455parts of the pattern, such as backreferences, recursion, and conditions, 1456can be made by name as well as by number. 1457</para> 1458 1459<para> 1460Names consist of up to 32 alphanumeric characters and underscores. Named 1461capturing parentheses are still allocated numbers as well as names, exactly as 1462if the names were not present. 1463By default, a name must be unique within a pattern, but it is possible to relax 1464this constraint by setting the <varname>G_REGEX_DUPNAMES</varname> option at 1465compile time. This can be useful for patterns where only one instance of the 1466named parentheses can match. Suppose you want to match the name of a weekday, 1467either as a 3-letter abbreviation or as the full name, and in both cases you 1468want to extract the abbreviation. This pattern (ignoring the line breaks) does 1469the job: 1470</para> 1471 1472<programlisting> 1473(?<DN>Mon|Fri|Sun)(?:day)?| 1474(?<DN>Tue)(?:sday)?| 1475(?<DN>Wed)(?:nesday)?| 1476(?<DN>Thu)(?:rsday)?| 1477(?<DN>Sat)(?:urday)? 1478</programlisting> 1479 1480<para> 1481There are five capturing substrings, but only one is ever set after a match. 1482The function for extracting the data by name returns the substring 1483for the first (and in this example, the only) subpattern of that name that 1484matched. This saves searching to find which numbered subpattern it was. If you 1485make a reference to a non-unique named subpattern from elsewhere in the 1486pattern, the one that corresponds to the lowest number is used. 1487</para> 1488</refsect1> 1489 1490<refsect1> 1491<title>Repetition</title> 1492<para> 1493Repetition is specified by quantifiers, which can follow any of the 1494following items: 1495</para> 1496 1497<itemizedlist> 1498<listitem><para>a literal data character</para></listitem> 1499<listitem><para>the dot metacharacter</para></listitem> 1500<listitem><para>the \C escape sequence</para></listitem> 1501<listitem><para>the \X escape sequence (in UTF-8 mode)</para></listitem> 1502<listitem><para>the \R escape sequence</para></listitem> 1503<listitem><para>an escape such as \d that matches a single character</para></listitem> 1504<listitem><para>a character class</para></listitem> 1505<listitem><para>a back reference (see next section)</para></listitem> 1506<listitem><para>a parenthesized subpattern (unless it is an assertion)</para></listitem> 1507</itemizedlist> 1508 1509<para> 1510The general repetition quantifier specifies a minimum and maximum number 1511of permitted matches, by giving the two numbers in curly brackets 1512(braces), separated by a comma. The numbers must be less than 65536, 1513and the first must be less than or equal to the second. For example: 1514</para> 1515 1516<programlisting> 1517z{2,4} 1518</programlisting> 1519 1520<para> 1521matches "zz", "zzz", or "zzzz". A closing brace on its own is not a 1522special character. If the second number is omitted, but the comma is 1523present, there is no upper limit; if the second number and the comma 1524are both omitted, the quantifier specifies an exact number of required 1525matches. Thus 1526</para> 1527 1528<programlisting> 1529[aeiou]{3,} 1530</programlisting> 1531 1532<para> 1533matches at least 3 successive vowels, but may match many more, while 1534</para> 1535 1536<programlisting> 1537\d{8} 1538</programlisting> 1539 1540<para> 1541matches exactly 8 digits. An opening curly bracket that appears in a 1542position where a quantifier is not allowed, or one that does not match 1543the syntax of a quantifier, is taken as a literal character. For example, 1544{,6} is not a quantifier, but a literal string of four characters. 1545</para> 1546 1547<para> 1548In UTF-8 mode, quantifiers apply to UTF-8 characters rather than to 1549individual bytes. Thus, for example, \x{100}{2} matches two UTF-8 1550characters, each of which is represented by a two-byte sequence. Similarly, 1551\X{3} matches three Unicode extended sequences, each of which may be 1552several bytes long (and they may be of different lengths). 1553</para> 1554 1555<para> 1556The quantifier {0} is permitted, causing the expression to behave as if 1557the previous item and the quantifier were not present. 1558</para> 1559 1560<para> 1561For convenience, the three most common quantifiers have single-character 1562abbreviations: 1563</para> 1564 1565<table frame="all" colsep="1" rowsep="1"> 1566<title>Abbreviations for quantifiers</title> 1567<tgroup cols="2"> 1568<colspec colnum="1" align="center"/> 1569<thead> 1570 <row> 1571 <entry>Abbreviation</entry> 1572 <entry>Meaning</entry> 1573 </row> 1574</thead> 1575<tbody> 1576 <row> 1577 <entry>*</entry> 1578 <entry>is equivalent to {0,}</entry> 1579 </row> 1580 <row> 1581 <entry>+</entry> 1582 <entry>is equivalent to {1,}</entry> 1583 </row> 1584 <row> 1585 <entry>?</entry> 1586 <entry>is equivalent to {0,1}</entry> 1587 </row> 1588</tbody> 1589</tgroup> 1590</table> 1591 1592<para> 1593It is possible to construct infinite loops by following a subpattern 1594that can match no characters with a quantifier that has no upper limit, 1595for example: 1596</para> 1597 1598<programlisting> 1599(a?)* 1600</programlisting> 1601 1602<para> 1603Because there are cases where this can be useful, such patterns are 1604accepted, but if any repetition of the subpattern does in fact match 1605no characters, the loop is forcibly broken. 1606</para> 1607 1608<para> 1609By default, the quantifiers are "greedy", that is, they match as much 1610as possible (up to the maximum number of permitted times), without 1611causing the rest of the pattern to fail. The classic example of where 1612this gives problems is in trying to match comments in C programs. These 1613appear between /* and */ and within the comment, individual * and / 1614characters may appear. An attempt to match C comments by applying the 1615pattern 1616</para> 1617 1618<programlisting> 1619/\*.*\*/ 1620</programlisting> 1621 1622<para> 1623to the string 1624</para> 1625 1626<programlisting> 1627/* first comment */ not comment /* second comment */ 1628</programlisting> 1629 1630<para> 1631fails, because it matches the entire string owing to the greediness of 1632the .* item. 1633</para> 1634 1635<para> 1636However, if a quantifier is followed by a question mark, it ceases to 1637be greedy, and instead matches the minimum number of times possible, so 1638the pattern 1639</para> 1640 1641<programlisting> 1642/\*.*?\*/ 1643</programlisting> 1644 1645<para> 1646does the right thing with the C comments. The meaning of the various 1647quantifiers is not otherwise changed, just the preferred number of 1648matches. Do not confuse this use of question mark with its use as a 1649quantifier in its own right. Because it has two uses, it can sometimes 1650appear doubled, as in 1651</para> 1652 1653<programlisting> 1654\d??\d 1655</programlisting> 1656 1657<para> 1658which matches one digit by preference, but can match two if that is the 1659only way the rest of the pattern matches. 1660</para> 1661 1662<para> 1663If the <varname>G_REGEX_UNGREEDY</varname> flag is set, the quantifiers are not greedy 1664by default, but individual ones can be made greedy by following them with 1665a question mark. In other words, it inverts the default behaviour. 1666</para> 1667 1668<para> 1669When a parenthesized subpattern is quantified with a minimum repeat 1670count that is greater than 1 or with a limited maximum, more memory is 1671required for the compiled pattern, in proportion to the size of the 1672minimum or maximum. 1673</para> 1674 1675<para> 1676If a pattern starts with .* or .{0,} and the <varname>G_REGEX_DOTALL</varname> flag 1677is set, thus allowing the dot to match newlines, the 1678pattern is implicitly anchored, because whatever follows will be tried 1679against every character position in the string, so there is no 1680point in retrying the overall match at any position after the first. 1681GRegex normally treats such a pattern as though it were preceded by \A. 1682</para> 1683 1684<para> 1685In cases where it is known that the string contains no newlines, it 1686is worth setting <varname>G_REGEX_DOTALL</varname> in order to obtain this optimization, 1687or alternatively using ^ to indicate anchoring explicitly. 1688</para> 1689 1690<para> 1691However, there is one situation where the optimization cannot be used. 1692When .* is inside capturing parentheses that are the subject of a 1693backreference elsewhere in the pattern, a match at the start may fail 1694where a later one succeeds. Consider, for example: 1695</para> 1696 1697<programlisting> 1698(.*)abc\1 1699</programlisting> 1700 1701<para> 1702If the string is "xyz123abc123" the match point is the fourth character. 1703For this reason, such a pattern is not implicitly anchored. 1704</para> 1705 1706<para> 1707When a capturing subpattern is repeated, the value captured is the 1708substring that matched the final iteration. For example, after 1709</para> 1710 1711<programlisting> 1712(tweedle[dume]{3}\s*)+ 1713</programlisting> 1714 1715<para> 1716has matched "tweedledum tweedledee" the value of the captured substring 1717is "tweedledee". However, if there are nested capturing subpatterns, 1718the corresponding captured values may have been set in previous iterations. 1719For example, after 1720</para> 1721 1722<programlisting> 1723/(a|(b))+/ 1724</programlisting> 1725 1726<para> 1727matches "aba" the value of the second captured substring is "b". 1728</para> 1729</refsect1> 1730 1731<refsect1> 1732<title>Atomic grouping and possessive quantifiers</title> 1733<para> 1734With both maximizing ("greedy") and minimizing ("ungreedy" or "lazy") 1735repetition, failure of what follows normally causes the repeated 1736item to be re-evaluated to see if a different number 1737of repeats allows the rest of the pattern to match. Sometimes it 1738is useful to prevent this, either to change the nature of the 1739match, or to cause it fail earlier than it otherwise might, when the 1740author of the pattern knows there is no point in carrying on. 1741</para> 1742 1743<para> 1744Consider, for example, the pattern \d+foo when applied to the string 1745</para> 1746 1747<programlisting> 1748123456bar 1749</programlisting> 1750 1751<para> 1752After matching all 6 digits and then failing to match "foo", the normal 1753action of the matcher is to try again with only 5 digits matching the 1754\d+ item, and then with 4, and so on, before ultimately failing. 1755"Atomic grouping" (a term taken from Jeffrey Friedl’s book) provides 1756the means for specifying that once a subpattern has matched, it is not 1757to be re-evaluated in this way. 1758</para> 1759 1760<para> 1761If we use atomic grouping for the previous example, the matcher 1762give up immediately on failing to match "foo" the first time. The notation 1763is a kind of special parenthesis, starting with (?> as in this 1764example: 1765</para> 1766 1767<programlisting> 1768(?>\d+)foo 1769</programlisting> 1770 1771<para> 1772This kind of parenthesis "locks up" the part of the pattern it contains 1773once it has matched, and a failure further into the pattern is 1774prevented from backtracking into it. Backtracking past it to previous 1775items, however, works as normal. 1776</para> 1777 1778<para> 1779An alternative description is that a subpattern of this type matches 1780the string of characters that an identical standalone pattern would 1781match, if anchored at the current point in the string. 1782</para> 1783 1784<para> 1785Atomic grouping subpatterns are not capturing subpatterns. Simple cases 1786such as the above example can be thought of as a maximizing repeat that 1787must swallow everything it can. So, while both \d+ and \d+? are prepared 1788to adjust the number of digits they match in order to make the 1789rest of the pattern match, (?>\d+) can only match an entire sequence of 1790digits. 1791</para> 1792 1793<para> 1794Atomic groups in general can of course contain arbitrarily complicated 1795subpatterns, and can be nested. However, when the subpattern for an 1796atomic group is just a single repeated item, as in the example above, a 1797simpler notation, called a "possessive quantifier" can be used. This 1798consists of an additional + character following a quantifier. Using 1799this notation, the previous example can be rewritten as 1800</para> 1801 1802<programlisting> 1803\d++foo 1804</programlisting> 1805 1806<para> 1807Possessive quantifiers are always greedy; the setting of the 1808<varname>G_REGEX_UNGREEDY</varname> option is ignored. They are a convenient notation for the 1809simpler forms of atomic group. However, there is no difference in the 1810meaning of a possessive quantifier and the equivalent 1811atomic group, though there may be a performance difference; 1812possessive quantifiers should be slightly faster. 1813</para> 1814 1815<para> 1816The possessive quantifier syntax is an extension to the Perl syntax. 1817It was invented by Jeffrey Friedl in the first edition of his book and 1818then implemented by Mike McCloskey in Sun's Java package. 1819It ultimately found its way into Perl at release 5.10. 1820</para> 1821 1822<para> 1823GRegex has an optimization that automatically "possessifies" certain simple 1824pattern constructs. For example, the sequence A+B is treated as A++B because 1825there is no point in backtracking into a sequence of A's when B must follow. 1826</para> 1827 1828<para> 1829When a pattern contains an unlimited repeat inside a subpattern that 1830can itself be repeated an unlimited number of times, the use of an 1831atomic group is the only way to avoid some failing matches taking a 1832very long time indeed. The pattern 1833</para> 1834 1835<programlisting> 1836(\D+|<\d+>)*[!?] 1837</programlisting> 1838 1839<para> 1840matches an unlimited number of substrings that either consist of non- 1841digits, or digits enclosed in <>, followed by either ! or ?. When it 1842matches, it runs quickly. However, if it is applied to 1843</para> 1844 1845<programlisting> 1846aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 1847</programlisting> 1848 1849<para> 1850it takes a long time before reporting failure. This is because the 1851string can be divided between the internal \D+ repeat and the external 1852* repeat in a large number of ways, and all have to be tried. (The 1853example uses [!?] rather than a single character at the end, because 1854GRegex has an optimization that allows for fast failure 1855when a single character is used. It remember the last single character 1856that is required for a match, and fail early if it is not present 1857in the string.) If the pattern is changed so that it uses an atomic 1858group, like this: 1859</para> 1860 1861<programlisting> 1862((?>\D+)|<\d+>)*[!?] 1863</programlisting> 1864 1865<para> 1866sequences of non-digits cannot be broken, and failure happens quickly. 1867</para> 1868</refsect1> 1869 1870<refsect1> 1871<title>Back references</title> 1872<para> 1873Outside a character class, a backslash followed by a digit greater than 18740 (and possibly further digits) is a back reference to a capturing subpattern 1875earlier (that is, to its left) in the pattern, provided there have been that 1876many previous capturing left parentheses. 1877</para> 1878 1879<para> 1880However, if the decimal number following the backslash is less than 10, 1881it is always taken as a back reference, and causes an error only if 1882there are not that many capturing left parentheses in the entire pattern. 1883In other words, the parentheses that are referenced need not be 1884to the left of the reference for numbers less than 10. A "forward back 1885reference" of this type can make sense when a repetition is involved and 1886the subpattern to the right has participated in an earlier iteration. 1887</para> 1888 1889<para> 1890It is not possible to have a numerical "forward back reference" to subpattern 1891whose number is 10 or more using this syntax because a sequence such as \e50 is 1892interpreted as a character defined in octal. See the subsection entitled 1893"Non-printing characters" above for further details of the handling of digits 1894following a backslash. There is no such problem when named parentheses are used. 1895A back reference to any subpattern is possible using named parentheses (see below). 1896</para> 1897 1898<para> 1899Another way of avoiding the ambiguity inherent in the use of digits following a 1900backslash is to use the \g escape sequence (introduced in Perl 5.10.) 1901This escape must be followed by a positive or a negative number, 1902optionally enclosed in braces. 1903</para> 1904 1905<para> 1906A positive number specifies an absolute reference without the ambiguity that is 1907present in the older syntax. It is also useful when literal digits follow the 1908reference. A negative number is a relative reference. Consider "(abc(def)ghi)\g{-1}", 1909the sequence \g{-1} is a reference to the most recently started capturing 1910subpattern before \g, that is, is it equivalent to \2. Similarly, \g{-2} 1911would be equivalent to \1. The use of relative references can be helpful in 1912long patterns, and also in patterns that are created by joining together 1913fragments that contain references within themselves. 1914</para> 1915 1916<para> 1917A back reference matches whatever actually matched the capturing subpattern 1918in the current string, rather than anything matching 1919the subpattern itself (see "Subpatterns as subroutines" below for a way 1920of doing that). So the pattern 1921</para> 1922 1923<programlisting> 1924(sens|respons)e and \1ibility 1925</programlisting> 1926 1927<para> 1928matches "sense and sensibility" and "response and responsibility", but 1929not "sense and responsibility". If caseful matching is in force at the 1930time of the back reference, the case of letters is relevant. For example, 1931</para> 1932 1933<programlisting> 1934((?i)rah)\s+\1 1935</programlisting> 1936 1937<para> 1938matches "rah rah" and "RAH RAH", but not "RAH rah", even though the 1939original capturing subpattern is matched caselessly. 1940</para> 1941 1942<para> 1943Back references to named subpatterns use the Perl syntax \k<name> or \k'name' 1944or the Python syntax (?P=name). We could rewrite the above example in either of 1945the following ways: 1946</para> 1947 1948<programlisting> 1949(?<p1>(?i)rah)\s+\k<p1> 1950(?P<p1>(?i)rah)\s+(?P=p1) 1951</programlisting> 1952 1953<para> 1954A subpattern that is referenced by name may appear in the pattern before or 1955after the reference. 1956</para> 1957 1958<para> 1959There may be more than one back reference to the same subpattern. If a 1960subpattern has not actually been used in a particular match, any back 1961references to it always fail. For example, the pattern 1962</para> 1963 1964<programlisting> 1965(a|(bc))\2 1966</programlisting> 1967 1968<para> 1969always fails if it starts to match "a" rather than "bc". Because there 1970may be many capturing parentheses in a pattern, all digits following 1971the backslash are taken as part of a potential back reference number. 1972If the pattern continues with a digit character, some delimiter must be 1973used to terminate the back reference. If the <varname>G_REGEX_EXTENDED</varname> flag is 1974set, this can be whitespace. Otherwise an empty comment (see "Comments" below) can be used. 1975</para> 1976 1977<para> 1978A back reference that occurs inside the parentheses to which it refers 1979fails when the subpattern is first used, so, for example, (a\1) never 1980matches. However, such references can be useful inside repeated subpatterns. 1981For example, the pattern 1982</para> 1983 1984<programlisting> 1985(a|b\1)+ 1986</programlisting> 1987 1988<para> 1989matches any number of "a"s and also "aba", "ababbaa" etc. At each iteration 1990of the subpattern, the back reference matches the character 1991string corresponding to the previous iteration. In order for this to 1992work, the pattern must be such that the first iteration does not need 1993to match the back reference. This can be done using alternation, as in 1994the example above, or by a quantifier with a minimum of zero. 1995</para> 1996</refsect1> 1997 1998<refsect1> 1999<title>Assertions</title> 2000<para> 2001An assertion is a test on the characters following or preceding the 2002current matching point that does not actually consume any characters. 2003The simple assertions coded as \b, \B, \A, \G, \Z, \z, ^ and $ are 2004described above. 2005</para> 2006 2007<para> 2008More complicated assertions are coded as subpatterns. There are two 2009kinds: those that look ahead of the current position in the 2010string, and those that look behind it. An assertion subpattern is 2011matched in the normal way, except that it does not cause the current 2012matching position to be changed. 2013</para> 2014 2015<para> 2016Assertion subpatterns are not capturing subpatterns, and may not be 2017repeated, because it makes no sense to assert the same thing several 2018times. If any kind of assertion contains capturing subpatterns within 2019it, these are counted for the purposes of numbering the capturing 2020subpatterns in the whole pattern. However, substring capturing is carried 2021out only for positive assertions, because it does not make sense for 2022negative assertions. 2023</para> 2024 2025<refsect2> 2026<title>Lookahead assertions</title> 2027<para> 2028Lookahead assertions start with (?= for positive assertions and (?! for 2029negative assertions. For example, 2030</para> 2031 2032<programlisting> 2033\w+(?=;) 2034</programlisting> 2035 2036<para> 2037matches a word followed by a semicolon, but does not include the semicolon 2038in the match, and 2039</para> 2040 2041<programlisting> 2042foo(?!bar) 2043</programlisting> 2044 2045<para> 2046matches any occurrence of "foo" that is not followed by "bar". Note 2047that the apparently similar pattern 2048</para> 2049 2050<programlisting> 2051(?!foo)bar 2052</programlisting> 2053 2054<para> 2055does not find an occurrence of "bar" that is preceded by something 2056other than "foo"; it finds any occurrence of "bar" whatsoever, because 2057the assertion (?!foo) is always true when the next three characters are 2058"bar". A lookbehind assertion is needed to achieve the other effect. 2059</para> 2060 2061<para> 2062If you want to force a matching failure at some point in a pattern, the 2063most convenient way to do it is with (?!) because an empty string 2064always matches, so an assertion that requires there not to be an empty 2065string must always fail. 2066</para> 2067</refsect2> 2068 2069<refsect2> 2070<title>Lookbehind assertions</title> 2071<para> 2072Lookbehind assertions start with (?<= for positive assertions and (?<! 2073for negative assertions. For example, 2074</para> 2075 2076<programlisting> 2077(?<!foo)bar 2078</programlisting> 2079 2080<para> 2081does find an occurrence of "bar" that is not preceded by "foo". The 2082contents of a lookbehind assertion are restricted such that all the 2083strings it matches must have a fixed length. However, if there are 2084several top-level alternatives, they do not all have to have the same 2085fixed length. Thus 2086</para> 2087 2088<programlisting> 2089(?<=bullock|donkey) 2090</programlisting> 2091 2092<para> 2093is permitted, but 2094</para> 2095 2096<programlisting> 2097(?<!dogs?|cats?) 2098</programlisting> 2099 2100<para> 2101causes an error at compile time. Branches that match different length 2102strings are permitted only at the top level of a lookbehind assertion. 2103An assertion such as 2104</para> 2105 2106<programlisting> 2107(?<=ab(c|de)) 2108</programlisting> 2109 2110<para> 2111is not permitted, because its single top-level branch can match two 2112different lengths, but it is acceptable if rewritten to use two top- 2113level branches: 2114</para> 2115 2116<programlisting> 2117(?<=abc|abde) 2118</programlisting> 2119 2120<para> 2121The implementation of lookbehind assertions is, for each alternative, 2122to temporarily move the current position back by the fixed length and 2123then try to match. If there are insufficient characters before the 2124current position, the assertion fails. 2125</para> 2126 2127<para> 2128GRegex does not allow the \C escape (which matches a single byte in UTF-8 2129mode) to appear in lookbehind assertions, because it makes it impossible 2130to calculate the length of the lookbehind. The \X and \R escapes, which can 2131match different numbers of bytes, are also not permitted. 2132</para> 2133 2134<para> 2135Possessive quantifiers can be used in conjunction with lookbehind assertions to 2136specify efficient matching at the end of the subject string. Consider a simple 2137pattern such as 2138</para> 2139 2140<programlisting> 2141abcd$ 2142</programlisting> 2143 2144<para> 2145when applied to a long string that does not match. Because matching 2146proceeds from left to right, GRegex will look for each "a" in the string 2147and then see if what follows matches the rest of the pattern. If the 2148pattern is specified as 2149</para> 2150 2151<programlisting> 2152^.*abcd$ 2153</programlisting> 2154 2155<para> 2156the initial .* matches the entire string at first, but when this fails 2157(because there is no following "a"), it backtracks to match all but the 2158last character, then all but the last two characters, and so on. Once 2159again the search for "a" covers the entire string, from right to left, 2160so we are no better off. However, if the pattern is written as 2161</para> 2162 2163<programlisting> 2164^.*+(?<=abcd) 2165</programlisting> 2166 2167<para> 2168there can be no backtracking for the .*+ item; it can match only the 2169entire string. The subsequent lookbehind assertion does a single test 2170on the last four characters. If it fails, the match fails immediately. 2171For long strings, this approach makes a significant difference to the 2172processing time. 2173</para> 2174</refsect2> 2175 2176<refsect2> 2177<title>Using multiple assertions</title> 2178<para> 2179Several assertions (of any sort) may occur in succession. For example, 2180</para> 2181 2182<programlisting> 2183(?<=\d{3})(?<!999)foo 2184</programlisting> 2185 2186<para> 2187matches "foo" preceded by three digits that are not "999". Notice that 2188each of the assertions is applied independently at the same point in 2189the string. First there is a check that the previous three 2190characters are all digits, and then there is a check that the same 2191three characters are not "999". This pattern does not match "foo" preceded 2192by six characters, the first of which are digits and the last 2193three of which are not "999". For example, it doesn’t match "123abcfoo". 2194A pattern to do that is 2195</para> 2196 2197<programlisting> 2198(?<=\d{3}...)(?<!999)foo 2199</programlisting> 2200 2201<para> 2202This time the first assertion looks at the preceding six characters, 2203checking that the first three are digits, and then the second assertion 2204checks that the preceding three characters are not "999". 2205</para> 2206 2207<para> 2208Assertions can be nested in any combination. For example, 2209</para> 2210 2211<programlisting> 2212(?<=(?<!foo)bar)baz 2213</programlisting> 2214 2215<para> 2216matches an occurrence of "baz" that is preceded by "bar" which in turn 2217is not preceded by "foo", while 2218</para> 2219 2220<programlisting> 2221(?<=\d{3}(?!999)...)foo 2222</programlisting> 2223 2224<para> 2225is another pattern that matches "foo" preceded by three digits and any 2226three characters that are not "999". 2227</para> 2228</refsect2> 2229</refsect1> 2230 2231<refsect1> 2232<title>Conditional subpatterns</title> 2233<para> 2234It is possible to cause the matching process to obey a subpattern 2235conditionally or to choose between two alternative subpatterns, depending 2236on the result of an assertion, or whether a previous capturing subpattern 2237matched or not. The two possible forms of conditional subpattern are 2238</para> 2239 2240<programlisting> 2241(?(condition)yes-pattern) 2242(?(condition)yes-pattern|no-pattern) 2243</programlisting> 2244 2245<para> 2246If the condition is satisfied, the yes-pattern is used; otherwise the 2247no-pattern (if present) is used. If there are more than two alternatives 2248in the subpattern, a compile-time error occurs. 2249</para> 2250 2251<para> 2252There are four kinds of condition: references to subpatterns, references to 2253recursion, a pseudo-condition called DEFINE, and assertions. 2254</para> 2255 2256<refsect2> 2257<title>Checking for a used subpattern by number</title> 2258<para> 2259If the text between the parentheses consists of a sequence of digits, the 2260condition is true if the capturing subpattern of that number has previously 2261matched. 2262</para> 2263 2264<para> 2265Consider the following pattern, which contains non-significant white space 2266to make it more readable (assume the <varname>G_REGEX_EXTENDED</varname>) 2267and to divide it into three parts for ease of discussion: 2268</para> 2269 2270<programlisting> 2271( \( )? [^()]+ (?(1) \) ) 2272</programlisting> 2273 2274<para> 2275The first part matches an optional opening parenthesis, and if that 2276character is present, sets it as the first captured substring. The second 2277part matches one or more characters that are not parentheses. The 2278third part is a conditional subpattern that tests whether the first set 2279of parentheses matched or not. If they did, that is, if string started 2280with an opening parenthesis, the condition is true, and so the yes-pattern 2281is executed and a closing parenthesis is required. Otherwise, 2282since no-pattern is not present, the subpattern matches nothing. In 2283other words, this pattern matches a sequence of non-parentheses, 2284optionally enclosed in parentheses. 2285</para> 2286</refsect2> 2287 2288<refsect2> 2289<title>Checking for a used subpattern by name</title> 2290<para> 2291Perl uses the syntax (?(<name>)...) or (?('name')...) to test for a used 2292subpattern by name, the Python syntax (?(name)...) is also recognized. However, 2293there is a possible ambiguity with this syntax, because subpattern names may 2294consist entirely of digits. GRegex looks first for a named subpattern; if it 2295cannot find one and the name consists entirely of digits, GRegex looks for a 2296subpattern of that number, which must be greater than zero. Using subpattern 2297names that consist entirely of digits is not recommended. 2298</para> 2299 2300<para> 2301Rewriting the above example to use a named subpattern gives this: 2302</para> 2303 2304<programlisting> 2305(?<OPEN> \( )? [^()]+ (?(<OPEN>) \) ) 2306</programlisting> 2307</refsect2> 2308 2309<refsect2> 2310<title>Checking for pattern recursion</title> 2311<para> 2312If the condition is the string (R), and there is no subpattern with the name R, 2313the condition is true if a recursive call to the whole pattern or any 2314subpattern has been made. If digits or a name preceded by ampersand follow the 2315letter R, for example: 2316</para> 2317 2318<programlisting> 2319(?(R3)...) 2320(?(R&name)...) 2321</programlisting> 2322 2323<para> 2324the condition is true if the most recent recursion is into the subpattern whose 2325number or name is given. This condition does not check the entire recursion 2326stack. 2327</para> 2328 2329<para> 2330At "top level", all these recursion test conditions are false. Recursive 2331patterns are described below. 2332</para> 2333</refsect2> 2334 2335<refsect2> 2336<title>Defining subpatterns for use by reference only</title> 2337<para> 2338If the condition is the string (DEFINE), and there is no subpattern with the 2339name DEFINE, the condition is always false. In this case, there may be only one 2340alternative in the subpattern. It is always skipped if control reaches this 2341point in the pattern; the idea of DEFINE is that it can be used to define 2342"subroutines" that can be referenced from elsewhere. (The use of "subroutines" 2343is described below.) For example, a pattern to match an IPv4 address could be 2344written like this (ignore whitespace and line breaks): 2345</para> 2346 2347<programlisting> 2348(?(DEFINE) (?<byte> 2[0-4]\d | 25[0-5] | 1\d\d | [1-9]?\d) ) 2349\b (?&byte) (\.(?&byte)){3} \b 2350</programlisting> 2351 2352<para> 2353The first part of the pattern is a DEFINE group inside which a another group 2354named "byte" is defined. This matches an individual component of an IPv4 2355address (a number less than 256). When matching takes place, this part of the 2356pattern is skipped because DEFINE acts like a false condition. 2357</para> 2358 2359<para> 2360The rest of the pattern uses references to the named group to match the four 2361dot-separated components of an IPv4 address, insisting on a word boundary at 2362each end. 2363</para> 2364</refsect2> 2365 2366<refsect2> 2367<title>Assertion conditions</title> 2368<para> 2369If the condition is not in any of the above formats, it must be an 2370assertion. This may be a positive or negative lookahead or lookbehind 2371assertion. Consider this pattern, again containing non-significant 2372white space, and with the two alternatives on the second line: 2373</para> 2374 2375<programlisting> 2376(?(?=[^a-z]*[a-z]) 2377\d{2}-[a-z]{3}-\d{2} | \d{2}-\d{2}-\d{2} ) 2378</programlisting> 2379 2380<para> 2381The condition is a positive lookahead assertion that matches an 2382optional sequence of non-letters followed by a letter. In other words, 2383it tests for the presence of at least one letter in the string. If a 2384letter is found, the string is matched against the first alternative; 2385otherwise it is matched against the second. This pattern matches 2386strings in one of the two forms dd-aaa-dd or dd-dd-dd, where aaa are 2387letters and dd are digits. 2388</para> 2389</refsect2> 2390</refsect1> 2391 2392<refsect1> 2393<title>Comments</title> 2394<para> 2395The sequence (?# marks the start of a comment that continues up to the 2396next closing parenthesis. Nested parentheses are not permitted. The 2397characters that make up a comment play no part in the pattern matching 2398at all. 2399</para> 2400 2401<para> 2402If the <varname>G_REGEX_EXTENDED</varname> option is set, an unescaped # 2403character outside a character class introduces a comment that continues to 2404immediately after the next newline in the pattern. 2405</para> 2406</refsect1> 2407 2408<refsect1> 2409<title>Recursive patterns</title> 2410<para> 2411Consider the problem of matching a string in parentheses, allowing for 2412unlimited nested parentheses. Without the use of recursion, the best 2413that can be done is to use a pattern that matches up to some fixed 2414depth of nesting. It is not possible to handle an arbitrary nesting 2415depth. 2416</para> 2417 2418<para> 2419For some time, Perl has provided a facility that allows regular expressions to 2420recurse (amongst other things). It does this by interpolating Perl code in the 2421expression at run time, and the code can refer to the expression itself. A Perl 2422pattern using code interpolation to solve the parentheses problem can be 2423created like this: 2424</para> 2425 2426<programlisting> 2427$re = qr{\( (?: (?>[^()]+) | (?p{$re}) )* \)}x; 2428</programlisting> 2429 2430<para> 2431The (?p{...}) item interpolates Perl code at run time, and in this case refers 2432recursively to the pattern in which it appears. 2433</para> 2434 2435<para> 2436Obviously, GRegex cannot support the interpolation of Perl code. Instead, it 2437supports special syntax for recursion of the entire pattern, and also for 2438individual subpattern recursion. This kind of recursion was introduced into 2439Perl at release 5.10. 2440</para> 2441 2442<para> 2443A special item that consists of (? followed by a number greater than zero and a 2444closing parenthesis is a recursive call of the subpattern of the given number, 2445provided that it occurs inside that subpattern. (If not, it is a "subroutine" 2446call, which is described in the next section.) The special item (?R) or (?0) is 2447a recursive call of the entire regular expression. 2448</para> 2449 2450<para> 2451In GRegex (like Python, but unlike Perl), a recursive subpattern call is always 2452treated as an atomic group. That is, once it has matched some of the subject 2453string, it is never re-entered, even if it contains untried alternatives and 2454there is a subsequent matching failure. 2455</para> 2456 2457<para> 2458This pattern solves the nested parentheses problem (assume the 2459<varname>G_REGEX_EXTENDED</varname> option is set so that white space is 2460ignored): 2461</para> 2462 2463<programlisting> 2464\( ( (?>[^()]+) | (?R) )* \) 2465</programlisting> 2466 2467<para> 2468First it matches an opening parenthesis. Then it matches any number of 2469substrings which can either be a sequence of non-parentheses, or a 2470recursive match of the pattern itself (that is, a correctly parenthesized 2471substring). Finally there is a closing parenthesis. 2472</para> 2473 2474<para> 2475If this were part of a larger pattern, you would not want to recurse 2476the entire pattern, so instead you could use this: 2477</para> 2478 2479<programlisting> 2480( \( ( (?>[^()]+) | (?1) )* \) ) 2481</programlisting> 2482 2483<para> 2484We have put the pattern into parentheses, and caused the recursion to 2485refer to them instead of the whole pattern. In a larger pattern, keeping 2486track of parenthesis numbers can be tricky. It may be more convenient to 2487use named parentheses instead. 2488The Perl syntax for this is (?&name); GRegex also supports the(?P>name) 2489syntac. We could rewrite the above example as follows: 2490</para> 2491 2492<programlisting> 2493(?<pn> \( ( (?>[^()]+) | (?&pn) )* \) ) 2494</programlisting> 2495 2496<para> 2497If there is more than one subpattern with the same name, the earliest one is 2498used. This particular example pattern contains nested unlimited repeats, and so 2499the use of atomic grouping for matching strings of non-parentheses is important 2500when applying the pattern to strings that do not match. 2501For example, when this pattern is applied to 2502</para> 2503 2504<programlisting> 2505(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa() 2506</programlisting> 2507 2508<para> 2509it yields "no match" quickly. However, if atomic grouping is not used, 2510the match runs for a very long time indeed because there are so many 2511different ways the + and * repeats can carve up the string, and all 2512have to be tested before failure can be reported. 2513</para> 2514 2515<para> 2516At the end of a match, the values set for any capturing subpatterns are 2517those from the outermost level of the recursion at which the subpattern 2518value is set. 2519 2520<!-- Callouts are not supported by GRegex 2521If you want to obtain intermediate values, a callout 2522function can be used (see below and the pcrecallout documentation). --> 2523 2524If the pattern above is matched against 2525</para> 2526 2527<programlisting> 2528(ab(cd)ef) 2529</programlisting> 2530 2531<para> 2532the value for the capturing parentheses is "ef", which is the last 2533value taken on at the top level. If additional parentheses are added, 2534giving 2535</para> 2536 2537<programlisting> 2538\( ( ( (?>[^()]+) | (?R) )* ) \) 2539 ^ ^ 2540 ^ ^ 2541</programlisting> 2542 2543<para> 2544the string they capture is "ab(cd)ef", the contents of the top level 2545parentheses. 2546</para> 2547 2548<para> 2549Do not confuse the (?R) item with the condition (R), which tests for 2550recursion. Consider this pattern, which matches text in angle brackets, 2551allowing for arbitrary nesting. Only digits are allowed in nested 2552brackets (that is, when recursing), whereas any characters are permitted 2553at the outer level. 2554</para> 2555 2556<programlisting> 2557< (?: (?(R) \d++ | [^<>]*+) | (?R)) * > 2558</programlisting> 2559 2560<para> 2561In this pattern, (?(R) is the start of a conditional subpattern, with 2562two different alternatives for the recursive and non-recursive cases. 2563The (?R) item is the actual recursive call. 2564</para> 2565</refsect1> 2566 2567<refsect1> 2568<title>Subpatterns as subroutines</title> 2569<para> 2570If the syntax for a recursive subpattern reference (either by number or 2571by name) is used outside the parentheses to which it refers, it operates 2572like a subroutine in a programming language. The "called" subpattern may 2573be defined before or after the reference. An earlier example pointed out 2574that the pattern 2575</para> 2576 2577<programlisting> 2578(sens|respons)e and \1ibility 2579</programlisting> 2580 2581<para> 2582matches "sense and sensibility" and "response and responsibility", but 2583not "sense and responsibility". If instead the pattern 2584</para> 2585 2586<programlisting> 2587(sens|respons)e and (?1)ibility 2588</programlisting> 2589 2590<para> 2591is used, it does match "sense and responsibility" as well as the other 2592two strings. Another example is given in the discussion of DEFINE above. 2593</para> 2594 2595<para> 2596Like recursive subpatterns, a "subroutine" call is always treated as an atomic 2597group. That is, once it has matched some of the string, it is never 2598re-entered, even if it contains untried alternatives and there is a subsequent 2599matching failure. 2600</para> 2601 2602<para> 2603When a subpattern is used as a subroutine, processing options such as 2604case-independence are fixed when the subpattern is defined. They cannot be 2605changed for different calls. For example, consider this pattern: 2606</para> 2607 2608<programlisting> 2609(abc)(?i:(?1)) 2610</programlisting> 2611 2612<para> 2613It matches "abcabc". It does not match "abcABC" because the change of 2614processing option does not affect the called subpattern. 2615</para> 2616</refsect1> 2617 2618<!-- Callouts are not supported by GRegex 2619<refsect1> 2620<title>Callouts</title> 2621<para> 2622Perl has a feature whereby using the sequence (?{...}) causes arbitrary 2623Perl code to be obeyed in the middle of matching a regular expression. 2624This makes it possible, amongst other things, to extract different substrings that match the same pair of parentheses when there is a repetition. 2625</para> 2626 2627<para> 2628PCRE provides a similar feature, but of course it cannot obey arbitrary 2629Perl code. The feature is called "callout". The caller of PCRE provides 2630an external function by putting its entry point in the global variable 2631pcre_callout. By default, this variable contains NULL, which disables 2632all calling out. 2633</para> 2634 2635<para> 2636Within a regular expression, (?C) indicates the points at which the 2637external function is to be called. If you want to identify different 2638callout points, you can put a number less than 256 after the letter C. 2639The default value is zero. For example, this pattern has two callout 2640points: 2641</para> 2642 2643<programlisting> 2644(?C1)abc(?C2)def 2645</programlisting> 2646 2647<para> 2648If the PCRE_AUTO_CALLOUT flag is passed to pcre_compile(), callouts are 2649automatically installed before each item in the pattern. They are all 2650numbered 255. 2651</para> 2652 2653<para> 2654During matching, when PCRE reaches a callout point (and pcre_callout is 2655set), the external function is called. It is provided with the number 2656of the callout, the position in the pattern, and, optionally, one item 2657of data originally supplied by the caller of pcre_exec(). The callout 2658function may cause matching to proceed, to backtrack, or to fail altogether. A complete description of the interface to the callout function 2659is given in the pcrecallout documentation. 2660</para> 2661</refsect1> 2662--> 2663 2664<refsect1> 2665<title>Copyright</title> 2666<para> 2667This document was copied and adapted from the PCRE documentation, 2668specifically from the man page for pcrepattern. 2669The original copyright note is: 2670</para> 2671 2672<programlisting> 2673Copyright (c) 1997-2006 University of Cambridge. 2674 2675Redistribution and use in source and binary forms, with or without 2676modification, are permitted provided that the following conditions are met: 2677 2678 * Redistributions of source code must retain the above copyright notice, 2679 this list of conditions and the following disclaimer. 2680 2681 * Redistributions in binary form must reproduce the above copyright 2682 notice, this list of conditions and the following disclaimer in the 2683 documentation and/or other materials provided with the distribution. 2684 2685 * Neither the name of the University of Cambridge nor the name of Google 2686 Inc. nor the names of their contributors may be used to endorse or 2687 promote products derived from this software without specific prior 2688 written permission. 2689 2690THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 2691AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 2692IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 2693ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 2694LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 2695CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 2696SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 2697INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 2698CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 2699ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 2700POSSIBILITY OF SUCH DAMAGE. 2701</programlisting> 2702</refsect1> 2703 2704</refentry> 2705