1<html> 2<head> 3<title>pcre2pattern specification</title> 4</head> 5<body bgcolor="#FFFFFF" text="#00005A" link="#0066FF" alink="#3399FF" vlink="#2222BB"> 6<h1>pcre2pattern man page</h1> 7<p> 8Return to the <a href="index.html">PCRE2 index page</a>. 9</p> 10<p> 11This page is part of the PCRE2 HTML documentation. It was generated 12automatically from the original man page. If there is any nonsense in it, 13please consult the man page, in case the conversion went wrong. 14<br> 15<ul> 16<li><a name="TOC1" href="#SEC1">PCRE2 REGULAR EXPRESSION DETAILS</a> 17<li><a name="TOC2" href="#SEC2">SPECIAL START-OF-PATTERN ITEMS</a> 18<li><a name="TOC3" href="#SEC3">EBCDIC CHARACTER CODES</a> 19<li><a name="TOC4" href="#SEC4">CHARACTERS AND METACHARACTERS</a> 20<li><a name="TOC5" href="#SEC5">BACKSLASH</a> 21<li><a name="TOC6" href="#SEC6">CIRCUMFLEX AND DOLLAR</a> 22<li><a name="TOC7" href="#SEC7">FULL STOP (PERIOD, DOT) AND \N</a> 23<li><a name="TOC8" href="#SEC8">MATCHING A SINGLE CODE UNIT</a> 24<li><a name="TOC9" href="#SEC9">SQUARE BRACKETS AND CHARACTER CLASSES</a> 25<li><a name="TOC10" href="#SEC10">POSIX CHARACTER CLASSES</a> 26<li><a name="TOC11" href="#SEC11">COMPATIBILITY FEATURE FOR WORD BOUNDARIES</a> 27<li><a name="TOC12" href="#SEC12">VERTICAL BAR</a> 28<li><a name="TOC13" href="#SEC13">INTERNAL OPTION SETTING</a> 29<li><a name="TOC14" href="#SEC14">SUBPATTERNS</a> 30<li><a name="TOC15" href="#SEC15">DUPLICATE SUBPATTERN NUMBERS</a> 31<li><a name="TOC16" href="#SEC16">NAMED SUBPATTERNS</a> 32<li><a name="TOC17" href="#SEC17">REPETITION</a> 33<li><a name="TOC18" href="#SEC18">ATOMIC GROUPING AND POSSESSIVE QUANTIFIERS</a> 34<li><a name="TOC19" href="#SEC19">BACKREFERENCES</a> 35<li><a name="TOC20" href="#SEC20">ASSERTIONS</a> 36<li><a name="TOC21" href="#SEC21">CONDITIONAL SUBPATTERNS</a> 37<li><a name="TOC22" href="#SEC22">COMMENTS</a> 38<li><a name="TOC23" href="#SEC23">RECURSIVE PATTERNS</a> 39<li><a name="TOC24" href="#SEC24">SUBPATTERNS AS SUBROUTINES</a> 40<li><a name="TOC25" href="#SEC25">ONIGURUMA SUBROUTINE SYNTAX</a> 41<li><a name="TOC26" href="#SEC26">CALLOUTS</a> 42<li><a name="TOC27" href="#SEC27">BACKTRACKING CONTROL</a> 43<li><a name="TOC28" href="#SEC28">SEE ALSO</a> 44<li><a name="TOC29" href="#SEC29">AUTHOR</a> 45<li><a name="TOC30" href="#SEC30">REVISION</a> 46</ul> 47<br><a name="SEC1" href="#TOC1">PCRE2 REGULAR EXPRESSION DETAILS</a><br> 48<P> 49The syntax and semantics of the regular expressions that are supported by PCRE2 50are described in detail below. There is a quick-reference syntax summary in the 51<a href="pcre2syntax.html"><b>pcre2syntax</b></a> 52page. PCRE2 tries to match Perl syntax and semantics as closely as it can. 53PCRE2 also supports some alternative regular expression syntax (which does not 54conflict with the Perl syntax) in order to provide some compatibility with 55regular expressions in Python, .NET, and Oniguruma. 56</P> 57<P> 58Perl's regular expressions are described in its own documentation, and regular 59expressions in general are covered in a number of books, some of which have 60copious examples. Jeffrey Friedl's "Mastering Regular Expressions", published 61by O'Reilly, covers regular expressions in great detail. This description of 62PCRE2's regular expressions is intended as reference material. 63</P> 64<P> 65This document discusses the patterns that are supported by PCRE2 when its main 66matching function, <b>pcre2_match()</b>, is used. PCRE2 also has an alternative 67matching function, <b>pcre2_dfa_match()</b>, which matches using a different 68algorithm that is not Perl-compatible. Some of the features discussed below are 69not available when DFA matching is used. The advantages and disadvantages of 70the alternative function, and how it differs from the normal function, are 71discussed in the 72<a href="pcre2matching.html"><b>pcre2matching</b></a> 73page. 74</P> 75<br><a name="SEC2" href="#TOC1">SPECIAL START-OF-PATTERN ITEMS</a><br> 76<P> 77A number of options that can be passed to <b>pcre2_compile()</b> can also be set 78by special items at the start of a pattern. These are not Perl-compatible, but 79are provided to make these options accessible to pattern writers who are not 80able to change the program that processes the pattern. Any number of these 81items may appear, but they must all be together right at the start of the 82pattern string, and the letters must be in upper case. 83</P> 84<br><b> 85UTF support 86</b><br> 87<P> 88In the 8-bit and 16-bit PCRE2 libraries, characters may be coded either as 89single code units, or as multiple UTF-8 or UTF-16 code units. UTF-32 can be 90specified for the 32-bit library, in which case it constrains the character 91values to valid Unicode code points. To process UTF strings, PCRE2 must be 92built to include Unicode support (which is the default). When using UTF strings 93you must either call the compiling function with the PCRE2_UTF option, or the 94pattern must start with the special sequence (*UTF), which is equivalent to 95setting the relevant option. How setting a UTF mode affects pattern matching is 96mentioned in several places below. There is also a summary of features in the 97<a href="pcre2unicode.html"><b>pcre2unicode</b></a> 98page. 99</P> 100<P> 101Some applications that allow their users to supply patterns may wish to 102restrict them to non-UTF data for security reasons. If the PCRE2_NEVER_UTF 103option is passed to <b>pcre2_compile()</b>, (*UTF) is not allowed, and its 104appearance in a pattern causes an error. 105</P> 106<br><b> 107Unicode property support 108</b><br> 109<P> 110Another special sequence that may appear at the start of a pattern is (*UCP). 111This has the same effect as setting the PCRE2_UCP option: it causes sequences 112such as \d and \w to use Unicode properties to determine character types, 113instead of recognizing only characters with codes less than 256 via a lookup 114table. 115</P> 116<P> 117Some applications that allow their users to supply patterns may wish to 118restrict them for security reasons. If the PCRE2_NEVER_UCP option is passed to 119<b>pcre2_compile()</b>, (*UCP) is not allowed, and its appearance in a pattern 120causes an error. 121</P> 122<br><b> 123Locking out empty string matching 124</b><br> 125<P> 126Starting a pattern with (*NOTEMPTY) or (*NOTEMPTY_ATSTART) has the same effect 127as passing the PCRE2_NOTEMPTY or PCRE2_NOTEMPTY_ATSTART option to whichever 128matching function is subsequently called to match the pattern. These options 129lock out the matching of empty strings, either entirely, or only at the start 130of the subject. 131</P> 132<br><b> 133Disabling auto-possessification 134</b><br> 135<P> 136If a pattern starts with (*NO_AUTO_POSSESS), it has the same effect as setting 137the PCRE2_NO_AUTO_POSSESS option. This stops PCRE2 from making quantifiers 138possessive when what follows cannot match the repeated item. For example, by 139default a+b is treated as a++b. For more details, see the 140<a href="pcre2api.html"><b>pcre2api</b></a> 141documentation. 142</P> 143<br><b> 144Disabling start-up optimizations 145</b><br> 146<P> 147If a pattern starts with (*NO_START_OPT), it has the same effect as setting the 148PCRE2_NO_START_OPTIMIZE option. This disables several optimizations for quickly 149reaching "no match" results. For more details, see the 150<a href="pcre2api.html"><b>pcre2api</b></a> 151documentation. 152</P> 153<br><b> 154Disabling automatic anchoring 155</b><br> 156<P> 157If a pattern starts with (*NO_DOTSTAR_ANCHOR), it has the same effect as 158setting the PCRE2_NO_DOTSTAR_ANCHOR option. This disables optimizations that 159apply to patterns whose top-level branches all start with .* (match any number 160of arbitrary characters). For more details, see the 161<a href="pcre2api.html"><b>pcre2api</b></a> 162documentation. 163</P> 164<br><b> 165Disabling JIT compilation 166</b><br> 167<P> 168If a pattern that starts with (*NO_JIT) is successfully compiled, an attempt by 169the application to apply the JIT optimization by calling 170<b>pcre2_jit_compile()</b> is ignored. 171</P> 172<br><b> 173Setting match resource limits 174</b><br> 175<P> 176The <b>pcre2_match()</b> function contains a counter that is incremented every 177time it goes round its main loop. The caller of <b>pcre2_match()</b> can set a 178limit on this counter, which therefore limits the amount of computing resource 179used for a match. The maximum depth of nested backtracking can also be limited; 180this indirectly restricts the amount of heap memory that is used, but there is 181also an explicit memory limit that can be set. 182</P> 183<P> 184These facilities are provided to catch runaway matches that are provoked by 185patterns with huge matching trees (a typical example is a pattern with nested 186unlimited repeats applied to a long string that does not match). When one of 187these limits is reached, <b>pcre2_match()</b> gives an error return. The limits 188can also be set by items at the start of the pattern of the form 189<pre> 190 (*LIMIT_HEAP=d) 191 (*LIMIT_MATCH=d) 192 (*LIMIT_DEPTH=d) 193</pre> 194where d is any number of decimal digits. However, the value of the setting must 195be less than the value set (or defaulted) by the caller of <b>pcre2_match()</b> 196for it to have any effect. In other words, the pattern writer can lower the 197limits set by the programmer, but not raise them. If there is more than one 198setting of one of these limits, the lower value is used. The heap limit is 199specified in kibibytes (units of 1024 bytes). 200</P> 201<P> 202Prior to release 10.30, LIMIT_DEPTH was called LIMIT_RECURSION. This name is 203still recognized for backwards compatibility. 204</P> 205<P> 206The heap limit applies only when the <b>pcre2_match()</b> or 207<b>pcre2_dfa_match()</b> interpreters are used for matching. It does not apply 208to JIT. The match limit is used (but in a different way) when JIT is being 209used, or when <b>pcre2_dfa_match()</b> is called, to limit computing resource 210usage by those matching functions. The depth limit is ignored by JIT but is 211relevant for DFA matching, which uses function recursion for recursions within 212the pattern and for lookaround assertions and atomic groups. In this case, the 213depth limit controls the depth of such recursion. 214<a name="newlines"></a></P> 215<br><b> 216Newline conventions 217</b><br> 218<P> 219PCRE2 supports six different conventions for indicating line breaks in 220strings: a single CR (carriage return) character, a single LF (linefeed) 221character, the two-character sequence CRLF, any of the three preceding, any 222Unicode newline sequence, or the NUL character (binary zero). The 223<a href="pcre2api.html"><b>pcre2api</b></a> 224page has 225<a href="pcre2api.html#newlines">further discussion</a> 226about newlines, and shows how to set the newline convention when calling 227<b>pcre2_compile()</b>. 228</P> 229<P> 230It is also possible to specify a newline convention by starting a pattern 231string with one of the following sequences: 232<pre> 233 (*CR) carriage return 234 (*LF) linefeed 235 (*CRLF) carriage return, followed by linefeed 236 (*ANYCRLF) any of the three above 237 (*ANY) all Unicode newline sequences 238 (*NUL) the NUL character (binary zero) 239</pre> 240These override the default and the options given to the compiling function. For 241example, on a Unix system where LF is the default newline sequence, the pattern 242<pre> 243 (*CR)a.b 244</pre> 245changes the convention to CR. That pattern matches "a\nb" because LF is no 246longer a newline. If more than one of these settings is present, the last one 247is used. 248</P> 249<P> 250The newline convention affects where the circumflex and dollar assertions are 251true. It also affects the interpretation of the dot metacharacter when 252PCRE2_DOTALL is not set, and the behaviour of \N when not followed by an 253opening brace. However, it does not affect what the \R escape sequence 254matches. By default, this is any Unicode newline sequence, for Perl 255compatibility. However, this can be changed; see the next section and the 256description of \R in the section entitled 257<a href="#newlineseq">"Newline sequences"</a> 258below. A change of \R setting can be combined with a change of newline 259convention. 260</P> 261<br><b> 262Specifying what \R matches 263</b><br> 264<P> 265It is possible to restrict \R to match only CR, LF, or CRLF (instead of the 266complete set of Unicode line endings) by setting the option PCRE2_BSR_ANYCRLF 267at compile time. This effect can also be achieved by starting a pattern with 268(*BSR_ANYCRLF). For completeness, (*BSR_UNICODE) is also recognized, 269corresponding to PCRE2_BSR_UNICODE. 270</P> 271<br><a name="SEC3" href="#TOC1">EBCDIC CHARACTER CODES</a><br> 272<P> 273PCRE2 can be compiled to run in an environment that uses EBCDIC as its 274character code instead of ASCII or Unicode (typically a mainframe system). In 275the sections below, character code values are ASCII or Unicode; in an EBCDIC 276environment these characters may have different code values, and there are no 277code points greater than 255. 278</P> 279<br><a name="SEC4" href="#TOC1">CHARACTERS AND METACHARACTERS</a><br> 280<P> 281A regular expression is a pattern that is matched against a subject string from 282left to right. Most characters stand for themselves in a pattern, and match the 283corresponding characters in the subject. As a trivial example, the pattern 284<pre> 285 The quick brown fox 286</pre> 287matches a portion of a subject string that is identical to itself. When 288caseless matching is specified (the PCRE2_CASELESS option), letters are matched 289independently of case. 290</P> 291<P> 292The power of regular expressions comes from the ability to include alternatives 293and repetitions in the pattern. These are encoded in the pattern by the use of 294<i>metacharacters</i>, which do not stand for themselves but instead are 295interpreted in some special way. 296</P> 297<P> 298There are two different sets of metacharacters: those that are recognized 299anywhere in the pattern except within square brackets, and those that are 300recognized within square brackets. Outside square brackets, the metacharacters 301are as follows: 302<pre> 303 \ general escape character with several uses 304 ^ assert start of string (or line, in multiline mode) 305 $ assert end of string (or line, in multiline mode) 306 . match any character except newline (by default) 307 [ start character class definition 308 | start of alternative branch 309 ( start subpattern 310 ) end subpattern 311 ? extends the meaning of ( 312 also 0 or 1 quantifier 313 also quantifier minimizer 314 * 0 or more quantifier 315 + 1 or more quantifier 316 also "possessive quantifier" 317 { start min/max quantifier 318</pre> 319Part of a pattern that is in square brackets is called a "character class". In 320a character class the only metacharacters are: 321<pre> 322 \ general escape character 323 ^ negate the class, but only if the first character 324 - indicates character range 325 [ POSIX character class (only if followed by POSIX syntax) 326 ] terminates the character class 327</pre> 328The following sections describe the use of each of the metacharacters. 329</P> 330<br><a name="SEC5" href="#TOC1">BACKSLASH</a><br> 331<P> 332The backslash character has several uses. Firstly, if it is followed by a 333character that is not a number or a letter, it takes away any special meaning 334that character may have. This use of backslash as an escape character applies 335both inside and outside character classes. 336</P> 337<P> 338For example, if you want to match a * character, you must write \* in the 339pattern. This escaping action applies whether or not the following character 340would otherwise be interpreted as a metacharacter, so it is always safe to 341precede a non-alphanumeric with backslash to specify that it stands for itself. 342In particular, if you want to match a backslash, you write \\. 343</P> 344<P> 345In a UTF mode, only ASCII numbers and letters have any special meaning after a 346backslash. All other characters (in particular, those whose code points are 347greater than 127) are treated as literals. 348</P> 349<P> 350If a pattern is compiled with the PCRE2_EXTENDED option, most white space in 351the pattern (other than in a character class), and characters between a # 352outside a character class and the next newline, inclusive, are ignored. An 353escaping backslash can be used to include a white space or # character as part 354of the pattern. 355</P> 356<P> 357If you want to remove the special meaning from a sequence of characters, you 358can do so by putting them between \Q and \E. This is different from Perl in 359that $ and @ are handled as literals in \Q...\E sequences in PCRE2, whereas 360in Perl, $ and @ cause variable interpolation. Also, Perl does "double-quotish 361backslash interpolation" on any backslashes between \Q and \E which, its 362documentation says, "may lead to confusing results". PCRE2 treats a backslash 363between \Q and \E just like any other character. Note the following examples: 364<pre> 365 Pattern PCRE2 matches Perl matches 366 367 \Qabc$xyz\E abc$xyz abc followed by the contents of $xyz 368 \Qabc\$xyz\E abc\$xyz abc\$xyz 369 \Qabc\E\$\Qxyz\E abc$xyz abc$xyz 370 \QA\B\E A\B A\B 371 \Q\\E \ \\E 372</pre> 373The \Q...\E sequence is recognized both inside and outside character classes. 374An isolated \E that is not preceded by \Q is ignored. If \Q is not followed 375by \E later in the pattern, the literal interpretation continues to the end of 376the pattern (that is, \E is assumed at the end). If the isolated \Q is inside 377a character class, this causes an error, because the character class is not 378terminated by a closing square bracket. 379<a name="digitsafterbackslash"></a></P> 380<br><b> 381Non-printing characters 382</b><br> 383<P> 384A second use of backslash provides a way of encoding non-printing characters 385in patterns in a visible manner. There is no restriction on the appearance of 386non-printing characters in a pattern, but when a pattern is being prepared by 387text editing, it is often easier to use one of the following escape sequences 388than the binary character it represents. In an ASCII or Unicode environment, 389these escapes are as follows: 390<pre> 391 \a alarm, that is, the BEL character (hex 07) 392 \cx "control-x", where x is any printable ASCII character 393 \e escape (hex 1B) 394 \f form feed (hex 0C) 395 \n linefeed (hex 0A) 396 \r carriage return (hex 0D) 397 \t tab (hex 09) 398 \0dd character with octal code 0dd 399 \ddd character with octal code ddd, or backreference 400 \o{ddd..} character with octal code ddd.. 401 \xhh character with hex code hh 402 \x{hhh..} character with hex code hhh.. 403 \N{U+hhh..} character with Unicode hex code point hhh.. 404 \uhhhh character with hex code hhhh (when PCRE2_ALT_BSUX is set) 405</pre> 406The \N{U+hhh..} escape sequence is recognized only when the PCRE2_UTF option 407is set, that is, when PCRE2 is operating in a Unicode mode. Perl also uses 408\N{name} to specify characters by Unicode name; PCRE2 does not support this. 409Note that when \N is not followed by an opening brace (curly bracket) it has 410an entirely different meaning, matching any character that is not a newline. 411</P> 412<P> 413The precise effect of \cx on ASCII characters is as follows: if x is a lower 414case letter, it is converted to upper case. Then bit 6 of the character (hex 41540) is inverted. Thus \cA to \cZ become hex 01 to hex 1A (A is 41, Z is 5A), 416but \c{ becomes hex 3B ({ is 7B), and \c; becomes hex 7B (; is 3B). If the 417code unit following \c has a value less than 32 or greater than 126, a 418compile-time error occurs. 419</P> 420<P> 421When PCRE2 is compiled in EBCDIC mode, \N{U+hhh..} is not supported. \a, \e, 422\f, \n, \r, and \t generate the appropriate EBCDIC code values. The \c 423escape is processed as specified for Perl in the <b>perlebcdic</b> document. The 424only characters that are allowed after \c are A-Z, a-z, or one of @, [, \, ], 425^, _, or ?. Any other character provokes a compile-time error. The sequence 426\c@ encodes character code 0; after \c the letters (in either case) encode 427characters 1-26 (hex 01 to hex 1A); [, \, ], ^, and _ encode characters 27-31 428(hex 1B to hex 1F), and \c? becomes either 255 (hex FF) or 95 (hex 5F). 429</P> 430<P> 431Thus, apart from \c?, these escapes generate the same character code values as 432they do in an ASCII environment, though the meanings of the values mostly 433differ. For example, \cG always generates code value 7, which is BEL in ASCII 434but DEL in EBCDIC. 435</P> 436<P> 437The sequence \c? generates DEL (127, hex 7F) in an ASCII environment, but 438because 127 is not a control character in EBCDIC, Perl makes it generate the 439APC character. Unfortunately, there are several variants of EBCDIC. In most of 440them the APC character has the value 255 (hex FF), but in the one Perl calls 441POSIX-BC its value is 95 (hex 5F). If certain other characters have POSIX-BC 442values, PCRE2 makes \c? generate 95; otherwise it generates 255. 443</P> 444<P> 445After \0 up to two further octal digits are read. If there are fewer than two 446digits, just those that are present are used. Thus the sequence \0\x\015 447specifies two binary zeros followed by a CR character (code value 13). Make 448sure you supply two digits after the initial zero if the pattern character that 449follows is itself an octal digit. 450</P> 451<P> 452The escape \o must be followed by a sequence of octal digits, enclosed in 453braces. An error occurs if this is not the case. This escape is a recent 454addition to Perl; it provides way of specifying character code points as octal 455numbers greater than 0777, and it also allows octal numbers and backreferences 456to be unambiguously specified. 457</P> 458<P> 459For greater clarity and unambiguity, it is best to avoid following \ by a 460digit greater than zero. Instead, use \o{} or \x{} to specify numerical 461character code points, and \g{} to specify backreferences. The following 462paragraphs describe the old, ambiguous syntax. 463</P> 464<P> 465The handling of a backslash followed by a digit other than 0 is complicated, 466and Perl has changed over time, causing PCRE2 also to change. 467</P> 468<P> 469Outside a character class, PCRE2 reads the digit and any following digits as a 470decimal number. If the number is less than 10, begins with the digit 8 or 9, or 471if there are at least that many previous capturing left parentheses in the 472expression, the entire sequence is taken as a <i>backreference</i>. A 473description of how this works is given 474<a href="#backreferences">later,</a> 475following the discussion of 476<a href="#subpattern">parenthesized subpatterns.</a> 477Otherwise, up to three octal digits are read to form a character code. 478</P> 479<P> 480Inside a character class, PCRE2 handles \8 and \9 as the literal characters 481"8" and "9", and otherwise reads up to three octal digits following the 482backslash, using them to generate a data character. Any subsequent digits stand 483for themselves. For example, outside a character class: 484<pre> 485 \040 is another way of writing an ASCII space 486 \40 is the same, provided there are fewer than 40 previous capturing subpatterns 487 \7 is always a backreference 488 \11 might be a backreference, or another way of writing a tab 489 \011 is always a tab 490 \0113 is a tab followed by the character "3" 491 \113 might be a backreference, otherwise the character with octal code 113 492 \377 might be a backreference, otherwise the value 255 (decimal) 493 \81 is always a backreference .sp 494</pre> 495Note that octal values of 100 or greater that are specified using this syntax 496must not be introduced by a leading zero, because no more than three octal 497digits are ever read. 498</P> 499<P> 500By default, after \x that is not followed by {, from zero to two hexadecimal 501digits are read (letters can be in upper or lower case). Any number of 502hexadecimal digits may appear between \x{ and }. If a character other than 503a hexadecimal digit appears between \x{ and }, or if there is no terminating 504}, an error occurs. 505</P> 506<P> 507If the PCRE2_ALT_BSUX option is set, the interpretation of \x is as just 508described only when it is followed by two hexadecimal digits. Otherwise, it 509matches a literal "x" character. In this mode, support for code points greater 510than 256 is provided by \u, which must be followed by four hexadecimal digits; 511otherwise it matches a literal "u" character. 512</P> 513<P> 514Characters whose value is less than 256 can be defined by either of the two 515syntaxes for \x (or by \u in PCRE2_ALT_BSUX mode). There is no difference in 516the way they are handled. For example, \xdc is exactly the same as \x{dc} (or 517\u00dc in PCRE2_ALT_BSUX mode). 518</P> 519<br><b> 520Constraints on character values 521</b><br> 522<P> 523Characters that are specified using octal or hexadecimal numbers are 524limited to certain values, as follows: 525<pre> 526 8-bit non-UTF mode no greater than 0xff 527 16-bit non-UTF mode no greater than 0xffff 528 32-bit non-UTF mode no greater than 0xffffffff 529 All UTF modes no greater than 0x10ffff and a valid code point 530</pre> 531Invalid Unicode code points are all those in the range 0xd800 to 0xdfff (the 532so-called "surrogate" code points). The check for these can be disabled by the 533caller of <b>pcre2_compile()</b> by setting the option 534PCRE2_EXTRA_ALLOW_SURROGATE_ESCAPES. However, this is possible only in UTF-8 535and UTF-32 modes, because these values are not representable in UTF-16. 536</P> 537<br><b> 538Escape sequences in character classes 539</b><br> 540<P> 541All the sequences that define a single character value can be used both inside 542and outside character classes. In addition, inside a character class, \b is 543interpreted as the backspace character (hex 08). 544</P> 545<P> 546When not followed by an opening brace, \N is not allowed in a character class. 547\B, \R, and \X are not special inside a character class. Like other 548unrecognized alphabetic escape sequences, they cause an error. Outside a 549character class, these sequences have different meanings. 550</P> 551<br><b> 552Unsupported escape sequences 553</b><br> 554<P> 555In Perl, the sequences \F, \l, \L, \u, and \U are recognized by its string 556handler and used to modify the case of following characters. By default, PCRE2 557does not support these escape sequences. However, if the PCRE2_ALT_BSUX option 558is set, \U matches a "U" character, and \u can be used to define a character 559by code point, as described above. 560</P> 561<br><b> 562Absolute and relative backreferences 563</b><br> 564<P> 565The sequence \g followed by a signed or unsigned number, optionally enclosed 566in braces, is an absolute or relative backreference. A named backreference 567can be coded as \g{name}. Backreferences are discussed 568<a href="#backreferences">later,</a> 569following the discussion of 570<a href="#subpattern">parenthesized subpatterns.</a> 571</P> 572<br><b> 573Absolute and relative subroutine calls 574</b><br> 575<P> 576For compatibility with Oniguruma, the non-Perl syntax \g followed by a name or 577a number enclosed either in angle brackets or single quotes, is an alternative 578syntax for referencing a subpattern as a "subroutine". Details are discussed 579<a href="#onigurumasubroutines">later.</a> 580Note that \g{...} (Perl syntax) and \g<...> (Oniguruma syntax) are <i>not</i> 581synonymous. The former is a backreference; the latter is a 582<a href="#subpatternsassubroutines">subroutine</a> 583call. 584<a name="genericchartypes"></a></P> 585<br><b> 586Generic character types 587</b><br> 588<P> 589Another use of backslash is for specifying generic character types: 590<pre> 591 \d any decimal digit 592 \D any character that is not a decimal digit 593 \h any horizontal white space character 594 \H any character that is not a horizontal white space character 595 \N any character that is not a newline 596 \s any white space character 597 \S any character that is not a white space character 598 \v any vertical white space character 599 \V any character that is not a vertical white space character 600 \w any "word" character 601 \W any "non-word" character 602</pre> 603The \N escape sequence has the same meaning as 604<a href="#fullstopdot">the "." metacharacter</a> 605when PCRE2_DOTALL is not set, but setting PCRE2_DOTALL does not change the 606meaning of \N. Note that when \N is followed by an opening brace it has a 607different meaning. See the section entitled 608<a href="#digitsafterbackslash">"Non-printing characters"</a> 609above for details. Perl also uses \N{name} to specify characters by Unicode 610name; PCRE2 does not support this. 611</P> 612<P> 613Each pair of lower and upper case escape sequences partitions the complete set 614of characters into two disjoint sets. Any given character matches one, and only 615one, of each pair. The sequences can appear both inside and outside character 616classes. They each match one character of the appropriate type. If the current 617matching point is at the end of the subject string, all of them fail, because 618there is no character to match. 619</P> 620<P> 621The default \s characters are HT (9), LF (10), VT (11), FF (12), CR (13), and 622space (32), which are defined as white space in the "C" locale. This list may 623vary if locale-specific matching is taking place. For example, in some locales 624the "non-breaking space" character (\xA0) is recognized as white space, and in 625others the VT character is not. 626</P> 627<P> 628A "word" character is an underscore or any character that is a letter or digit. 629By default, the definition of letters and digits is controlled by PCRE2's 630low-valued character tables, and may vary if locale-specific matching is taking 631place (see 632<a href="pcre2api.html#localesupport">"Locale support"</a> 633in the 634<a href="pcre2api.html"><b>pcre2api</b></a> 635page). For example, in a French locale such as "fr_FR" in Unix-like systems, 636or "french" in Windows, some character codes greater than 127 are used for 637accented letters, and these are then matched by \w. The use of locales with 638Unicode is discouraged. 639</P> 640<P> 641By default, characters whose code points are greater than 127 never match \d, 642\s, or \w, and always match \D, \S, and \W, although this may be different 643for characters in the range 128-255 when locale-specific matching is happening. 644These escape sequences retain their original meanings from before Unicode 645support was available, mainly for efficiency reasons. If the PCRE2_UCP option 646is set, the behaviour is changed so that Unicode properties are used to 647determine character types, as follows: 648<pre> 649 \d any character that matches \p{Nd} (decimal digit) 650 \s any character that matches \p{Z} or \h or \v 651 \w any character that matches \p{L} or \p{N}, plus underscore 652</pre> 653The upper case escapes match the inverse sets of characters. Note that \d 654matches only decimal digits, whereas \w matches any Unicode digit, as well as 655any Unicode letter, and underscore. Note also that PCRE2_UCP affects \b, and 656\B because they are defined in terms of \w and \W. Matching these sequences 657is noticeably slower when PCRE2_UCP is set. 658</P> 659<P> 660The sequences \h, \H, \v, and \V, in contrast to the other sequences, which 661match only ASCII characters by default, always match a specific list of code 662points, whether or not PCRE2_UCP is set. The horizontal space characters are: 663<pre> 664 U+0009 Horizontal tab (HT) 665 U+0020 Space 666 U+00A0 Non-break space 667 U+1680 Ogham space mark 668 U+180E Mongolian vowel separator 669 U+2000 En quad 670 U+2001 Em quad 671 U+2002 En space 672 U+2003 Em space 673 U+2004 Three-per-em space 674 U+2005 Four-per-em space 675 U+2006 Six-per-em space 676 U+2007 Figure space 677 U+2008 Punctuation space 678 U+2009 Thin space 679 U+200A Hair space 680 U+202F Narrow no-break space 681 U+205F Medium mathematical space 682 U+3000 Ideographic space 683</pre> 684The vertical space characters are: 685<pre> 686 U+000A Linefeed (LF) 687 U+000B Vertical tab (VT) 688 U+000C Form feed (FF) 689 U+000D Carriage return (CR) 690 U+0085 Next line (NEL) 691 U+2028 Line separator 692 U+2029 Paragraph separator 693</pre> 694In 8-bit, non-UTF-8 mode, only the characters with code points less than 256 695are relevant. 696<a name="newlineseq"></a></P> 697<br><b> 698Newline sequences 699</b><br> 700<P> 701Outside a character class, by default, the escape sequence \R matches any 702Unicode newline sequence. In 8-bit non-UTF-8 mode \R is equivalent to the 703following: 704<pre> 705 (?>\r\n|\n|\x0b|\f|\r|\x85) 706</pre> 707This is an example of an "atomic group", details of which are given 708<a href="#atomicgroup">below.</a> 709This particular group matches either the two-character sequence CR followed by 710LF, or one of the single characters LF (linefeed, U+000A), VT (vertical tab, 711U+000B), FF (form feed, U+000C), CR (carriage return, U+000D), or NEL (next 712line, U+0085). Because this is an atomic group, the two-character sequence is 713treated as a single unit that cannot be split. 714</P> 715<P> 716In other modes, two additional characters whose code points are greater than 255 717are added: LS (line separator, U+2028) and PS (paragraph separator, U+2029). 718Unicode support is not needed for these characters to be recognized. 719</P> 720<P> 721It is possible to restrict \R to match only CR, LF, or CRLF (instead of the 722complete set of Unicode line endings) by setting the option PCRE2_BSR_ANYCRLF 723at compile time. (BSR is an abbrevation for "backslash R".) This can be made 724the default when PCRE2 is built; if this is the case, the other behaviour can 725be requested via the PCRE2_BSR_UNICODE option. It is also possible to specify 726these settings by starting a pattern string with one of the following 727sequences: 728<pre> 729 (*BSR_ANYCRLF) CR, LF, or CRLF only 730 (*BSR_UNICODE) any Unicode newline sequence 731</pre> 732These override the default and the options given to the compiling function. 733Note that these special settings, which are not Perl-compatible, are recognized 734only at the very start of a pattern, and that they must be in upper case. If 735more than one of them is present, the last one is used. They can be combined 736with a change of newline convention; for example, a pattern can start with: 737<pre> 738 (*ANY)(*BSR_ANYCRLF) 739</pre> 740They can also be combined with the (*UTF) or (*UCP) special sequences. Inside a 741character class, \R is treated as an unrecognized escape sequence, and causes 742an error. 743<a name="uniextseq"></a></P> 744<br><b> 745Unicode character properties 746</b><br> 747<P> 748When PCRE2 is built with Unicode support (the default), three additional escape 749sequences that match characters with specific properties are available. In 7508-bit non-UTF-8 mode, these sequences are of course limited to testing 751characters whose code points are less than 256, but they do work in this mode. 752In 32-bit non-UTF mode, code points greater than 0x10ffff (the Unicode limit) 753may be encountered. These are all treated as being in the Common script and 754with an unassigned type. The extra escape sequences are: 755<pre> 756 \p{<i>xx</i>} a character with the <i>xx</i> property 757 \P{<i>xx</i>} a character without the <i>xx</i> property 758 \X a Unicode extended grapheme cluster 759</pre> 760The property names represented by <i>xx</i> above are limited to the Unicode 761script names, the general category properties, "Any", which matches any 762character (including newline), and some special PCRE2 properties (described 763in the 764<a href="#extraprops">next section).</a> 765Other Perl properties such as "InMusicalSymbols" are not supported by PCRE2. 766Note that \P{Any} does not match any characters, so always causes a match 767failure. 768</P> 769<P> 770Sets of Unicode characters are defined as belonging to certain scripts. A 771character from one of these sets can be matched using a script name. For 772example: 773<pre> 774 \p{Greek} 775 \P{Han} 776</pre> 777Those that are not part of an identified script are lumped together as 778"Common". The current list of scripts is: 779</P> 780<P> 781Adlam, 782Ahom, 783Anatolian_Hieroglyphs, 784Arabic, 785Armenian, 786Avestan, 787Balinese, 788Bamum, 789Bassa_Vah, 790Batak, 791Bengali, 792Bhaiksuki, 793Bopomofo, 794Brahmi, 795Braille, 796Buginese, 797Buhid, 798Canadian_Aboriginal, 799Carian, 800Caucasian_Albanian, 801Chakma, 802Cham, 803Cherokee, 804Common, 805Coptic, 806Cuneiform, 807Cypriot, 808Cyrillic, 809Deseret, 810Devanagari, 811Dogra, 812Duployan, 813Egyptian_Hieroglyphs, 814Elbasan, 815Ethiopic, 816Georgian, 817Glagolitic, 818Gothic, 819Grantha, 820Greek, 821Gujarati, 822Gunjala_Gondi, 823Gurmukhi, 824Han, 825Hangul, 826Hanifi_Rohingya, 827Hanunoo, 828Hatran, 829Hebrew, 830Hiragana, 831Imperial_Aramaic, 832Inherited, 833Inscriptional_Pahlavi, 834Inscriptional_Parthian, 835Javanese, 836Kaithi, 837Kannada, 838Katakana, 839Kayah_Li, 840Kharoshthi, 841Khmer, 842Khojki, 843Khudawadi, 844Lao, 845Latin, 846Lepcha, 847Limbu, 848Linear_A, 849Linear_B, 850Lisu, 851Lycian, 852Lydian, 853Mahajani, 854Makasar, 855Malayalam, 856Mandaic, 857Manichaean, 858Marchen, 859Masaram_Gondi, 860Medefaidrin, 861Meetei_Mayek, 862Mende_Kikakui, 863Meroitic_Cursive, 864Meroitic_Hieroglyphs, 865Miao, 866Modi, 867Mongolian, 868Mro, 869Multani, 870Myanmar, 871Nabataean, 872New_Tai_Lue, 873Newa, 874Nko, 875Nushu, 876Ogham, 877Ol_Chiki, 878Old_Hungarian, 879Old_Italic, 880Old_North_Arabian, 881Old_Permic, 882Old_Persian, 883Old_Sogdian, 884Old_South_Arabian, 885Old_Turkic, 886Oriya, 887Osage, 888Osmanya, 889Pahawh_Hmong, 890Palmyrene, 891Pau_Cin_Hau, 892Phags_Pa, 893Phoenician, 894Psalter_Pahlavi, 895Rejang, 896Runic, 897Samaritan, 898Saurashtra, 899Sharada, 900Shavian, 901Siddham, 902SignWriting, 903Sinhala, 904Sogdian, 905Sora_Sompeng, 906Soyombo, 907Sundanese, 908Syloti_Nagri, 909Syriac, 910Tagalog, 911Tagbanwa, 912Tai_Le, 913Tai_Tham, 914Tai_Viet, 915Takri, 916Tamil, 917Tangut, 918Telugu, 919Thaana, 920Thai, 921Tibetan, 922Tifinagh, 923Tirhuta, 924Ugaritic, 925Vai, 926Warang_Citi, 927Yi, 928Zanabazar_Square. 929</P> 930<P> 931Each character has exactly one Unicode general category property, specified by 932a two-letter abbreviation. For compatibility with Perl, negation can be 933specified by including a circumflex between the opening brace and the property 934name. For example, \p{^Lu} is the same as \P{Lu}. 935</P> 936<P> 937If only one letter is specified with \p or \P, it includes all the general 938category properties that start with that letter. In this case, in the absence 939of negation, the curly brackets in the escape sequence are optional; these two 940examples have the same effect: 941<pre> 942 \p{L} 943 \pL 944</pre> 945The following general category property codes are supported: 946<pre> 947 C Other 948 Cc Control 949 Cf Format 950 Cn Unassigned 951 Co Private use 952 Cs Surrogate 953 954 L Letter 955 Ll Lower case letter 956 Lm Modifier letter 957 Lo Other letter 958 Lt Title case letter 959 Lu Upper case letter 960 961 M Mark 962 Mc Spacing mark 963 Me Enclosing mark 964 Mn Non-spacing mark 965 966 N Number 967 Nd Decimal number 968 Nl Letter number 969 No Other number 970 971 P Punctuation 972 Pc Connector punctuation 973 Pd Dash punctuation 974 Pe Close punctuation 975 Pf Final punctuation 976 Pi Initial punctuation 977 Po Other punctuation 978 Ps Open punctuation 979 980 S Symbol 981 Sc Currency symbol 982 Sk Modifier symbol 983 Sm Mathematical symbol 984 So Other symbol 985 986 Z Separator 987 Zl Line separator 988 Zp Paragraph separator 989 Zs Space separator 990</pre> 991The special property L& is also supported: it matches a character that has 992the Lu, Ll, or Lt property, in other words, a letter that is not classified as 993a modifier or "other". 994</P> 995<P> 996The Cs (Surrogate) property applies only to characters in the range U+D800 to 997U+DFFF. Such characters are not valid in Unicode strings and so 998cannot be tested by PCRE2, unless UTF validity checking has been turned off 999(see the discussion of PCRE2_NO_UTF_CHECK in the 1000<a href="pcre2api.html"><b>pcre2api</b></a> 1001page). Perl does not support the Cs property. 1002</P> 1003<P> 1004The long synonyms for property names that Perl supports (such as \p{Letter}) 1005are not supported by PCRE2, nor is it permitted to prefix any of these 1006properties with "Is". 1007</P> 1008<P> 1009No character that is in the Unicode table has the Cn (unassigned) property. 1010Instead, this property is assumed for any code point that is not in the 1011Unicode table. 1012</P> 1013<P> 1014Specifying caseless matching does not affect these escape sequences. For 1015example, \p{Lu} always matches only upper case letters. This is different from 1016the behaviour of current versions of Perl. 1017</P> 1018<P> 1019Matching characters by Unicode property is not fast, because PCRE2 has to do a 1020multistage table lookup in order to find a character's property. That is why 1021the traditional escape sequences such as \d and \w do not use Unicode 1022properties in PCRE2 by default, though you can make them do so by setting the 1023PCRE2_UCP option or by starting the pattern with (*UCP). 1024</P> 1025<br><b> 1026Extended grapheme clusters 1027</b><br> 1028<P> 1029The \X escape matches any number of Unicode characters that form an "extended 1030grapheme cluster", and treats the sequence as an atomic group 1031<a href="#atomicgroup">(see below).</a> 1032Unicode supports various kinds of composite character by giving each character 1033a grapheme breaking property, and having rules that use these properties to 1034define the boundaries of extended grapheme clusters. The rules are defined in 1035Unicode Standard Annex 29, "Unicode Text Segmentation". Unicode 11.0.0 1036abandoned the use of some previous properties that had been used for emojis. 1037Instead it introduced various emoji-specific properties. PCRE2 uses only the 1038Extended Pictographic property. 1039</P> 1040<P> 1041\X always matches at least one character. Then it decides whether to add 1042additional characters according to the following rules for ending a cluster: 1043</P> 1044<P> 10451. End at the end of the subject string. 1046</P> 1047<P> 10482. Do not end between CR and LF; otherwise end after any control character. 1049</P> 1050<P> 10513. Do not break Hangul (a Korean script) syllable sequences. Hangul characters 1052are of five types: L, V, T, LV, and LVT. An L character may be followed by an 1053L, V, LV, or LVT character; an LV or V character may be followed by a V or T 1054character; an LVT or T character may be follwed only by a T character. 1055</P> 1056<P> 10574. Do not end before extending characters or spacing marks or the "zero-width 1058joiner" character. Characters with the "mark" property always have the 1059"extend" grapheme breaking property. 1060</P> 1061<P> 10625. Do not end after prepend characters. 1063</P> 1064<P> 10656. Do not break within emoji modifier sequences or emoji zwj sequences. That 1066is, do not break between characters with the Extended_Pictographic property. 1067Extend and ZWJ characters are allowed between the characters. 1068</P> 1069<P> 10707. Do not break within emoji flag sequences. That is, do not break between 1071regional indicator (RI) characters if there are an odd number of RI characters 1072before the break point. 1073</P> 1074<P> 10758. Otherwise, end the cluster. 1076<a name="extraprops"></a></P> 1077<br><b> 1078PCRE2's additional properties 1079</b><br> 1080<P> 1081As well as the standard Unicode properties described above, PCRE2 supports four 1082more that make it possible to convert traditional escape sequences such as \w 1083and \s to use Unicode properties. PCRE2 uses these non-standard, non-Perl 1084properties internally when PCRE2_UCP is set. However, they may also be used 1085explicitly. These properties are: 1086<pre> 1087 Xan Any alphanumeric character 1088 Xps Any POSIX space character 1089 Xsp Any Perl space character 1090 Xwd Any Perl "word" character 1091</pre> 1092Xan matches characters that have either the L (letter) or the N (number) 1093property. Xps matches the characters tab, linefeed, vertical tab, form feed, or 1094carriage return, and any other character that has the Z (separator) property. 1095Xsp is the same as Xps; in PCRE1 it used to exclude vertical tab, for Perl 1096compatibility, but Perl changed. Xwd matches the same characters as Xan, plus 1097underscore. 1098</P> 1099<P> 1100There is another non-standard property, Xuc, which matches any character that 1101can be represented by a Universal Character Name in C++ and other programming 1102languages. These are the characters $, @, ` (grave accent), and all characters 1103with Unicode code points greater than or equal to U+00A0, except for the 1104surrogates U+D800 to U+DFFF. Note that most base (ASCII) characters are 1105excluded. (Universal Character Names are of the form \uHHHH or \UHHHHHHHH 1106where H is a hexadecimal digit. Note that the Xuc property does not match these 1107sequences but the characters that they represent.) 1108<a name="resetmatchstart"></a></P> 1109<br><b> 1110Resetting the match start 1111</b><br> 1112<P> 1113In normal use, the escape sequence \K causes any previously matched characters 1114not to be included in the final matched sequence that is returned. For example, 1115the pattern: 1116<pre> 1117 foo\Kbar 1118</pre> 1119matches "foobar", but reports that it has matched "bar". \K does not interact 1120with anchoring in any way. The pattern: 1121<pre> 1122 ^foo\Kbar 1123</pre> 1124matches only when the subject begins with "foobar" (in single line mode), 1125though it again reports the matched string as "bar". This feature is similar to 1126a lookbehind assertion 1127<a href="#lookbehind">(described below).</a> 1128However, in this case, the part of the subject before the real match does not 1129have to be of fixed length, as lookbehind assertions do. The use of \K does 1130not interfere with the setting of 1131<a href="#subpattern">captured substrings.</a> 1132For example, when the pattern 1133<pre> 1134 (foo)\Kbar 1135</pre> 1136matches "foobar", the first substring is still set to "foo". 1137</P> 1138<P> 1139Perl documents that the use of \K within assertions is "not well defined". In 1140PCRE2, \K is acted upon when it occurs inside positive assertions, but is 1141ignored in negative assertions. Note that when a pattern such as (?=ab\K) 1142matches, the reported start of the match can be greater than the end of the 1143match. Using \K in a lookbehind assertion at the start of a pattern can also 1144lead to odd effects. For example, consider this pattern: 1145<pre> 1146 (?<=\Kfoo)bar 1147</pre> 1148If the subject is "foobar", a call to <b>pcre2_match()</b> with a starting 1149offset of 3 succeeds and reports the matching string as "foobar", that is, the 1150start of the reported match is earlier than where the match started. 1151<a name="smallassertions"></a></P> 1152<br><b> 1153Simple assertions 1154</b><br> 1155<P> 1156The final use of backslash is for certain simple assertions. An assertion 1157specifies a condition that has to be met at a particular point in a match, 1158without consuming any characters from the subject string. The use of 1159subpatterns for more complicated assertions is described 1160<a href="#bigassertions">below.</a> 1161The backslashed assertions are: 1162<pre> 1163 \b matches at a word boundary 1164 \B matches when not at a word boundary 1165 \A matches at the start of the subject 1166 \Z matches at the end of the subject 1167 also matches before a newline at the end of the subject 1168 \z matches only at the end of the subject 1169 \G matches at the first matching position in the subject 1170</pre> 1171Inside a character class, \b has a different meaning; it matches the backspace 1172character. If any other of these assertions appears in a character class, an 1173"invalid escape sequence" error is generated. 1174</P> 1175<P> 1176A word boundary is a position in the subject string where the current character 1177and the previous character do not both match \w or \W (i.e. one matches 1178\w and the other matches \W), or the start or end of the string if the 1179first or last character matches \w, respectively. In a UTF mode, the meanings 1180of \w and \W can be changed by setting the PCRE2_UCP option. When this is 1181done, it also affects \b and \B. Neither PCRE2 nor Perl has a separate "start 1182of word" or "end of word" metasequence. However, whatever follows \b normally 1183determines which it is. For example, the fragment \ba matches "a" at the start 1184of a word. 1185</P> 1186<P> 1187The \A, \Z, and \z assertions differ from the traditional circumflex and 1188dollar (described in the next section) in that they only ever match at the very 1189start and end of the subject string, whatever options are set. Thus, they are 1190independent of multiline mode. These three assertions are not affected by the 1191PCRE2_NOTBOL or PCRE2_NOTEOL options, which affect only the behaviour of the 1192circumflex and dollar metacharacters. However, if the <i>startoffset</i> 1193argument of <b>pcre2_match()</b> is non-zero, indicating that matching is to 1194start at a point other than the beginning of the subject, \A can never match. 1195The difference between \Z and \z is that \Z matches before a newline at the 1196end of the string as well as at the very end, whereas \z matches only at the 1197end. 1198</P> 1199<P> 1200The \G assertion is true only when the current matching position is at the 1201start point of the matching process, as specified by the <i>startoffset</i> 1202argument of <b>pcre2_match()</b>. It differs from \A when the value of 1203<i>startoffset</i> is non-zero. By calling <b>pcre2_match()</b> multiple times 1204with appropriate arguments, you can mimic Perl's /g option, and it is in this 1205kind of implementation where \G can be useful. 1206</P> 1207<P> 1208Note, however, that PCRE2's implementation of \G, being true at the starting 1209character of the matching process, is subtly different from Perl's, which 1210defines it as true at the end of the previous match. In Perl, these can be 1211different when the previously matched string was empty. Because PCRE2 does just 1212one match at a time, it cannot reproduce this behaviour. 1213</P> 1214<P> 1215If all the alternatives of a pattern begin with \G, the expression is anchored 1216to the starting match position, and the "anchored" flag is set in the compiled 1217regular expression. 1218</P> 1219<br><a name="SEC6" href="#TOC1">CIRCUMFLEX AND DOLLAR</a><br> 1220<P> 1221The circumflex and dollar metacharacters are zero-width assertions. That is, 1222they test for a particular condition being true without consuming any 1223characters from the subject string. These two metacharacters are concerned with 1224matching the starts and ends of lines. If the newline convention is set so that 1225only the two-character sequence CRLF is recognized as a newline, isolated CR 1226and LF characters are treated as ordinary data characters, and are not 1227recognized as newlines. 1228</P> 1229<P> 1230Outside a character class, in the default matching mode, the circumflex 1231character is an assertion that is true only if the current matching point is at 1232the start of the subject string. If the <i>startoffset</i> argument of 1233<b>pcre2_match()</b> is non-zero, or if PCRE2_NOTBOL is set, circumflex can 1234never match if the PCRE2_MULTILINE option is unset. Inside a character class, 1235circumflex has an entirely different meaning 1236<a href="#characterclass">(see below).</a> 1237</P> 1238<P> 1239Circumflex need not be the first character of the pattern if a number of 1240alternatives are involved, but it should be the first thing in each alternative 1241in which it appears if the pattern is ever to match that branch. If all 1242possible alternatives start with a circumflex, that is, if the pattern is 1243constrained to match only at the start of the subject, it is said to be an 1244"anchored" pattern. (There are also other constructs that can cause a pattern 1245to be anchored.) 1246</P> 1247<P> 1248The dollar character is an assertion that is true only if the current matching 1249point is at the end of the subject string, or immediately before a newline at 1250the end of the string (by default), unless PCRE2_NOTEOL is set. Note, however, 1251that it does not actually match the newline. Dollar need not be the last 1252character of the pattern if a number of alternatives are involved, but it 1253should be the last item in any branch in which it appears. Dollar has no 1254special meaning in a character class. 1255</P> 1256<P> 1257The meaning of dollar can be changed so that it matches only at the very end of 1258the string, by setting the PCRE2_DOLLAR_ENDONLY option at compile time. This 1259does not affect the \Z assertion. 1260</P> 1261<P> 1262The meanings of the circumflex and dollar metacharacters are changed if the 1263PCRE2_MULTILINE option is set. When this is the case, a dollar character 1264matches before any newlines in the string, as well as at the very end, and a 1265circumflex matches immediately after internal newlines as well as at the start 1266of the subject string. It does not match after a newline that ends the string, 1267for compatibility with Perl. However, this can be changed by setting the 1268PCRE2_ALT_CIRCUMFLEX option. 1269</P> 1270<P> 1271For example, the pattern /^abc$/ matches the subject string "def\nabc" (where 1272\n represents a newline) in multiline mode, but not otherwise. Consequently, 1273patterns that are anchored in single line mode because all branches start with 1274^ are not anchored in multiline mode, and a match for circumflex is possible 1275when the <i>startoffset</i> argument of <b>pcre2_match()</b> is non-zero. The 1276PCRE2_DOLLAR_ENDONLY option is ignored if PCRE2_MULTILINE is set. 1277</P> 1278<P> 1279When the newline convention (see 1280<a href="#newlines">"Newline conventions"</a> 1281below) recognizes the two-character sequence CRLF as a newline, this is 1282preferred, even if the single characters CR and LF are also recognized as 1283newlines. For example, if the newline convention is "any", a multiline mode 1284circumflex matches before "xyz" in the string "abc\r\nxyz" rather than after 1285CR, even though CR on its own is a valid newline. (It also matches at the very 1286start of the string, of course.) 1287</P> 1288<P> 1289Note that the sequences \A, \Z, and \z can be used to match the start and 1290end of the subject in both modes, and if all branches of a pattern start with 1291\A it is always anchored, whether or not PCRE2_MULTILINE is set. 1292<a name="fullstopdot"></a></P> 1293<br><a name="SEC7" href="#TOC1">FULL STOP (PERIOD, DOT) AND \N</a><br> 1294<P> 1295Outside a character class, a dot in the pattern matches any one character in 1296the subject string except (by default) a character that signifies the end of a 1297line. 1298</P> 1299<P> 1300When a line ending is defined as a single character, dot never matches that 1301character; when the two-character sequence CRLF is used, dot does not match CR 1302if it is immediately followed by LF, but otherwise it matches all characters 1303(including isolated CRs and LFs). When any Unicode line endings are being 1304recognized, dot does not match CR or LF or any of the other line ending 1305characters. 1306</P> 1307<P> 1308The behaviour of dot with regard to newlines can be changed. If the 1309PCRE2_DOTALL option is set, a dot matches any one character, without exception. 1310If the two-character sequence CRLF is present in the subject string, it takes 1311two dots to match it. 1312</P> 1313<P> 1314The handling of dot is entirely independent of the handling of circumflex and 1315dollar, the only relationship being that they both involve newlines. Dot has no 1316special meaning in a character class. 1317</P> 1318<P> 1319The escape sequence \N when not followed by an opening brace behaves like a 1320dot, except that it is not affected by the PCRE2_DOTALL option. In other words, 1321it matches any character except one that signifies the end of a line. 1322</P> 1323<P> 1324When \N is followed by an opening brace it has a different meaning. See the 1325section entitled 1326<a href="digitsafterbackslash">"Non-printing characters"</a> 1327above for details. Perl also uses \N{name} to specify characters by Unicode 1328name; PCRE2 does not support this. 1329</P> 1330<br><a name="SEC8" href="#TOC1">MATCHING A SINGLE CODE UNIT</a><br> 1331<P> 1332Outside a character class, the escape sequence \C matches any one code unit, 1333whether or not a UTF mode is set. In the 8-bit library, one code unit is one 1334byte; in the 16-bit library it is a 16-bit unit; in the 32-bit library it is a 133532-bit unit. Unlike a dot, \C always matches line-ending characters. The 1336feature is provided in Perl in order to match individual bytes in UTF-8 mode, 1337but it is unclear how it can usefully be used. 1338</P> 1339<P> 1340Because \C breaks up characters into individual code units, matching one unit 1341with \C in UTF-8 or UTF-16 mode means that the rest of the string may start 1342with a malformed UTF character. This has undefined results, because PCRE2 1343assumes that it is matching character by character in a valid UTF string (by 1344default it checks the subject string's validity at the start of processing 1345unless the PCRE2_NO_UTF_CHECK option is used). 1346</P> 1347<P> 1348An application can lock out the use of \C by setting the 1349PCRE2_NEVER_BACKSLASH_C option when compiling a pattern. It is also possible to 1350build PCRE2 with the use of \C permanently disabled. 1351</P> 1352<P> 1353PCRE2 does not allow \C to appear in lookbehind assertions 1354<a href="#lookbehind">(described below)</a> 1355in UTF-8 or UTF-16 modes, because this would make it impossible to calculate 1356the length of the lookbehind. Neither the alternative matching function 1357<b>pcre2_dfa_match()</b> nor the JIT optimizer support \C in these UTF modes. 1358The former gives a match-time error; the latter fails to optimize and so the 1359match is always run using the interpreter. 1360</P> 1361<P> 1362In the 32-bit library, however, \C is always supported (when not explicitly 1363locked out) because it always matches a single code unit, whether or not UTF-32 1364is specified. 1365</P> 1366<P> 1367In general, the \C escape sequence is best avoided. However, one way of using 1368it that avoids the problem of malformed UTF-8 or UTF-16 characters is to use a 1369lookahead to check the length of the next character, as in this pattern, which 1370could be used with a UTF-8 string (ignore white space and line breaks): 1371<pre> 1372 (?| (?=[\x00-\x7f])(\C) | 1373 (?=[\x80-\x{7ff}])(\C)(\C) | 1374 (?=[\x{800}-\x{ffff}])(\C)(\C)(\C) | 1375 (?=[\x{10000}-\x{1fffff}])(\C)(\C)(\C)(\C)) 1376</pre> 1377In this example, a group that starts with (?| resets the capturing parentheses 1378numbers in each alternative (see 1379<a href="#dupsubpatternnumber">"Duplicate Subpattern Numbers"</a> 1380below). The assertions at the start of each branch check the next UTF-8 1381character for values whose encoding uses 1, 2, 3, or 4 bytes, respectively. The 1382character's individual bytes are then captured by the appropriate number of 1383\C groups. 1384<a name="characterclass"></a></P> 1385<br><a name="SEC9" href="#TOC1">SQUARE BRACKETS AND CHARACTER CLASSES</a><br> 1386<P> 1387An opening square bracket introduces a character class, terminated by a closing 1388square bracket. A closing square bracket on its own is not special by default. 1389If a closing square bracket is required as a member of the class, it should be 1390the first data character in the class (after an initial circumflex, if present) 1391or escaped with a backslash. This means that, by default, an empty class cannot 1392be defined. However, if the PCRE2_ALLOW_EMPTY_CLASS option is set, a closing 1393square bracket at the start does end the (empty) class. 1394</P> 1395<P> 1396A character class matches a single character in the subject. A matched 1397character must be in the set of characters defined by the class, unless the 1398first character in the class definition is a circumflex, in which case the 1399subject character must not be in the set defined by the class. If a circumflex 1400is actually required as a member of the class, ensure it is not the first 1401character, or escape it with a backslash. 1402</P> 1403<P> 1404For example, the character class [aeiou] matches any lower case vowel, while 1405[^aeiou] matches any character that is not a lower case vowel. Note that a 1406circumflex is just a convenient notation for specifying the characters that 1407are in the class by enumerating those that are not. A class that starts with a 1408circumflex is not an assertion; it still consumes a character from the subject 1409string, and therefore it fails if the current pointer is at the end of the 1410string. 1411</P> 1412<P> 1413Characters in a class may be specified by their code points using \o, \x, or 1414\N{U+hh..} in the usual way. When caseless matching is set, any letters in a 1415class represent both their upper case and lower case versions, so for example, 1416a caseless [aeiou] matches "A" as well as "a", and a caseless [^aeiou] does not 1417match "A", whereas a caseful version would. 1418</P> 1419<P> 1420Characters that might indicate line breaks are never treated in any special way 1421when matching character classes, whatever line-ending sequence is in use, and 1422whatever setting of the PCRE2_DOTALL and PCRE2_MULTILINE options is used. A 1423class such as [^a] always matches one of these characters. 1424</P> 1425<P> 1426The generic character type escape sequences \d, \D, \h, \H, \p, \P, \s, 1427\S, \v, \V, \w, and \W may appear in a character class, and add the 1428characters that they match to the class. For example, [\dABCDEF] matches any 1429hexadecimal digit. In UTF modes, the PCRE2_UCP option affects the meanings of 1430\d, \s, \w and their upper case partners, just as it does when they appear 1431outside a character class, as described in the section entitled 1432<a href="#genericchartypes">"Generic character types"</a> 1433above. The escape sequence \b has a different meaning inside a character 1434class; it matches the backspace character. The sequences \B, \R, and \X are 1435not special inside a character class. Like any other unrecognized escape 1436sequences, they cause an error. The same is true for \N when not followed by 1437an opening brace. 1438</P> 1439<P> 1440The minus (hyphen) character can be used to specify a range of characters in a 1441character class. For example, [d-m] matches any letter between d and m, 1442inclusive. If a minus character is required in a class, it must be escaped with 1443a backslash or appear in a position where it cannot be interpreted as 1444indicating a range, typically as the first or last character in the class, 1445or immediately after a range. For example, [b-d-z] matches letters in the range 1446b to d, a hyphen character, or z. 1447</P> 1448<P> 1449Perl treats a hyphen as a literal if it appears before or after a POSIX class 1450(see below) or before or after a character type escape such as as \d or \H. 1451However, unless the hyphen is the last character in the class, Perl outputs a 1452warning in its warning mode, as this is most likely a user error. As PCRE2 has 1453no facility for warning, an error is given in these cases. 1454</P> 1455<P> 1456It is not possible to have the literal character "]" as the end character of a 1457range. A pattern such as [W-]46] is interpreted as a class of two characters 1458("W" and "-") followed by a literal string "46]", so it would match "W46]" or 1459"-46]". However, if the "]" is escaped with a backslash it is interpreted as 1460the end of range, so [W-\]46] is interpreted as a class containing a range 1461followed by two other characters. The octal or hexadecimal representation of 1462"]" can also be used to end a range. 1463</P> 1464<P> 1465Ranges normally include all code points between the start and end characters, 1466inclusive. They can also be used for code points specified numerically, for 1467example [\000-\037]. Ranges can include any characters that are valid for the 1468current mode. In any UTF mode, the so-called "surrogate" characters (those 1469whose code points lie between 0xd800 and 0xdfff inclusive) may not be specified 1470explicitly by default (the PCRE2_EXTRA_ALLOW_SURROGATE_ESCAPES option disables 1471this check). However, ranges such as [\x{d7ff}-\x{e000}], which include the 1472surrogates, are always permitted. 1473</P> 1474<P> 1475There is a special case in EBCDIC environments for ranges whose end points are 1476both specified as literal letters in the same case. For compatibility with 1477Perl, EBCDIC code points within the range that are not letters are omitted. For 1478example, [h-k] matches only four characters, even though the codes for h and k 1479are 0x88 and 0x92, a range of 11 code points. However, if the range is 1480specified numerically, for example, [\x88-\x92] or [h-\x92], all code points 1481are included. 1482</P> 1483<P> 1484If a range that includes letters is used when caseless matching is set, it 1485matches the letters in either case. For example, [W-c] is equivalent to 1486[][\\^_`wxyzabc], matched caselessly, and in a non-UTF mode, if character 1487tables for a French locale are in use, [\xc8-\xcb] matches accented E 1488characters in both cases. 1489</P> 1490<P> 1491A circumflex can conveniently be used with the upper case character types to 1492specify a more restricted set of characters than the matching lower case type. 1493For example, the class [^\W_] matches any letter or digit, but not underscore, 1494whereas [\w] includes underscore. A positive character class should be read as 1495"something OR something OR ..." and a negative class as "NOT something AND NOT 1496something AND NOT ...". 1497</P> 1498<P> 1499The only metacharacters that are recognized in character classes are backslash, 1500hyphen (only where it can be interpreted as specifying a range), circumflex 1501(only at the start), opening square bracket (only when it can be interpreted as 1502introducing a POSIX class name, or for a special compatibility feature - see 1503the next two sections), and the terminating closing square bracket. However, 1504escaping other non-alphanumeric characters does no harm. 1505</P> 1506<br><a name="SEC10" href="#TOC1">POSIX CHARACTER CLASSES</a><br> 1507<P> 1508Perl supports the POSIX notation for character classes. This uses names 1509enclosed by [: and :] within the enclosing square brackets. PCRE2 also supports 1510this notation. For example, 1511<pre> 1512 [01[:alpha:]%] 1513</pre> 1514matches "0", "1", any alphabetic character, or "%". The supported class names 1515are: 1516<pre> 1517 alnum letters and digits 1518 alpha letters 1519 ascii character codes 0 - 127 1520 blank space or tab only 1521 cntrl control characters 1522 digit decimal digits (same as \d) 1523 graph printing characters, excluding space 1524 lower lower case letters 1525 print printing characters, including space 1526 punct printing characters, excluding letters and digits and space 1527 space white space (the same as \s from PCRE2 8.34) 1528 upper upper case letters 1529 word "word" characters (same as \w) 1530 xdigit hexadecimal digits 1531</pre> 1532The default "space" characters are HT (9), LF (10), VT (11), FF (12), CR (13), 1533and space (32). If locale-specific matching is taking place, the list of space 1534characters may be different; there may be fewer or more of them. "Space" and 1535\s match the same set of characters. 1536</P> 1537<P> 1538The name "word" is a Perl extension, and "blank" is a GNU extension from Perl 15395.8. Another Perl extension is negation, which is indicated by a ^ character 1540after the colon. For example, 1541<pre> 1542 [12[:^digit:]] 1543</pre> 1544matches "1", "2", or any non-digit. PCRE2 (and Perl) also recognize the POSIX 1545syntax [.ch.] and [=ch=] where "ch" is a "collating element", but these are not 1546supported, and an error is given if they are encountered. 1547</P> 1548<P> 1549By default, characters with values greater than 127 do not match any of the 1550POSIX character classes, although this may be different for characters in the 1551range 128-255 when locale-specific matching is happening. However, if the 1552PCRE2_UCP option is passed to <b>pcre2_compile()</b>, some of the classes are 1553changed so that Unicode character properties are used. This is achieved by 1554replacing certain POSIX classes with other sequences, as follows: 1555<pre> 1556 [:alnum:] becomes \p{Xan} 1557 [:alpha:] becomes \p{L} 1558 [:blank:] becomes \h 1559 [:cntrl:] becomes \p{Cc} 1560 [:digit:] becomes \p{Nd} 1561 [:lower:] becomes \p{Ll} 1562 [:space:] becomes \p{Xps} 1563 [:upper:] becomes \p{Lu} 1564 [:word:] becomes \p{Xwd} 1565</pre> 1566Negated versions, such as [:^alpha:] use \P instead of \p. Three other POSIX 1567classes are handled specially in UCP mode: 1568</P> 1569<P> 1570[:graph:] 1571This matches characters that have glyphs that mark the page when printed. In 1572Unicode property terms, it matches all characters with the L, M, N, P, S, or Cf 1573properties, except for: 1574<pre> 1575 U+061C Arabic Letter Mark 1576 U+180E Mongolian Vowel Separator 1577 U+2066 - U+2069 Various "isolate"s 1578 1579</PRE> 1580</P> 1581<P> 1582[:print:] 1583This matches the same characters as [:graph:] plus space characters that are 1584not controls, that is, characters with the Zs property. 1585</P> 1586<P> 1587[:punct:] 1588This matches all characters that have the Unicode P (punctuation) property, 1589plus those characters with code points less than 256 that have the S (Symbol) 1590property. 1591</P> 1592<P> 1593The other POSIX classes are unchanged, and match only characters with code 1594points less than 256. 1595</P> 1596<br><a name="SEC11" href="#TOC1">COMPATIBILITY FEATURE FOR WORD BOUNDARIES</a><br> 1597<P> 1598In the POSIX.2 compliant library that was included in 4.4BSD Unix, the ugly 1599syntax [[:<:]] and [[:>:]] is used for matching "start of word" and "end of 1600word". PCRE2 treats these items as follows: 1601<pre> 1602 [[:<:]] is converted to \b(?=\w) 1603 [[:>:]] is converted to \b(?<=\w) 1604</pre> 1605Only these exact character sequences are recognized. A sequence such as 1606[a[:<:]b] provokes error for an unrecognized POSIX class name. This support is 1607not compatible with Perl. It is provided to help migrations from other 1608environments, and is best not used in any new patterns. Note that \b matches 1609at the start and the end of a word (see 1610<a href="#smallassertions">"Simple assertions"</a> 1611above), and in a Perl-style pattern the preceding or following character 1612normally shows which is wanted, without the need for the assertions that are 1613used above in order to give exactly the POSIX behaviour. 1614</P> 1615<br><a name="SEC12" href="#TOC1">VERTICAL BAR</a><br> 1616<P> 1617Vertical bar characters are used to separate alternative patterns. For example, 1618the pattern 1619<pre> 1620 gilbert|sullivan 1621</pre> 1622matches either "gilbert" or "sullivan". Any number of alternatives may appear, 1623and an empty alternative is permitted (matching the empty string). The matching 1624process tries each alternative in turn, from left to right, and the first one 1625that succeeds is used. If the alternatives are within a subpattern 1626<a href="#subpattern">(defined below),</a> 1627"succeeds" means matching the rest of the main pattern as well as the 1628alternative in the subpattern. 1629</P> 1630<br><a name="SEC13" href="#TOC1">INTERNAL OPTION SETTING</a><br> 1631<P> 1632The settings of the PCRE2_CASELESS, PCRE2_MULTILINE, PCRE2_DOTALL, 1633PCRE2_EXTENDED, PCRE2_EXTENDED_MORE, and PCRE2_NO_AUTO_CAPTURE options can be 1634changed from within the pattern by a sequence of letters enclosed between "(?" 1635and ")". These options are Perl-compatible, and are described in detail in the 1636<a href="pcre2api.html"><b>pcre2api</b></a> 1637documentation. The option letters are: 1638<pre> 1639 i for PCRE2_CASELESS 1640 m for PCRE2_MULTILINE 1641 n for PCRE2_NO_AUTO_CAPTURE 1642 s for PCRE2_DOTALL 1643 x for PCRE2_EXTENDED 1644 xx for PCRE2_EXTENDED_MORE 1645</pre> 1646For example, (?im) sets caseless, multiline matching. It is also possible to 1647unset these options by preceding the relevant letters with a hyphen, for 1648example (?-im). The two "extended" options are not independent; unsetting either 1649one cancels the effects of both of them. 1650</P> 1651<P> 1652A combined setting and unsetting such as (?im-sx), which sets PCRE2_CASELESS 1653and PCRE2_MULTILINE while unsetting PCRE2_DOTALL and PCRE2_EXTENDED, is also 1654permitted. Only one hyphen may appear in the options string. If a letter 1655appears both before and after the hyphen, the option is unset. An empty options 1656setting "(?)" is allowed. Needless to say, it has no effect. 1657</P> 1658<P> 1659If the first character following (? is a circumflex, it causes all of the above 1660options to be unset. Thus, (?^) is equivalent to (?-imnsx). Letters may follow 1661the circumflex to cause some options to be re-instated, but a hyphen may not 1662appear. 1663</P> 1664<P> 1665The PCRE2-specific options PCRE2_DUPNAMES and PCRE2_UNGREEDY can be changed in 1666the same way as the Perl-compatible options by using the characters J and U 1667respectively. However, these are not unset by (?^). 1668</P> 1669<P> 1670When one of these option changes occurs at top level (that is, not inside 1671subpattern parentheses), the change applies to the remainder of the pattern 1672that follows. An option change within a subpattern (see below for a description 1673of subpatterns) affects only that part of the subpattern that follows it, so 1674<pre> 1675 (a(?i)b)c 1676</pre> 1677matches abc and aBc and no other strings (assuming PCRE2_CASELESS is not used). 1678By this means, options can be made to have different settings in different 1679parts of the pattern. Any changes made in one alternative do carry on 1680into subsequent branches within the same subpattern. For example, 1681<pre> 1682 (a(?i)b|c) 1683</pre> 1684matches "ab", "aB", "c", and "C", even though when matching "C" the first 1685branch is abandoned before the option setting. This is because the effects of 1686option settings happen at compile time. There would be some very weird 1687behaviour otherwise. 1688</P> 1689<P> 1690As a convenient shorthand, if any option settings are required at the start of 1691a non-capturing subpattern (see the next section), the option letters may 1692appear between the "?" and the ":". Thus the two patterns 1693<pre> 1694 (?i:saturday|sunday) 1695 (?:(?i)saturday|sunday) 1696</pre> 1697match exactly the same set of strings. 1698</P> 1699<P> 1700<b>Note:</b> There are other PCRE2-specific options that can be set by the 1701application when the compiling function is called. The pattern can contain 1702special leading sequences such as (*CRLF) to override what the application has 1703set or what has been defaulted. Details are given in the section entitled 1704<a href="#newlineseq">"Newline sequences"</a> 1705above. There are also the (*UTF) and (*UCP) leading sequences that can be used 1706to set UTF and Unicode property modes; they are equivalent to setting the 1707PCRE2_UTF and PCRE2_UCP options, respectively. However, the application can set 1708the PCRE2_NEVER_UTF and PCRE2_NEVER_UCP options, which lock out the use of the 1709(*UTF) and (*UCP) sequences. 1710<a name="subpattern"></a></P> 1711<br><a name="SEC14" href="#TOC1">SUBPATTERNS</a><br> 1712<P> 1713Subpatterns are delimited by parentheses (round brackets), which can be nested. 1714Turning part of a pattern into a subpattern does two things: 1715<br> 1716<br> 17171. It localizes a set of alternatives. For example, the pattern 1718<pre> 1719 cat(aract|erpillar|) 1720</pre> 1721matches "cataract", "caterpillar", or "cat". Without the parentheses, it would 1722match "cataract", "erpillar" or an empty string. 1723<br> 1724<br> 17252. It sets up the subpattern as a capturing subpattern. This means that, when 1726the whole pattern matches, the portion of the subject string that matched the 1727subpattern is passed back to the caller, separately from the portion that 1728matched the whole pattern. (This applies only to the traditional matching 1729function; the DFA matching function does not support capturing.) 1730</P> 1731<P> 1732Opening parentheses are counted from left to right (starting from 1) to obtain 1733numbers for the capturing subpatterns. For example, if the string "the red 1734king" is matched against the pattern 1735<pre> 1736 the ((red|white) (king|queen)) 1737</pre> 1738the captured substrings are "red king", "red", and "king", and are numbered 1, 17392, and 3, respectively. 1740</P> 1741<P> 1742The fact that plain parentheses fulfil two functions is not always helpful. 1743There are often times when a grouping subpattern is required without a 1744capturing requirement. If an opening parenthesis is followed by a question mark 1745and a colon, the subpattern does not do any capturing, and is not counted when 1746computing the number of any subsequent capturing subpatterns. For example, if 1747the string "the white queen" is matched against the pattern 1748<pre> 1749 the ((?:red|white) (king|queen)) 1750</pre> 1751the captured substrings are "white queen" and "queen", and are numbered 1 and 17522. The maximum number of capturing subpatterns is 65535. 1753</P> 1754<P> 1755As a convenient shorthand, if any option settings are required at the start of 1756a non-capturing subpattern, the option letters may appear between the "?" and 1757the ":". Thus the two patterns 1758<pre> 1759 (?i:saturday|sunday) 1760 (?:(?i)saturday|sunday) 1761</pre> 1762match exactly the same set of strings. Because alternative branches are tried 1763from left to right, and options are not reset until the end of the subpattern 1764is reached, an option setting in one branch does affect subsequent branches, so 1765the above patterns match "SUNDAY" as well as "Saturday". 1766<a name="dupsubpatternnumber"></a></P> 1767<br><a name="SEC15" href="#TOC1">DUPLICATE SUBPATTERN NUMBERS</a><br> 1768<P> 1769Perl 5.10 introduced a feature whereby each alternative in a subpattern uses 1770the same numbers for its capturing parentheses. Such a subpattern starts with 1771(?| and is itself a non-capturing subpattern. For example, consider this 1772pattern: 1773<pre> 1774 (?|(Sat)ur|(Sun))day 1775</pre> 1776Because the two alternatives are inside a (?| group, both sets of capturing 1777parentheses are numbered one. Thus, when the pattern matches, you can look 1778at captured substring number one, whichever alternative matched. This construct 1779is useful when you want to capture part, but not all, of one of a number of 1780alternatives. Inside a (?| group, parentheses are numbered as usual, but the 1781number is reset at the start of each branch. The numbers of any capturing 1782parentheses that follow the subpattern start after the highest number used in 1783any branch. The following example is taken from the Perl documentation. The 1784numbers underneath show in which buffer the captured content will be stored. 1785<pre> 1786 # before ---------------branch-reset----------- after 1787 / ( a ) (?| x ( y ) z | (p (q) r) | (t) u (v) ) ( z ) /x 1788 # 1 2 2 3 2 3 4 1789</pre> 1790A backreference to a numbered subpattern uses the most recent value that is 1791set for that number by any subpattern. The following pattern matches "abcabc" 1792or "defdef": 1793<pre> 1794 /(?|(abc)|(def))\1/ 1795</pre> 1796In contrast, a subroutine call to a numbered subpattern always refers to the 1797first one in the pattern with the given number. The following pattern matches 1798"abcabc" or "defabc": 1799<pre> 1800 /(?|(abc)|(def))(?1)/ 1801</pre> 1802A relative reference such as (?-1) is no different: it is just a convenient way 1803of computing an absolute group number. 1804</P> 1805<P> 1806If a 1807<a href="#conditions">condition test</a> 1808for a subpattern's having matched refers to a non-unique number, the test is 1809true if any of the subpatterns of that number have matched. 1810</P> 1811<P> 1812An alternative approach to using this "branch reset" feature is to use 1813duplicate named subpatterns, as described in the next section. 1814</P> 1815<br><a name="SEC16" href="#TOC1">NAMED SUBPATTERNS</a><br> 1816<P> 1817Identifying capturing parentheses by number is simple, but it can be very hard 1818to keep track of the numbers in complicated patterns. Furthermore, if an 1819expression is modified, the numbers may change. To help with this difficulty, 1820PCRE2 supports the naming of capturing subpatterns. This feature was not added 1821to Perl until release 5.10. Python had the feature earlier, and PCRE1 1822introduced it at release 4.0, using the Python syntax. PCRE2 supports both the 1823Perl and the Python syntax. 1824</P> 1825<P> 1826In PCRE2, a capturing subpattern can be named in one of three ways: 1827(?<name>...) or (?'name'...) as in Perl, or (?P<name>...) as in Python. Names 1828consist of up to 32 alphanumeric characters and underscores, but must start 1829with a non-digit. References to capturing parentheses from other parts of the 1830pattern, such as 1831<a href="#backreferences">backreferences,</a> 1832<a href="#recursion">recursion,</a> 1833and 1834<a href="#conditions">conditions,</a> 1835can all be made by name as well as by number. 1836</P> 1837<P> 1838Named capturing parentheses are allocated numbers as well as names, exactly as 1839if the names were not present. In both PCRE2 and Perl, capturing subpatterns 1840are primarily identified by numbers; any names are just aliases for these 1841numbers. The PCRE2 API provides function calls for extracting the complete 1842name-to-number translation table from a compiled pattern, as well as 1843convenience functions for extracting captured substrings by name. 1844</P> 1845<P> 1846<b>Warning:</b> When more than one subpattern has the same number, as described 1847in the previous section, a name given to one of them applies to all of them. 1848Perl allows identically numbered subpatterns to have different names. Consider 1849this pattern, where there are two capturing subpatterns, both numbered 1: 1850<pre> 1851 (?|(?<AA>aa)|(?<BB>bb)) 1852</pre> 1853Perl allows this, with both names AA and BB as aliases of group 1. Thus, after 1854a successful match, both names yield the same value (either "aa" or "bb"). 1855</P> 1856<P> 1857In an attempt to reduce confusion, PCRE2 does not allow the same group number 1858to be associated with more than one name. The example above provokes a 1859compile-time error. However, there is still scope for confusion. Consider this 1860pattern: 1861<pre> 1862 (?|(?<AA>aa)|(bb)) 1863</pre> 1864Although the second subpattern number 1 is not explicitly named, the name AA is 1865still an alias for subpattern 1. Whether the pattern matches "aa" or "bb", a 1866reference by name to group AA yields the matched string. 1867</P> 1868<P> 1869By default, a name must be unique within a pattern, except that duplicate names 1870are permitted for subpatterns with the same number, for example: 1871<pre> 1872 (?|(?<AA>aa)|(?<AA>bb)) 1873</pre> 1874The duplicate name constraint can be disabled by setting the PCRE2_DUPNAMES 1875option at compile time, or by the use of (?J) within the pattern. Duplicate 1876names can be useful for patterns where only one instance of the named 1877parentheses can match. Suppose you want to match the name of a weekday, either 1878as a 3-letter abbreviation or as the full name, and in both cases you want to 1879extract the abbreviation. This pattern (ignoring the line breaks) does the job: 1880<pre> 1881 (?<DN>Mon|Fri|Sun)(?:day)?| 1882 (?<DN>Tue)(?:sday)?| 1883 (?<DN>Wed)(?:nesday)?| 1884 (?<DN>Thu)(?:rsday)?| 1885 (?<DN>Sat)(?:urday)? 1886</pre> 1887There are five capturing substrings, but only one is ever set after a match. 1888The convenience functions for extracting the data by name returns the substring 1889for the first (and in this example, the only) subpattern of that name that 1890matched. This saves searching to find which numbered subpattern it was. (An 1891alternative way of solving this problem is to use a "branch reset" subpattern, 1892as described in the previous section.) 1893</P> 1894<P> 1895If you make a backreference to a non-unique named subpattern from elsewhere in 1896the pattern, the subpatterns to which the name refers are checked in the order 1897in which they appear in the overall pattern. The first one that is set is used 1898for the reference. For example, this pattern matches both "foofoo" and 1899"barbar" but not "foobar" or "barfoo": 1900<pre> 1901 (?:(?<n>foo)|(?<n>bar))\k<n> 1902 1903</PRE> 1904</P> 1905<P> 1906If you make a subroutine call to a non-unique named subpattern, the one that 1907corresponds to the first occurrence of the name is used. In the absence of 1908duplicate numbers this is the one with the lowest number. 1909</P> 1910<P> 1911If you use a named reference in a condition 1912test (see the 1913<a href="#conditions">section about conditions</a> 1914below), either to check whether a subpattern has matched, or to check for 1915recursion, all subpatterns with the same name are tested. If the condition is 1916true for any one of them, the overall condition is true. This is the same 1917behaviour as testing by number. For further details of the interfaces for 1918handling named subpatterns, see the 1919<a href="pcre2api.html"><b>pcre2api</b></a> 1920documentation. 1921</P> 1922<br><a name="SEC17" href="#TOC1">REPETITION</a><br> 1923<P> 1924Repetition is specified by quantifiers, which can follow any of the following 1925items: 1926<pre> 1927 a literal data character 1928 the dot metacharacter 1929 the \C escape sequence 1930 the \X escape sequence 1931 the \R escape sequence 1932 an escape such as \d or \pL that matches a single character 1933 a character class 1934 a backreference 1935 a parenthesized subpattern (including most assertions) 1936 a subroutine call to a subpattern (recursive or otherwise) 1937</pre> 1938The general repetition quantifier specifies a minimum and maximum number of 1939permitted matches, by giving the two numbers in curly brackets (braces), 1940separated by a comma. The numbers must be less than 65536, and the first must 1941be less than or equal to the second. For example: 1942<pre> 1943 z{2,4} 1944</pre> 1945matches "zz", "zzz", or "zzzz". A closing brace on its own is not a special 1946character. If the second number is omitted, but the comma is present, there is 1947no upper limit; if the second number and the comma are both omitted, the 1948quantifier specifies an exact number of required matches. Thus 1949<pre> 1950 [aeiou]{3,} 1951</pre> 1952matches at least 3 successive vowels, but may match many more, whereas 1953<pre> 1954 \d{8} 1955</pre> 1956matches exactly 8 digits. An opening curly bracket that appears in a position 1957where a quantifier is not allowed, or one that does not match the syntax of a 1958quantifier, is taken as a literal character. For example, {,6} is not a 1959quantifier, but a literal string of four characters. 1960</P> 1961<P> 1962In UTF modes, quantifiers apply to characters rather than to individual code 1963units. Thus, for example, \x{100}{2} matches two characters, each of 1964which is represented by a two-byte sequence in a UTF-8 string. Similarly, 1965\X{3} matches three Unicode extended grapheme clusters, each of which may be 1966several code units long (and they may be of different lengths). 1967</P> 1968<P> 1969The quantifier {0} is permitted, causing the expression to behave as if the 1970previous item and the quantifier were not present. This may be useful for 1971subpatterns that are referenced as 1972<a href="#subpatternsassubroutines">subroutines</a> 1973from elsewhere in the pattern (but see also the section entitled 1974<a href="#subdefine">"Defining subpatterns for use by reference only"</a> 1975below). Items other than subpatterns that have a {0} quantifier are omitted 1976from the compiled pattern. 1977</P> 1978<P> 1979For convenience, the three most common quantifiers have single-character 1980abbreviations: 1981<pre> 1982 * is equivalent to {0,} 1983 + is equivalent to {1,} 1984 ? is equivalent to {0,1} 1985</pre> 1986It is possible to construct infinite loops by following a subpattern that can 1987match no characters with a quantifier that has no upper limit, for example: 1988<pre> 1989 (a?)* 1990</pre> 1991Earlier versions of Perl and PCRE1 used to give an error at compile time for 1992such patterns. However, because there are cases where this can be useful, such 1993patterns are now accepted, but if any repetition of the subpattern does in fact 1994match no characters, the loop is forcibly broken. 1995</P> 1996<P> 1997By default, the quantifiers are "greedy", that is, they match as much as 1998possible (up to the maximum number of permitted times), without causing the 1999rest of the pattern to fail. The classic example of where this gives problems 2000is in trying to match comments in C programs. These appear between /* and */ 2001and within the comment, individual * and / characters may appear. An attempt to 2002match C comments by applying the pattern 2003<pre> 2004 /\*.*\*/ 2005</pre> 2006to the string 2007<pre> 2008 /* first comment */ not comment /* second comment */ 2009</pre> 2010fails, because it matches the entire string owing to the greediness of the .* 2011item. 2012</P> 2013<P> 2014If a quantifier is followed by a question mark, it ceases to be greedy, and 2015instead matches the minimum number of times possible, so the pattern 2016<pre> 2017 /\*.*?\*/ 2018</pre> 2019does the right thing with the C comments. The meaning of the various 2020quantifiers is not otherwise changed, just the preferred number of matches. 2021Do not confuse this use of question mark with its use as a quantifier in its 2022own right. Because it has two uses, it can sometimes appear doubled, as in 2023<pre> 2024 \d??\d 2025</pre> 2026which matches one digit by preference, but can match two if that is the only 2027way the rest of the pattern matches. 2028</P> 2029<P> 2030If the PCRE2_UNGREEDY option is set (an option that is not available in Perl), 2031the quantifiers are not greedy by default, but individual ones can be made 2032greedy by following them with a question mark. In other words, it inverts the 2033default behaviour. 2034</P> 2035<P> 2036When a parenthesized subpattern is quantified with a minimum repeat count that 2037is greater than 1 or with a limited maximum, more memory is required for the 2038compiled pattern, in proportion to the size of the minimum or maximum. 2039</P> 2040<P> 2041If a pattern starts with .* or .{0,} and the PCRE2_DOTALL option (equivalent 2042to Perl's /s) is set, thus allowing the dot to match newlines, the pattern is 2043implicitly anchored, because whatever follows will be tried against every 2044character position in the subject string, so there is no point in retrying the 2045overall match at any position after the first. PCRE2 normally treats such a 2046pattern as though it were preceded by \A. 2047</P> 2048<P> 2049In cases where it is known that the subject string contains no newlines, it is 2050worth setting PCRE2_DOTALL in order to obtain this optimization, or 2051alternatively, using ^ to indicate anchoring explicitly. 2052</P> 2053<P> 2054However, there are some cases where the optimization cannot be used. When .* 2055is inside capturing parentheses that are the subject of a backreference 2056elsewhere in the pattern, a match at the start may fail where a later one 2057succeeds. Consider, for example: 2058<pre> 2059 (.*)abc\1 2060</pre> 2061If the subject is "xyz123abc123" the match point is the fourth character. For 2062this reason, such a pattern is not implicitly anchored. 2063</P> 2064<P> 2065Another case where implicit anchoring is not applied is when the leading .* is 2066inside an atomic group. Once again, a match at the start may fail where a later 2067one succeeds. Consider this pattern: 2068<pre> 2069 (?>.*?a)b 2070</pre> 2071It matches "ab" in the subject "aab". The use of the backtracking control verbs 2072(*PRUNE) and (*SKIP) also disable this optimization, and there is an option, 2073PCRE2_NO_DOTSTAR_ANCHOR, to do so explicitly. 2074</P> 2075<P> 2076When a capturing subpattern is repeated, the value captured is the substring 2077that matched the final iteration. For example, after 2078<pre> 2079 (tweedle[dume]{3}\s*)+ 2080</pre> 2081has matched "tweedledum tweedledee" the value of the captured substring is 2082"tweedledee". However, if there are nested capturing subpatterns, the 2083corresponding captured values may have been set in previous iterations. For 2084example, after 2085<pre> 2086 (a|(b))+ 2087</pre> 2088matches "aba" the value of the second captured substring is "b". 2089<a name="atomicgroup"></a></P> 2090<br><a name="SEC18" href="#TOC1">ATOMIC GROUPING AND POSSESSIVE QUANTIFIERS</a><br> 2091<P> 2092With both maximizing ("greedy") and minimizing ("ungreedy" or "lazy") 2093repetition, failure of what follows normally causes the repeated item to be 2094re-evaluated to see if a different number of repeats allows the rest of the 2095pattern to match. Sometimes it is useful to prevent this, either to change the 2096nature of the match, or to cause it fail earlier than it otherwise might, when 2097the author of the pattern knows there is no point in carrying on. 2098</P> 2099<P> 2100Consider, for example, the pattern \d+foo when applied to the subject line 2101<pre> 2102 123456bar 2103</pre> 2104After matching all 6 digits and then failing to match "foo", the normal 2105action of the matcher is to try again with only 5 digits matching the \d+ 2106item, and then with 4, and so on, before ultimately failing. "Atomic grouping" 2107(a term taken from Jeffrey Friedl's book) provides the means for specifying 2108that once a subpattern has matched, it is not to be re-evaluated in this way. 2109</P> 2110<P> 2111If we use atomic grouping for the previous example, the matcher gives up 2112immediately on failing to match "foo" the first time. The notation is a kind of 2113special parenthesis, starting with (?> as in this example: 2114<pre> 2115 (?>\d+)foo 2116</pre> 2117This kind of parenthesis "locks up" the part of the pattern it contains once 2118it has matched, and a failure further into the pattern is prevented from 2119backtracking into it. Backtracking past it to previous items, however, works as 2120normal. 2121</P> 2122<P> 2123An alternative description is that a subpattern of this type matches exactly 2124the string of characters that an identical standalone pattern would match, if 2125anchored at the current point in the subject string. 2126</P> 2127<P> 2128Atomic grouping subpatterns are not capturing subpatterns. Simple cases such as 2129the above example can be thought of as a maximizing repeat that must swallow 2130everything it can. So, while both \d+ and \d+? are prepared to adjust the 2131number of digits they match in order to make the rest of the pattern match, 2132(?>\d+) can only match an entire sequence of digits. 2133</P> 2134<P> 2135Atomic groups in general can of course contain arbitrarily complicated 2136subpatterns, and can be nested. However, when the subpattern for an atomic 2137group is just a single repeated item, as in the example above, a simpler 2138notation, called a "possessive quantifier" can be used. This consists of an 2139additional + character following a quantifier. Using this notation, the 2140previous example can be rewritten as 2141<pre> 2142 \d++foo 2143</pre> 2144Note that a possessive quantifier can be used with an entire group, for 2145example: 2146<pre> 2147 (abc|xyz){2,3}+ 2148</pre> 2149Possessive quantifiers are always greedy; the setting of the PCRE2_UNGREEDY 2150option is ignored. They are a convenient notation for the simpler forms of 2151atomic group. However, there is no difference in the meaning of a possessive 2152quantifier and the equivalent atomic group, though there may be a performance 2153difference; possessive quantifiers should be slightly faster. 2154</P> 2155<P> 2156The possessive quantifier syntax is an extension to the Perl 5.8 syntax. 2157Jeffrey Friedl originated the idea (and the name) in the first edition of his 2158book. Mike McCloskey liked it, so implemented it when he built Sun's Java 2159package, and PCRE1 copied it from there. It ultimately found its way into Perl 2160at release 5.10. 2161</P> 2162<P> 2163PCRE2 has an optimization that automatically "possessifies" certain simple 2164pattern constructs. For example, the sequence A+B is treated as A++B because 2165there is no point in backtracking into a sequence of A's when B must follow. 2166This feature can be disabled by the PCRE2_NO_AUTOPOSSESS option, or starting 2167the pattern with (*NO_AUTO_POSSESS). 2168</P> 2169<P> 2170When a pattern contains an unlimited repeat inside a subpattern that can itself 2171be repeated an unlimited number of times, the use of an atomic group is the 2172only way to avoid some failing matches taking a very long time indeed. The 2173pattern 2174<pre> 2175 (\D+|<\d+>)*[!?] 2176</pre> 2177matches an unlimited number of substrings that either consist of non-digits, or 2178digits enclosed in <>, followed by either ! or ?. When it matches, it runs 2179quickly. However, if it is applied to 2180<pre> 2181 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 2182</pre> 2183it takes a long time before reporting failure. This is because the string can 2184be divided between the internal \D+ repeat and the external * repeat in a 2185large number of ways, and all have to be tried. (The example uses [!?] rather 2186than a single character at the end, because both PCRE2 and Perl have an 2187optimization that allows for fast failure when a single character is used. They 2188remember the last single character that is required for a match, and fail early 2189if it is not present in the string.) If the pattern is changed so that it uses 2190an atomic group, like this: 2191<pre> 2192 ((?>\D+)|<\d+>)*[!?] 2193</pre> 2194sequences of non-digits cannot be broken, and failure happens quickly. 2195<a name="backreferences"></a></P> 2196<br><a name="SEC19" href="#TOC1">BACKREFERENCES</a><br> 2197<P> 2198Outside a character class, a backslash followed by a digit greater than 0 (and 2199possibly further digits) is a backreference to a capturing subpattern earlier 2200(that is, to its left) in the pattern, provided there have been that many 2201previous capturing left parentheses. 2202</P> 2203<P> 2204However, if the decimal number following the backslash is less than 8, it is 2205always taken as a backreference, and causes an error only if there are not 2206that many capturing left parentheses in the entire pattern. In other words, the 2207parentheses that are referenced need not be to the left of the reference for 2208numbers less than 8. A "forward backreference" of this type can make sense 2209when a repetition is involved and the subpattern to the right has participated 2210in an earlier iteration. 2211</P> 2212<P> 2213It is not possible to have a numerical "forward backreference" to a subpattern 2214whose number is 8 or more using this syntax because a sequence such as \50 is 2215interpreted as a character defined in octal. See the subsection entitled 2216"Non-printing characters" 2217<a href="#digitsafterbackslash">above</a> 2218for further details of the handling of digits following a backslash. There is 2219no such problem when named parentheses are used. A backreference to any 2220subpattern is possible using named parentheses (see below). 2221</P> 2222<P> 2223Another way of avoiding the ambiguity inherent in the use of digits following a 2224backslash is to use the \g escape sequence. This escape must be followed by a 2225signed or unsigned number, optionally enclosed in braces. These examples are 2226all identical: 2227<pre> 2228 (ring), \1 2229 (ring), \g1 2230 (ring), \g{1} 2231</pre> 2232An unsigned number specifies an absolute reference without the ambiguity that 2233is present in the older syntax. It is also useful when literal digits follow 2234the reference. A signed number is a relative reference. Consider this example: 2235<pre> 2236 (abc(def)ghi)\g{-1} 2237</pre> 2238The sequence \g{-1} is a reference to the most recently started capturing 2239subpattern before \g, that is, is it equivalent to \2 in this example. 2240Similarly, \g{-2} would be equivalent to \1. The use of relative references 2241can be helpful in long patterns, and also in patterns that are created by 2242joining together fragments that contain references within themselves. 2243</P> 2244<P> 2245The sequence \g{+1} is a reference to the next capturing subpattern. This kind 2246of forward reference can be useful it patterns that repeat. Perl does not 2247support the use of + in this way. 2248</P> 2249<P> 2250A backreference matches whatever actually matched the capturing subpattern in 2251the current subject string, rather than anything matching the subpattern 2252itself (see 2253<a href="#subpatternsassubroutines">"Subpatterns as subroutines"</a> 2254below for a way of doing that). So the pattern 2255<pre> 2256 (sens|respons)e and \1ibility 2257</pre> 2258matches "sense and sensibility" and "response and responsibility", but not 2259"sense and responsibility". If caseful matching is in force at the time of the 2260backreference, the case of letters is relevant. For example, 2261<pre> 2262 ((?i)rah)\s+\1 2263</pre> 2264matches "rah rah" and "RAH RAH", but not "RAH rah", even though the original 2265capturing subpattern is matched caselessly. 2266</P> 2267<P> 2268There are several different ways of writing backreferences to named 2269subpatterns. The .NET syntax \k{name} and the Perl syntax \k<name> or 2270\k'name' are supported, as is the Python syntax (?P=name). Perl 5.10's unified 2271backreference syntax, in which \g can be used for both numeric and named 2272references, is also supported. We could rewrite the above example in any of 2273the following ways: 2274<pre> 2275 (?<p1>(?i)rah)\s+\k<p1> 2276 (?'p1'(?i)rah)\s+\k{p1} 2277 (?P<p1>(?i)rah)\s+(?P=p1) 2278 (?<p1>(?i)rah)\s+\g{p1} 2279</pre> 2280A subpattern that is referenced by name may appear in the pattern before or 2281after the reference. 2282</P> 2283<P> 2284There may be more than one backreference to the same subpattern. If a 2285subpattern has not actually been used in a particular match, any backreferences 2286to it always fail by default. For example, the pattern 2287<pre> 2288 (a|(bc))\2 2289</pre> 2290always fails if it starts to match "a" rather than "bc". However, if the 2291PCRE2_MATCH_UNSET_BACKREF option is set at compile time, a backreference to an 2292unset value matches an empty string. 2293</P> 2294<P> 2295Because there may be many capturing parentheses in a pattern, all digits 2296following a backslash are taken as part of a potential backreference number. 2297If the pattern continues with a digit character, some delimiter must be used to 2298terminate the backreference. If the PCRE2_EXTENDED or PCRE2_EXTENDED_MORE 2299option is set, this can be white space. Otherwise, the \g{ syntax or an empty 2300comment (see 2301<a href="#comments">"Comments"</a> 2302below) can be used. 2303</P> 2304<br><b> 2305Recursive backreferences 2306</b><br> 2307<P> 2308A backreference that occurs inside the parentheses to which it refers fails 2309when the subpattern is first used, so, for example, (a\1) never matches. 2310However, such references can be useful inside repeated subpatterns. For 2311example, the pattern 2312<pre> 2313 (a|b\1)+ 2314</pre> 2315matches any number of "a"s and also "aba", "ababbaa" etc. At each iteration of 2316the subpattern, the backreference matches the character string corresponding 2317to the previous iteration. In order for this to work, the pattern must be such 2318that the first iteration does not need to match the backreference. This can be 2319done using alternation, as in the example above, or by a quantifier with a 2320minimum of zero. 2321</P> 2322<P> 2323Backreferences of this type cause the group that they reference to be treated 2324as an 2325<a href="#atomicgroup">atomic group.</a> 2326Once the whole group has been matched, a subsequent matching failure cannot 2327cause backtracking into the middle of the group. 2328<a name="bigassertions"></a></P> 2329<br><a name="SEC20" href="#TOC1">ASSERTIONS</a><br> 2330<P> 2331An assertion is a test on the characters following or preceding the current 2332matching point that does not consume any characters. The simple assertions 2333coded as \b, \B, \A, \G, \Z, \z, ^ and $ are described 2334<a href="#smallassertions">above.</a> 2335</P> 2336<P> 2337More complicated assertions are coded as subpatterns. There are two kinds: 2338those that look ahead of the current position in the subject string, and those 2339that look behind it, and in each case an assertion may be positive (must 2340succeed for matching to continue) or negative (must not succeed for matching to 2341continue). An assertion subpattern is matched in the normal way, except that, 2342when matching continues after a successful assertion, the matching position in 2343the subject string is as it was before the assertion was processed. 2344</P> 2345<P> 2346Assertion subpatterns are not capturing subpatterns. If an assertion contains 2347capturing subpatterns within it, these are counted for the purposes of 2348numbering the capturing subpatterns in the whole pattern. Within each branch of 2349an assertion, locally captured substrings may be referenced in the usual way. 2350For example, a sequence such as (.)\g{-1} can be used to check that two 2351adjacent characters are the same. 2352</P> 2353<P> 2354When a branch within an assertion fails to match, any substrings that were 2355captured are discarded (as happens with any pattern branch that fails to 2356match). A negative assertion succeeds only when all its branches fail to match; 2357this means that no captured substrings are ever retained after a successful 2358negative assertion. When an assertion contains a matching branch, what happens 2359depends on the type of assertion. 2360</P> 2361<P> 2362For a positive assertion, internally captured substrings in the successful 2363branch are retained, and matching continues with the next pattern item after 2364the assertion. For a negative assertion, a matching branch means that the 2365assertion has failed. If the assertion is being used as a condition in a 2366<a href="#conditions">conditional subpattern</a> 2367(see below), captured substrings are retained, because matching continues with 2368the "no" branch of the condition. For other failing negative assertions, 2369control passes to the previous backtracking point, thus discarding any captured 2370strings within the assertion. 2371</P> 2372<P> 2373For compatibility with Perl, most assertion subpatterns may be repeated; though 2374it makes no sense to assert the same thing several times, the side effect of 2375capturing parentheses may occasionally be useful. However, an assertion that 2376forms the condition for a conditional subpattern may not be quantified. In 2377practice, for other assertions, there only three cases: 2378<br> 2379<br> 2380(1) If the quantifier is {0}, the assertion is never obeyed during matching. 2381However, it may contain internal capturing parenthesized groups that are called 2382from elsewhere via the 2383<a href="#subpatternsassubroutines">subroutine mechanism.</a> 2384<br> 2385<br> 2386(2) If quantifier is {0,n} where n is greater than zero, it is treated as if it 2387were {0,1}. At run time, the rest of the pattern match is tried with and 2388without the assertion, the order depending on the greediness of the quantifier. 2389<br> 2390<br> 2391(3) If the minimum repetition is greater than zero, the quantifier is ignored. 2392The assertion is obeyed just once when encountered during matching. 2393</P> 2394<br><b> 2395Lookahead assertions 2396</b><br> 2397<P> 2398Lookahead assertions start with (?= for positive assertions and (?! for 2399negative assertions. For example, 2400<pre> 2401 \w+(?=;) 2402</pre> 2403matches a word followed by a semicolon, but does not include the semicolon in 2404the match, and 2405<pre> 2406 foo(?!bar) 2407</pre> 2408matches any occurrence of "foo" that is not followed by "bar". Note that the 2409apparently similar pattern 2410<pre> 2411 (?!foo)bar 2412</pre> 2413does not find an occurrence of "bar" that is preceded by something other than 2414"foo"; it finds any occurrence of "bar" whatsoever, because the assertion 2415(?!foo) is always true when the next three characters are "bar". A 2416lookbehind assertion is needed to achieve the other effect. 2417</P> 2418<P> 2419If you want to force a matching failure at some point in a pattern, the most 2420convenient way to do it is with (?!) because an empty string always matches, so 2421an assertion that requires there not to be an empty string must always fail. 2422The backtracking control verb (*FAIL) or (*F) is a synonym for (?!). 2423<a name="lookbehind"></a></P> 2424<br><b> 2425Lookbehind assertions 2426</b><br> 2427<P> 2428Lookbehind assertions start with (?<= for positive assertions and (?<! for 2429negative assertions. For example, 2430<pre> 2431 (?<!foo)bar 2432</pre> 2433does find an occurrence of "bar" that is not preceded by "foo". The contents of 2434a lookbehind assertion are restricted such that all the strings it matches must 2435have a fixed length. However, if there are several top-level alternatives, they 2436do not all have to have the same fixed length. Thus 2437<pre> 2438 (?<=bullock|donkey) 2439</pre> 2440is permitted, but 2441<pre> 2442 (?<!dogs?|cats?) 2443</pre> 2444causes an error at compile time. Branches that match different length strings 2445are permitted only at the top level of a lookbehind assertion. This is an 2446extension compared with Perl, which requires all branches to match the same 2447length of string. An assertion such as 2448<pre> 2449 (?<=ab(c|de)) 2450</pre> 2451is not permitted, because its single top-level branch can match two different 2452lengths, but it is acceptable to PCRE2 if rewritten to use two top-level 2453branches: 2454<pre> 2455 (?<=abc|abde) 2456</pre> 2457In some cases, the escape sequence \K 2458<a href="#resetmatchstart">(see above)</a> 2459can be used instead of a lookbehind assertion to get round the fixed-length 2460restriction. 2461</P> 2462<P> 2463The implementation of lookbehind assertions is, for each alternative, to 2464temporarily move the current position back by the fixed length and then try to 2465match. If there are insufficient characters before the current position, the 2466assertion fails. 2467</P> 2468<P> 2469In UTF-8 and UTF-16 modes, PCRE2 does not allow the \C escape (which matches a 2470single code unit even in a UTF mode) to appear in lookbehind assertions, 2471because it makes it impossible to calculate the length of the lookbehind. The 2472\X and \R escapes, which can match different numbers of code units, are never 2473permitted in lookbehinds. 2474</P> 2475<P> 2476<a href="#subpatternsassubroutines">"Subroutine"</a> 2477calls (see below) such as (?2) or (?&X) are permitted in lookbehinds, as long 2478as the subpattern matches a fixed-length string. However, 2479<a href="#recursion">recursion,</a> 2480that is, a "subroutine" call into a group that is already active, 2481is not supported. 2482</P> 2483<P> 2484Perl does not support backreferences in lookbehinds. PCRE2 does support them, 2485but only if certain conditions are met. The PCRE2_MATCH_UNSET_BACKREF option 2486must not be set, there must be no use of (?| in the pattern (it creates 2487duplicate subpattern numbers), and if the backreference is by name, the name 2488must be unique. Of course, the referenced subpattern must itself be of fixed 2489length. The following pattern matches words containing at least two characters 2490that begin and end with the same character: 2491<pre> 2492 \b(\w)\w++(?<=\1) 2493</PRE> 2494</P> 2495<P> 2496Possessive quantifiers can be used in conjunction with lookbehind assertions to 2497specify efficient matching of fixed-length strings at the end of subject 2498strings. Consider a simple pattern such as 2499<pre> 2500 abcd$ 2501</pre> 2502when applied to a long string that does not match. Because matching proceeds 2503from left to right, PCRE2 will look for each "a" in the subject and then see if 2504what follows matches the rest of the pattern. If the pattern is specified as 2505<pre> 2506 ^.*abcd$ 2507</pre> 2508the initial .* matches the entire string at first, but when this fails (because 2509there is no following "a"), it backtracks to match all but the last character, 2510then all but the last two characters, and so on. Once again the search for "a" 2511covers the entire string, from right to left, so we are no better off. However, 2512if the pattern is written as 2513<pre> 2514 ^.*+(?<=abcd) 2515</pre> 2516there can be no backtracking for the .*+ item because of the possessive 2517quantifier; it can match only the entire string. The subsequent lookbehind 2518assertion does a single test on the last four characters. If it fails, the 2519match fails immediately. For long strings, this approach makes a significant 2520difference to the processing time. 2521</P> 2522<br><b> 2523Using multiple assertions 2524</b><br> 2525<P> 2526Several assertions (of any sort) may occur in succession. For example, 2527<pre> 2528 (?<=\d{3})(?<!999)foo 2529</pre> 2530matches "foo" preceded by three digits that are not "999". Notice that each of 2531the assertions is applied independently at the same point in the subject 2532string. First there is a check that the previous three characters are all 2533digits, and then there is a check that the same three characters are not "999". 2534This pattern does <i>not</i> match "foo" preceded by six characters, the first 2535of which are digits and the last three of which are not "999". For example, it 2536doesn't match "123abcfoo". A pattern to do that is 2537<pre> 2538 (?<=\d{3}...)(?<!999)foo 2539</pre> 2540This time the first assertion looks at the preceding six characters, checking 2541that the first three are digits, and then the second assertion checks that the 2542preceding three characters are not "999". 2543</P> 2544<P> 2545Assertions can be nested in any combination. For example, 2546<pre> 2547 (?<=(?<!foo)bar)baz 2548</pre> 2549matches an occurrence of "baz" that is preceded by "bar" which in turn is not 2550preceded by "foo", while 2551<pre> 2552 (?<=\d{3}(?!999)...)foo 2553</pre> 2554is another pattern that matches "foo" preceded by three digits and any three 2555characters that are not "999". 2556<a name="conditions"></a></P> 2557<br><a name="SEC21" href="#TOC1">CONDITIONAL SUBPATTERNS</a><br> 2558<P> 2559It is possible to cause the matching process to obey a subpattern 2560conditionally or to choose between two alternative subpatterns, depending on 2561the result of an assertion, or whether a specific capturing subpattern has 2562already been matched. The two possible forms of conditional subpattern are: 2563<pre> 2564 (?(condition)yes-pattern) 2565 (?(condition)yes-pattern|no-pattern) 2566</pre> 2567If the condition is satisfied, the yes-pattern is used; otherwise the 2568no-pattern (if present) is used. An absent no-pattern is equivalent to an empty 2569string (it always matches). If there are more than two alternatives in the 2570subpattern, a compile-time error occurs. Each of the two alternatives may 2571itself contain nested subpatterns of any form, including conditional 2572subpatterns; the restriction to two alternatives applies only at the level of 2573the condition. This pattern fragment is an example where the alternatives are 2574complex: 2575<pre> 2576 (?(1) (A|B|C) | (D | (?(2)E|F) | E) ) 2577 2578</PRE> 2579</P> 2580<P> 2581There are five kinds of condition: references to subpatterns, references to 2582recursion, two pseudo-conditions called DEFINE and VERSION, and assertions. 2583</P> 2584<br><b> 2585Checking for a used subpattern by number 2586</b><br> 2587<P> 2588If the text between the parentheses consists of a sequence of digits, the 2589condition is true if a capturing subpattern of that number has previously 2590matched. If there is more than one capturing subpattern with the same number 2591(see the earlier 2592<a href="#recursion">section about duplicate subpattern numbers),</a> 2593the condition is true if any of them have matched. An alternative notation is 2594to precede the digits with a plus or minus sign. In this case, the subpattern 2595number is relative rather than absolute. The most recently opened parentheses 2596can be referenced by (?(-1), the next most recent by (?(-2), and so on. Inside 2597loops it can also make sense to refer to subsequent groups. The next 2598parentheses to be opened can be referenced as (?(+1), and so on. (The value 2599zero in any of these forms is not used; it provokes a compile-time error.) 2600</P> 2601<P> 2602Consider the following pattern, which contains non-significant white space to 2603make it more readable (assume the PCRE2_EXTENDED option) and to divide it into 2604three parts for ease of discussion: 2605<pre> 2606 ( \( )? [^()]+ (?(1) \) ) 2607</pre> 2608The first part matches an optional opening parenthesis, and if that 2609character is present, sets it as the first captured substring. The second part 2610matches one or more characters that are not parentheses. The third part is a 2611conditional subpattern that tests whether or not the first set of parentheses 2612matched. If they did, that is, if subject started with an opening parenthesis, 2613the condition is true, and so the yes-pattern is executed and a closing 2614parenthesis is required. Otherwise, since no-pattern is not present, the 2615subpattern matches nothing. In other words, this pattern matches a sequence of 2616non-parentheses, optionally enclosed in parentheses. 2617</P> 2618<P> 2619If you were embedding this pattern in a larger one, you could use a relative 2620reference: 2621<pre> 2622 ...other stuff... ( \( )? [^()]+ (?(-1) \) ) ... 2623</pre> 2624This makes the fragment independent of the parentheses in the larger pattern. 2625</P> 2626<br><b> 2627Checking for a used subpattern by name 2628</b><br> 2629<P> 2630Perl uses the syntax (?(<name>)...) or (?('name')...) to test for a used 2631subpattern by name. For compatibility with earlier versions of PCRE1, which had 2632this facility before Perl, the syntax (?(name)...) is also recognized. Note, 2633however, that undelimited names consisting of the letter R followed by digits 2634are ambiguous (see the following section). 2635</P> 2636<P> 2637Rewriting the above example to use a named subpattern gives this: 2638<pre> 2639 (?<OPEN> \( )? [^()]+ (?(<OPEN>) \) ) 2640</pre> 2641If the name used in a condition of this kind is a duplicate, the test is 2642applied to all subpatterns of the same name, and is true if any one of them has 2643matched. 2644</P> 2645<br><b> 2646Checking for pattern recursion 2647</b><br> 2648<P> 2649"Recursion" in this sense refers to any subroutine-like call from one part of 2650the pattern to another, whether or not it is actually recursive. See the 2651sections entitled 2652<a href="#recursion">"Recursive patterns"</a> 2653and 2654<a href="#subpatternsassubroutines">"Subpatterns as subroutines"</a> 2655below for details of recursion and subpattern calls. 2656</P> 2657<P> 2658If a condition is the string (R), and there is no subpattern with the name R, 2659the condition is true if matching is currently in a recursion or subroutine 2660call to the whole pattern or any subpattern. If digits follow the letter R, and 2661there is no subpattern with that name, the condition is true if the most recent 2662call is into a subpattern with the given number, which must exist somewhere in 2663the overall pattern. This is a contrived example that is equivalent to a+b: 2664<pre> 2665 ((?(R1)a+|(?1)b)) 2666</pre> 2667However, in both cases, if there is a subpattern with a matching name, the 2668condition tests for its being set, as described in the section above, instead 2669of testing for recursion. For example, creating a group with the name R1 by 2670adding (?<R1>) to the above pattern completely changes its meaning. 2671</P> 2672<P> 2673If a name preceded by ampersand follows the letter R, for example: 2674<pre> 2675 (?(R&name)...) 2676</pre> 2677the condition is true if the most recent recursion is into a subpattern of that 2678name (which must exist within the pattern). 2679</P> 2680<P> 2681This condition does not check the entire recursion stack. It tests only the 2682current level. If the name used in a condition of this kind is a duplicate, the 2683test is applied to all subpatterns of the same name, and is true if any one of 2684them is the most recent recursion. 2685</P> 2686<P> 2687At "top level", all these recursion test conditions are false. 2688<a name="subdefine"></a></P> 2689<br><b> 2690Defining subpatterns for use by reference only 2691</b><br> 2692<P> 2693If the condition is the string (DEFINE), the condition is always false, even if 2694there is a group with the name DEFINE. In this case, there may be only one 2695alternative in the subpattern. It is always skipped if control reaches this 2696point in the pattern; the idea of DEFINE is that it can be used to define 2697subroutines that can be referenced from elsewhere. (The use of 2698<a href="#subpatternsassubroutines">subroutines</a> 2699is described below.) For example, a pattern to match an IPv4 address such as 2700"192.168.23.245" could be written like this (ignore white space and line 2701breaks): 2702<pre> 2703 (?(DEFINE) (?<byte> 2[0-4]\d | 25[0-5] | 1\d\d | [1-9]?\d) ) 2704 \b (?&byte) (\.(?&byte)){3} \b 2705</pre> 2706The first part of the pattern is a DEFINE group inside which a another group 2707named "byte" is defined. This matches an individual component of an IPv4 2708address (a number less than 256). When matching takes place, this part of the 2709pattern is skipped because DEFINE acts like a false condition. The rest of the 2710pattern uses references to the named group to match the four dot-separated 2711components of an IPv4 address, insisting on a word boundary at each end. 2712</P> 2713<br><b> 2714Checking the PCRE2 version 2715</b><br> 2716<P> 2717Programs that link with a PCRE2 library can check the version by calling 2718<b>pcre2_config()</b> with appropriate arguments. Users of applications that do 2719not have access to the underlying code cannot do this. A special "condition" 2720called VERSION exists to allow such users to discover which version of PCRE2 2721they are dealing with by using this condition to match a string such as 2722"yesno". VERSION must be followed either by "=" or ">=" and a version number. 2723For example: 2724<pre> 2725 (?(VERSION>=10.4)yes|no) 2726</pre> 2727This pattern matches "yes" if the PCRE2 version is greater or equal to 10.4, or 2728"no" otherwise. The fractional part of the version number may not contain more 2729than two digits. 2730</P> 2731<br><b> 2732Assertion conditions 2733</b><br> 2734<P> 2735If the condition is not in any of the above formats, it must be an assertion. 2736This may be a positive or negative lookahead or lookbehind assertion. Consider 2737this pattern, again containing non-significant white space, and with the two 2738alternatives on the second line: 2739<pre> 2740 (?(?=[^a-z]*[a-z]) 2741 \d{2}-[a-z]{3}-\d{2} | \d{2}-\d{2}-\d{2} ) 2742</pre> 2743The condition is a positive lookahead assertion that matches an optional 2744sequence of non-letters followed by a letter. In other words, it tests for the 2745presence of at least one letter in the subject. If a letter is found, the 2746subject is matched against the first alternative; otherwise it is matched 2747against the second. This pattern matches strings in one of the two forms 2748dd-aaa-dd or dd-dd-dd, where aaa are letters and dd are digits. 2749</P> 2750<P> 2751When an assertion that is a condition contains capturing subpatterns, any 2752capturing that occurs in a matching branch is retained afterwards, for both 2753positive and negative assertions, because matching always continues after the 2754assertion, whether it succeeds or fails. (Compare non-conditional assertions, 2755when captures are retained only for positive assertions that succeed.) 2756<a name="comments"></a></P> 2757<br><a name="SEC22" href="#TOC1">COMMENTS</a><br> 2758<P> 2759There are two ways of including comments in patterns that are processed by 2760PCRE2. In both cases, the start of the comment must not be in a character 2761class, nor in the middle of any other sequence of related characters such as 2762(?: or a subpattern name or number. The characters that make up a comment play 2763no part in the pattern matching. 2764</P> 2765<P> 2766The sequence (?# marks the start of a comment that continues up to the next 2767closing parenthesis. Nested parentheses are not permitted. If the 2768PCRE2_EXTENDED or PCRE2_EXTENDED_MORE option is set, an unescaped # character 2769also introduces a comment, which in this case continues to immediately after 2770the next newline character or character sequence in the pattern. Which 2771characters are interpreted as newlines is controlled by an option passed to the 2772compiling function or by a special sequence at the start of the pattern, as 2773described in the section entitled 2774<a href="#newlines">"Newline conventions"</a> 2775above. Note that the end of this type of comment is a literal newline sequence 2776in the pattern; escape sequences that happen to represent a newline do not 2777count. For example, consider this pattern when PCRE2_EXTENDED is set, and the 2778default newline convention (a single linefeed character) is in force: 2779<pre> 2780 abc #comment \n still comment 2781</pre> 2782On encountering the # character, <b>pcre2_compile()</b> skips along, looking for 2783a newline in the pattern. The sequence \n is still literal at this stage, so 2784it does not terminate the comment. Only an actual character with the code value 27850x0a (the default newline) does so. 2786<a name="recursion"></a></P> 2787<br><a name="SEC23" href="#TOC1">RECURSIVE PATTERNS</a><br> 2788<P> 2789Consider the problem of matching a string in parentheses, allowing for 2790unlimited nested parentheses. Without the use of recursion, the best that can 2791be done is to use a pattern that matches up to some fixed depth of nesting. It 2792is not possible to handle an arbitrary nesting depth. 2793</P> 2794<P> 2795For some time, Perl has provided a facility that allows regular expressions to 2796recurse (amongst other things). It does this by interpolating Perl code in the 2797expression at run time, and the code can refer to the expression itself. A Perl 2798pattern using code interpolation to solve the parentheses problem can be 2799created like this: 2800<pre> 2801 $re = qr{\( (?: (?>[^()]+) | (?p{$re}) )* \)}x; 2802</pre> 2803The (?p{...}) item interpolates Perl code at run time, and in this case refers 2804recursively to the pattern in which it appears. 2805</P> 2806<P> 2807Obviously, PCRE2 cannot support the interpolation of Perl code. Instead, it 2808supports special syntax for recursion of the entire pattern, and also for 2809individual subpattern recursion. After its introduction in PCRE1 and Python, 2810this kind of recursion was subsequently introduced into Perl at release 5.10. 2811</P> 2812<P> 2813A special item that consists of (? followed by a number greater than zero and a 2814closing parenthesis is a recursive subroutine call of the subpattern of the 2815given number, provided that it occurs inside that subpattern. (If not, it is a 2816<a href="#subpatternsassubroutines">non-recursive subroutine</a> 2817call, which is described in the next section.) The special item (?R) or (?0) is 2818a recursive call of the entire regular expression. 2819</P> 2820<P> 2821This PCRE2 pattern solves the nested parentheses problem (assume the 2822PCRE2_EXTENDED option is set so that white space is ignored): 2823<pre> 2824 \( ( [^()]++ | (?R) )* \) 2825</pre> 2826First it matches an opening parenthesis. Then it matches any number of 2827substrings which can either be a sequence of non-parentheses, or a recursive 2828match of the pattern itself (that is, a correctly parenthesized substring). 2829Finally there is a closing parenthesis. Note the use of a possessive quantifier 2830to avoid backtracking into sequences of non-parentheses. 2831</P> 2832<P> 2833If this were part of a larger pattern, you would not want to recurse the entire 2834pattern, so instead you could use this: 2835<pre> 2836 ( \( ( [^()]++ | (?1) )* \) ) 2837</pre> 2838We have put the pattern into parentheses, and caused the recursion to refer to 2839them instead of the whole pattern. 2840</P> 2841<P> 2842In a larger pattern, keeping track of parenthesis numbers can be tricky. This 2843is made easier by the use of relative references. Instead of (?1) in the 2844pattern above you can write (?-2) to refer to the second most recently opened 2845parentheses preceding the recursion. In other words, a negative number counts 2846capturing parentheses leftwards from the point at which it is encountered. 2847</P> 2848<P> 2849Be aware however, that if 2850<a href="#dupsubpatternnumber">duplicate subpattern numbers</a> 2851are in use, relative references refer to the earliest subpattern with the 2852appropriate number. Consider, for example: 2853<pre> 2854 (?|(a)|(b)) (c) (?-2) 2855</pre> 2856The first two capturing groups (a) and (b) are both numbered 1, and group (c) 2857is number 2. When the reference (?-2) is encountered, the second most recently 2858opened parentheses has the number 1, but it is the first such group (the (a) 2859group) to which the recursion refers. This would be the same if an absolute 2860reference (?1) was used. In other words, relative references are just a 2861shorthand for computing a group number. 2862</P> 2863<P> 2864It is also possible to refer to subsequently opened parentheses, by writing 2865references such as (?+2). However, these cannot be recursive because the 2866reference is not inside the parentheses that are referenced. They are always 2867<a href="#subpatternsassubroutines">non-recursive subroutine</a> 2868calls, as described in the next section. 2869</P> 2870<P> 2871An alternative approach is to use named parentheses. The Perl syntax for this 2872is (?&name); PCRE1's earlier syntax (?P>name) is also supported. We could 2873rewrite the above example as follows: 2874<pre> 2875 (?<pn> \( ( [^()]++ | (?&pn) )* \) ) 2876</pre> 2877If there is more than one subpattern with the same name, the earliest one is 2878used. 2879</P> 2880<P> 2881The example pattern that we have been looking at contains nested unlimited 2882repeats, and so the use of a possessive quantifier for matching strings of 2883non-parentheses is important when applying the pattern to strings that do not 2884match. For example, when this pattern is applied to 2885<pre> 2886 (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa() 2887</pre> 2888it yields "no match" quickly. However, if a possessive quantifier is not used, 2889the match runs for a very long time indeed because there are so many different 2890ways the + and * repeats can carve up the subject, and all have to be tested 2891before failure can be reported. 2892</P> 2893<P> 2894At the end of a match, the values of capturing parentheses are those from 2895the outermost level. If you want to obtain intermediate values, a callout 2896function can be used (see below and the 2897<a href="pcre2callout.html"><b>pcre2callout</b></a> 2898documentation). If the pattern above is matched against 2899<pre> 2900 (ab(cd)ef) 2901</pre> 2902the value for the inner capturing parentheses (numbered 2) is "ef", which is 2903the last value taken on at the top level. If a capturing subpattern is not 2904matched at the top level, its final captured value is unset, even if it was 2905(temporarily) set at a deeper level during the matching process. 2906</P> 2907<P> 2908Do not confuse the (?R) item with the condition (R), which tests for recursion. 2909Consider this pattern, which matches text in angle brackets, allowing for 2910arbitrary nesting. Only digits are allowed in nested brackets (that is, when 2911recursing), whereas any characters are permitted at the outer level. 2912<pre> 2913 < (?: (?(R) \d++ | [^<>]*+) | (?R)) * > 2914</pre> 2915In this pattern, (?(R) is the start of a conditional subpattern, with two 2916different alternatives for the recursive and non-recursive cases. The (?R) item 2917is the actual recursive call. 2918<a name="recursiondifference"></a></P> 2919<br><b> 2920Differences in recursion processing between PCRE2 and Perl 2921</b><br> 2922<P> 2923Some former differences between PCRE2 and Perl no longer exist. 2924</P> 2925<P> 2926Before release 10.30, recursion processing in PCRE2 differed from Perl in that 2927a recursive subpattern call was always treated as an atomic group. That is, 2928once it had matched some of the subject string, it was never re-entered, even 2929if it contained untried alternatives and there was a subsequent matching 2930failure. (Historical note: PCRE implemented recursion before Perl did.) 2931</P> 2932<P> 2933Starting with release 10.30, recursive subroutine calls are no longer treated 2934as atomic. That is, they can be re-entered to try unused alternatives if there 2935is a matching failure later in the pattern. This is now compatible with the way 2936Perl works. If you want a subroutine call to be atomic, you must explicitly 2937enclose it in an atomic group. 2938</P> 2939<P> 2940Supporting backtracking into recursions simplifies certain types of recursive 2941pattern. For example, this pattern matches palindromic strings: 2942<pre> 2943 ^((.)(?1)\2|.?)$ 2944</pre> 2945The second branch in the group matches a single central character in the 2946palindrome when there are an odd number of characters, or nothing when there 2947are an even number of characters, but in order to work it has to be able to try 2948the second case when the rest of the pattern match fails. If you want to match 2949typical palindromic phrases, the pattern has to ignore all non-word characters, 2950which can be done like this: 2951<pre> 2952 ^\W*+((.)\W*+(?1)\W*+\2|\W*+.?)\W*+$ 2953</pre> 2954If run with the PCRE2_CASELESS option, this pattern matches phrases such as "A 2955man, a plan, a canal: Panama!". Note the use of the possessive quantifier *+ to 2956avoid backtracking into sequences of non-word characters. Without this, PCRE2 2957takes a great deal longer (ten times or more) to match typical phrases, and 2958Perl takes so long that you think it has gone into a loop. 2959</P> 2960<P> 2961Another way in which PCRE2 and Perl used to differ in their recursion 2962processing is in the handling of captured values. Formerly in Perl, when a 2963subpattern was called recursively or as a subpattern (see the next section), it 2964had no access to any values that were captured outside the recursion, whereas 2965in PCRE2 these values can be referenced. Consider this pattern: 2966<pre> 2967 ^(.)(\1|a(?2)) 2968</pre> 2969This pattern matches "bab". The first capturing parentheses match "b", then in 2970the second group, when the backreference \1 fails to match "b", the second 2971alternative matches "a" and then recurses. In the recursion, \1 does now match 2972"b" and so the whole match succeeds. This match used to fail in Perl, but in 2973later versions (I tried 5.024) it now works. 2974<a name="subpatternsassubroutines"></a></P> 2975<br><a name="SEC24" href="#TOC1">SUBPATTERNS AS SUBROUTINES</a><br> 2976<P> 2977If the syntax for a recursive subpattern call (either by number or by 2978name) is used outside the parentheses to which it refers, it operates a bit 2979like a subroutine in a programming language. More accurately, PCRE2 treats the 2980referenced subpattern as an independent subpattern which it tries to match at 2981the current matching position. The called subpattern may be defined before or 2982after the reference. A numbered reference can be absolute or relative, as in 2983these examples: 2984<pre> 2985 (...(absolute)...)...(?2)... 2986 (...(relative)...)...(?-1)... 2987 (...(?+1)...(relative)... 2988</pre> 2989An earlier example pointed out that the pattern 2990<pre> 2991 (sens|respons)e and \1ibility 2992</pre> 2993matches "sense and sensibility" and "response and responsibility", but not 2994"sense and responsibility". If instead the pattern 2995<pre> 2996 (sens|respons)e and (?1)ibility 2997</pre> 2998is used, it does match "sense and responsibility" as well as the other two 2999strings. Another example is given in the discussion of DEFINE above. 3000</P> 3001<P> 3002Like recursions, subroutine calls used to be treated as atomic, but this 3003changed at PCRE2 release 10.30, so backtracking into subroutine calls can now 3004occur. However, any capturing parentheses that are set during the subroutine 3005call revert to their previous values afterwards. 3006</P> 3007<P> 3008Processing options such as case-independence are fixed when a subpattern is 3009defined, so if it is used as a subroutine, such options cannot be changed for 3010different calls. For example, consider this pattern: 3011<pre> 3012 (abc)(?i:(?-1)) 3013</pre> 3014It matches "abcabc". It does not match "abcABC" because the change of 3015processing option does not affect the called subpattern. 3016</P> 3017<P> 3018The behaviour of 3019<a href="#backtrackcontrol">backtracking control verbs</a> 3020in subpatterns when called as subroutines is described in the section entitled 3021<a href="#btsub">"Backtracking verbs in subroutines"</a> 3022below. 3023<a name="onigurumasubroutines"></a></P> 3024<br><a name="SEC25" href="#TOC1">ONIGURUMA SUBROUTINE SYNTAX</a><br> 3025<P> 3026For compatibility with Oniguruma, the non-Perl syntax \g followed by a name or 3027a number enclosed either in angle brackets or single quotes, is an alternative 3028syntax for referencing a subpattern as a subroutine, possibly recursively. Here 3029are two of the examples used above, rewritten using this syntax: 3030<pre> 3031 (?<pn> \( ( (?>[^()]+) | \g<pn> )* \) ) 3032 (sens|respons)e and \g'1'ibility 3033</pre> 3034PCRE2 supports an extension to Oniguruma: if a number is preceded by a 3035plus or a minus sign it is taken as a relative reference. For example: 3036<pre> 3037 (abc)(?i:\g<-1>) 3038</pre> 3039Note that \g{...} (Perl syntax) and \g<...> (Oniguruma syntax) are <i>not</i> 3040synonymous. The former is a backreference; the latter is a subroutine call. 3041</P> 3042<br><a name="SEC26" href="#TOC1">CALLOUTS</a><br> 3043<P> 3044Perl has a feature whereby using the sequence (?{...}) causes arbitrary Perl 3045code to be obeyed in the middle of matching a regular expression. This makes it 3046possible, amongst other things, to extract different substrings that match the 3047same pair of parentheses when there is a repetition. 3048</P> 3049<P> 3050PCRE2 provides a similar feature, but of course it cannot obey arbitrary Perl 3051code. The feature is called "callout". The caller of PCRE2 provides an external 3052function by putting its entry point in a match context using the function 3053<b>pcre2_set_callout()</b>, and then passing that context to <b>pcre2_match()</b> 3054or <b>pcre2_dfa_match()</b>. If no match context is passed, or if the callout 3055entry point is set to NULL, callouts are disabled. 3056</P> 3057<P> 3058Within a regular expression, (?C<arg>) indicates a point at which the external 3059function is to be called. There are two kinds of callout: those with a 3060numerical argument and those with a string argument. (?C) on its own with no 3061argument is treated as (?C0). A numerical argument allows the application to 3062distinguish between different callouts. String arguments were added for release 306310.20 to make it possible for script languages that use PCRE2 to embed short 3064scripts within patterns in a similar way to Perl. 3065</P> 3066<P> 3067During matching, when PCRE2 reaches a callout point, the external function is 3068called. It is provided with the number or string argument of the callout, the 3069position in the pattern, and one item of data that is also set in the match 3070block. The callout function may cause matching to proceed, to backtrack, or to 3071fail. 3072</P> 3073<P> 3074By default, PCRE2 implements a number of optimizations at matching time, and 3075one side-effect is that sometimes callouts are skipped. If you need all 3076possible callouts to happen, you need to set options that disable the relevant 3077optimizations. More details, including a complete description of the 3078programming interface to the callout function, are given in the 3079<a href="pcre2callout.html"><b>pcre2callout</b></a> 3080documentation. 3081</P> 3082<br><b> 3083Callouts with numerical arguments 3084</b><br> 3085<P> 3086If you just want to have a means of identifying different callout points, put a 3087number less than 256 after the letter C. For example, this pattern has two 3088callout points: 3089<pre> 3090 (?C1)abc(?C2)def 3091</pre> 3092If the PCRE2_AUTO_CALLOUT flag is passed to <b>pcre2_compile()</b>, numerical 3093callouts are automatically installed before each item in the pattern. They are 3094all numbered 255. If there is a conditional group in the pattern whose 3095condition is an assertion, an additional callout is inserted just before the 3096condition. An explicit callout may also be set at this position, as in this 3097example: 3098<pre> 3099 (?(?C9)(?=a)abc|def) 3100</pre> 3101Note that this applies only to assertion conditions, not to other types of 3102condition. 3103</P> 3104<br><b> 3105Callouts with string arguments 3106</b><br> 3107<P> 3108A delimited string may be used instead of a number as a callout argument. The 3109starting delimiter must be one of ` ' " ^ % # $ { and the ending delimiter is 3110the same as the start, except for {, where the ending delimiter is }. If the 3111ending delimiter is needed within the string, it must be doubled. For 3112example: 3113<pre> 3114 (?C'ab ''c'' d')xyz(?C{any text})pqr 3115</pre> 3116The doubling is removed before the string is passed to the callout function. 3117<a name="backtrackcontrol"></a></P> 3118<br><a name="SEC27" href="#TOC1">BACKTRACKING CONTROL</a><br> 3119<P> 3120There are a number of special "Backtracking Control Verbs" (to use Perl's 3121terminology) that modify the behaviour of backtracking during matching. They 3122are generally of the form (*VERB) or (*VERB:NAME). Some verbs take either form, 3123possibly behaving differently depending on whether or not a name is present. 3124</P> 3125<P> 3126By default, for compatibility with Perl, a name is any sequence of characters 3127that does not include a closing parenthesis. The name is not processed in 3128any way, and it is not possible to include a closing parenthesis in the name. 3129This can be changed by setting the PCRE2_ALT_VERBNAMES option, but the result 3130is no longer Perl-compatible. 3131</P> 3132<P> 3133When PCRE2_ALT_VERBNAMES is set, backslash processing is applied to verb names 3134and only an unescaped closing parenthesis terminates the name. However, the 3135only backslash items that are permitted are \Q, \E, and sequences such as 3136\x{100} that define character code points. Character type escapes such as \d 3137are faulted. 3138</P> 3139<P> 3140A closing parenthesis can be included in a name either as \) or between \Q 3141and \E. In addition to backslash processing, if the PCRE2_EXTENDED or 3142PCRE2_EXTENDED_MORE option is also set, unescaped whitespace in verb names is 3143skipped, and #-comments are recognized, exactly as in the rest of the pattern. 3144PCRE2_EXTENDED and PCRE2_EXTENDED_MORE do not affect verb names unless 3145PCRE2_ALT_VERBNAMES is also set. 3146</P> 3147<P> 3148The maximum length of a name is 255 in the 8-bit library and 65535 in the 314916-bit and 32-bit libraries. If the name is empty, that is, if the closing 3150parenthesis immediately follows the colon, the effect is as if the colon were 3151not there. Any number of these verbs may occur in a pattern. 3152</P> 3153<P> 3154Since these verbs are specifically related to backtracking, most of them can be 3155used only when the pattern is to be matched using the traditional matching 3156function, because that uses a backtracking algorithm. With the exception of 3157(*FAIL), which behaves like a failing negative assertion, the backtracking 3158control verbs cause an error if encountered by the DFA matching function. 3159</P> 3160<P> 3161The behaviour of these verbs in 3162<a href="#btrepeat">repeated groups,</a> 3163<a href="#btassert">assertions,</a> 3164and in 3165<a href="#btsub">subpatterns called as subroutines</a> 3166(whether or not recursively) is documented below. 3167<a name="nooptimize"></a></P> 3168<br><b> 3169Optimizations that affect backtracking verbs 3170</b><br> 3171<P> 3172PCRE2 contains some optimizations that are used to speed up matching by running 3173some checks at the start of each match attempt. For example, it may know the 3174minimum length of matching subject, or that a particular character must be 3175present. When one of these optimizations bypasses the running of a match, any 3176included backtracking verbs will not, of course, be processed. You can suppress 3177the start-of-match optimizations by setting the PCRE2_NO_START_OPTIMIZE option 3178when calling <b>pcre2_compile()</b>, or by starting the pattern with 3179(*NO_START_OPT). There is more discussion of this option in the section 3180entitled 3181<a href="pcre2api.html#compiling">"Compiling a pattern"</a> 3182in the 3183<a href="pcre2api.html"><b>pcre2api</b></a> 3184documentation. 3185</P> 3186<P> 3187Experiments with Perl suggest that it too has similar optimizations, and like 3188PCRE2, turning them off can change the result of a match. 3189</P> 3190<br><b> 3191Verbs that act immediately 3192</b><br> 3193<P> 3194The following verbs act as soon as they are encountered. 3195<pre> 3196 (*ACCEPT) or (*ACCEPT:NAME) 3197</pre> 3198This verb causes the match to end successfully, skipping the remainder of the 3199pattern. However, when it is inside a subpattern that is called as a 3200subroutine, only that subpattern is ended successfully. Matching then continues 3201at the outer level. If (*ACCEPT) in triggered in a positive assertion, the 3202assertion succeeds; in a negative assertion, the assertion fails. 3203</P> 3204<P> 3205If (*ACCEPT) is inside capturing parentheses, the data so far is captured. For 3206example: 3207<pre> 3208 A((?:A|B(*ACCEPT)|C)D) 3209</pre> 3210This matches "AB", "AAD", or "ACD"; when it matches "AB", "B" is captured by 3211the outer parentheses. 3212<pre> 3213 (*FAIL) or (*FAIL:NAME) 3214</pre> 3215This verb causes a matching failure, forcing backtracking to occur. It may be 3216abbreviated to (*F). It is equivalent to (?!) but easier to read. The Perl 3217documentation notes that it is probably useful only when combined with (?{}) or 3218(??{}). Those are, of course, Perl features that are not present in PCRE2. The 3219nearest equivalent is the callout feature, as for example in this pattern: 3220<pre> 3221 a+(?C)(*FAIL) 3222</pre> 3223A match with the string "aaaa" always fails, but the callout is taken before 3224each backtrack happens (in this example, 10 times). 3225</P> 3226<P> 3227(*ACCEPT:NAME) and (*FAIL:NAME) behave exactly the same as 3228(*MARK:NAME)(*ACCEPT) and (*MARK:NAME)(*FAIL), respectively. 3229</P> 3230<br><b> 3231Recording which path was taken 3232</b><br> 3233<P> 3234There is one verb whose main purpose is to track how a match was arrived at, 3235though it also has a secondary use in conjunction with advancing the match 3236starting point (see (*SKIP) below). 3237<pre> 3238 (*MARK:NAME) or (*:NAME) 3239</pre> 3240A name is always required with this verb. There may be as many instances of 3241(*MARK) as you like in a pattern, and their names do not have to be unique. 3242</P> 3243<P> 3244When a match succeeds, the name of the last-encountered (*MARK:NAME) on the 3245matching path is passed back to the caller as described in the section entitled 3246<a href="pcre2api.html#matchotherdata">"Other information about the match"</a> 3247in the 3248<a href="pcre2api.html"><b>pcre2api</b></a> 3249documentation. This applies to all instances of (*MARK), including those inside 3250assertions and atomic groups. (There are differences in those cases when 3251(*MARK) is used in conjunction with (*SKIP) as described below.) 3252</P> 3253<P> 3254As well as (*MARK), the (*COMMIT), (*PRUNE) and (*THEN) verbs may have 3255associated NAME arguments. Whichever is last on the matching path is passed 3256back. See below for more details of these other verbs. 3257</P> 3258<P> 3259Here is an example of <b>pcre2test</b> output, where the "mark" modifier 3260requests the retrieval and outputting of (*MARK) data: 3261<pre> 3262 re> /X(*MARK:A)Y|X(*MARK:B)Z/mark 3263 data> XY 3264 0: XY 3265 MK: A 3266 XZ 3267 0: XZ 3268 MK: B 3269</pre> 3270The (*MARK) name is tagged with "MK:" in this output, and in this example it 3271indicates which of the two alternatives matched. This is a more efficient way 3272of obtaining this information than putting each alternative in its own 3273capturing parentheses. 3274</P> 3275<P> 3276If a verb with a name is encountered in a positive assertion that is true, the 3277name is recorded and passed back if it is the last-encountered. This does not 3278happen for negative assertions or failing positive assertions. 3279</P> 3280<P> 3281After a partial match or a failed match, the last encountered name in the 3282entire match process is returned. For example: 3283<pre> 3284 re> /X(*MARK:A)Y|X(*MARK:B)Z/mark 3285 data> XP 3286 No match, mark = B 3287</pre> 3288Note that in this unanchored example the mark is retained from the match 3289attempt that started at the letter "X" in the subject. Subsequent match 3290attempts starting at "P" and then with an empty string do not get as far as the 3291(*MARK) item, but nevertheless do not reset it. 3292</P> 3293<P> 3294If you are interested in (*MARK) values after failed matches, you should 3295probably set the PCRE2_NO_START_OPTIMIZE option 3296<a href="#nooptimize">(see above)</a> 3297to ensure that the match is always attempted. 3298</P> 3299<br><b> 3300Verbs that act after backtracking 3301</b><br> 3302<P> 3303The following verbs do nothing when they are encountered. Matching continues 3304with what follows, but if there is a subsequent match failure, causing a 3305backtrack to the verb, a failure is forced. That is, backtracking cannot pass 3306to the left of the verb. However, when one of these verbs appears inside an 3307atomic group or in a lookaround assertion that is true, its effect is confined 3308to that group, because once the group has been matched, there is never any 3309backtracking into it. Backtracking from beyond an assertion or an atomic group 3310ignores the entire group, and seeks a preceeding backtracking point. 3311</P> 3312<P> 3313These verbs differ in exactly what kind of failure occurs when backtracking 3314reaches them. The behaviour described below is what happens when the verb is 3315not in a subroutine or an assertion. Subsequent sections cover these special 3316cases. 3317<pre> 3318 (*COMMIT) or (*COMMIT:NAME) 3319</pre> 3320This verb causes the whole match to fail outright if there is a later matching 3321failure that causes backtracking to reach it. Even if the pattern is 3322unanchored, no further attempts to find a match by advancing the starting point 3323take place. If (*COMMIT) is the only backtracking verb that is encountered, 3324once it has been passed <b>pcre2_match()</b> is committed to finding a match at 3325the current starting point, or not at all. For example: 3326<pre> 3327 a+(*COMMIT)b 3328</pre> 3329This matches "xxaab" but not "aacaab". It can be thought of as a kind of 3330dynamic anchor, or "I've started, so I must finish." 3331</P> 3332<P> 3333The behaviour of (*COMMIT:NAME) is not the same as (*MARK:NAME)(*COMMIT). It is 3334like (*MARK:NAME) in that the name is remembered for passing back to the 3335caller. However, (*SKIP:NAME) searches only for names set with (*MARK), 3336ignoring those set by (*COMMIT), (*PRUNE) and (*THEN). 3337</P> 3338<P> 3339If there is more than one backtracking verb in a pattern, a different one that 3340follows (*COMMIT) may be triggered first, so merely passing (*COMMIT) during a 3341match does not always guarantee that a match must be at this starting point. 3342</P> 3343<P> 3344Note that (*COMMIT) at the start of a pattern is not the same as an anchor, 3345unless PCRE2's start-of-match optimizations are turned off, as shown in this 3346output from <b>pcre2test</b>: 3347<pre> 3348 re> /(*COMMIT)abc/ 3349 data> xyzabc 3350 0: abc 3351 data> 3352 re> /(*COMMIT)abc/no_start_optimize 3353 data> xyzabc 3354 No match 3355</pre> 3356For the first pattern, PCRE2 knows that any match must start with "a", so the 3357optimization skips along the subject to "a" before applying the pattern to the 3358first set of data. The match attempt then succeeds. The second pattern disables 3359the optimization that skips along to the first character. The pattern is now 3360applied starting at "x", and so the (*COMMIT) causes the match to fail without 3361trying any other starting points. 3362<pre> 3363 (*PRUNE) or (*PRUNE:NAME) 3364</pre> 3365This verb causes the match to fail at the current starting position in the 3366subject if there is a later matching failure that causes backtracking to reach 3367it. If the pattern is unanchored, the normal "bumpalong" advance to the next 3368starting character then happens. Backtracking can occur as usual to the left of 3369(*PRUNE), before it is reached, or when matching to the right of (*PRUNE), but 3370if there is no match to the right, backtracking cannot cross (*PRUNE). In 3371simple cases, the use of (*PRUNE) is just an alternative to an atomic group or 3372possessive quantifier, but there are some uses of (*PRUNE) that cannot be 3373expressed in any other way. In an anchored pattern (*PRUNE) has the same effect 3374as (*COMMIT). 3375</P> 3376<P> 3377The behaviour of (*PRUNE:NAME) is not the same as (*MARK:NAME)(*PRUNE). It is 3378like (*MARK:NAME) in that the name is remembered for passing back to the 3379caller. However, (*SKIP:NAME) searches only for names set with (*MARK), 3380ignoring those set by (*COMMIT), (*PRUNE) or (*THEN). 3381<pre> 3382 (*SKIP) 3383</pre> 3384This verb, when given without a name, is like (*PRUNE), except that if the 3385pattern is unanchored, the "bumpalong" advance is not to the next character, 3386but to the position in the subject where (*SKIP) was encountered. (*SKIP) 3387signifies that whatever text was matched leading up to it cannot be part of a 3388successful match if there is a later mismatch. Consider: 3389<pre> 3390 a+(*SKIP)b 3391</pre> 3392If the subject is "aaaac...", after the first match attempt fails (starting at 3393the first character in the string), the starting point skips on to start the 3394next attempt at "c". Note that a possessive quantifer does not have the same 3395effect as this example; although it would suppress backtracking during the 3396first match attempt, the second attempt would start at the second character 3397instead of skipping on to "c". 3398<pre> 3399 (*SKIP:NAME) 3400</pre> 3401When (*SKIP) has an associated name, its behaviour is modified. When such a 3402(*SKIP) is triggered, the previous path through the pattern is searched for the 3403most recent (*MARK) that has the same name. If one is found, the "bumpalong" 3404advance is to the subject position that corresponds to that (*MARK) instead of 3405to where (*SKIP) was encountered. If no (*MARK) with a matching name is found, 3406the (*SKIP) is ignored. 3407</P> 3408<P> 3409The search for a (*MARK) name uses the normal backtracking mechanism, which 3410means that it does not see (*MARK) settings that are inside atomic groups or 3411assertions, because they are never re-entered by backtracking. Compare the 3412following <b>pcre2test</b> examples: 3413<pre> 3414 re> /a(?>(*MARK:X))(*SKIP:X)(*F)|(.)/ 3415 data: abc 3416 0: a 3417 1: a 3418 data: 3419 re> /a(?:(*MARK:X))(*SKIP:X)(*F)|(.)/ 3420 data: abc 3421 0: b 3422 1: b 3423</pre> 3424In the first example, the (*MARK) setting is in an atomic group, so it is not 3425seen when (*SKIP:X) triggers, causing the (*SKIP) to be ignored. This allows 3426the second branch of the pattern to be tried at the first character position. 3427In the second example, the (*MARK) setting is not in an atomic group. This 3428allows (*SKIP:X) to find the (*MARK) when it backtracks, and this causes a new 3429matching attempt to start at the second character. This time, the (*MARK) is 3430never seen because "a" does not match "b", so the matcher immediately jumps to 3431the second branch of the pattern. 3432</P> 3433<P> 3434Note that (*SKIP:NAME) searches only for names set by (*MARK:NAME). It ignores 3435names that are set by (*COMMIT:NAME), (*PRUNE:NAME) or (*THEN:NAME). 3436<pre> 3437 (*THEN) or (*THEN:NAME) 3438</pre> 3439This verb causes a skip to the next innermost alternative when backtracking 3440reaches it. That is, it cancels any further backtracking within the current 3441alternative. Its name comes from the observation that it can be used for a 3442pattern-based if-then-else block: 3443<pre> 3444 ( COND1 (*THEN) FOO | COND2 (*THEN) BAR | COND3 (*THEN) BAZ ) ... 3445</pre> 3446If the COND1 pattern matches, FOO is tried (and possibly further items after 3447the end of the group if FOO succeeds); on failure, the matcher skips to the 3448second alternative and tries COND2, without backtracking into COND1. If that 3449succeeds and BAR fails, COND3 is tried. If subsequently BAZ fails, there are no 3450more alternatives, so there is a backtrack to whatever came before the entire 3451group. If (*THEN) is not inside an alternation, it acts like (*PRUNE). 3452</P> 3453<P> 3454The behaviour of (*THEN:NAME) is not the same as (*MARK:NAME)(*THEN). It is 3455like (*MARK:NAME) in that the name is remembered for passing back to the 3456caller. However, (*SKIP:NAME) searches only for names set with (*MARK), 3457ignoring those set by (*COMMIT), (*PRUNE) and (*THEN). 3458</P> 3459<P> 3460A subpattern that does not contain a | character is just a part of the 3461enclosing alternative; it is not a nested alternation with only one 3462alternative. The effect of (*THEN) extends beyond such a subpattern to the 3463enclosing alternative. Consider this pattern, where A, B, etc. are complex 3464pattern fragments that do not contain any | characters at this level: 3465<pre> 3466 A (B(*THEN)C) | D 3467</pre> 3468If A and B are matched, but there is a failure in C, matching does not 3469backtrack into A; instead it moves to the next alternative, that is, D. 3470However, if the subpattern containing (*THEN) is given an alternative, it 3471behaves differently: 3472<pre> 3473 A (B(*THEN)C | (*FAIL)) | D 3474</pre> 3475The effect of (*THEN) is now confined to the inner subpattern. After a failure 3476in C, matching moves to (*FAIL), which causes the whole subpattern to fail 3477because there are no more alternatives to try. In this case, matching does now 3478backtrack into A. 3479</P> 3480<P> 3481Note that a conditional subpattern is not considered as having two 3482alternatives, because only one is ever used. In other words, the | character in 3483a conditional subpattern has a different meaning. Ignoring white space, 3484consider: 3485<pre> 3486 ^.*? (?(?=a) a | b(*THEN)c ) 3487</pre> 3488If the subject is "ba", this pattern does not match. Because .*? is ungreedy, 3489it initially matches zero characters. The condition (?=a) then fails, the 3490character "b" is matched, but "c" is not. At this point, matching does not 3491backtrack to .*? as might perhaps be expected from the presence of the | 3492character. The conditional subpattern is part of the single alternative that 3493comprises the whole pattern, and so the match fails. (If there was a backtrack 3494into .*?, allowing it to match "b", the match would succeed.) 3495</P> 3496<P> 3497The verbs just described provide four different "strengths" of control when 3498subsequent matching fails. (*THEN) is the weakest, carrying on the match at the 3499next alternative. (*PRUNE) comes next, failing the match at the current 3500starting position, but allowing an advance to the next character (for an 3501unanchored pattern). (*SKIP) is similar, except that the advance may be more 3502than one character. (*COMMIT) is the strongest, causing the entire match to 3503fail. 3504</P> 3505<br><b> 3506More than one backtracking verb 3507</b><br> 3508<P> 3509If more than one backtracking verb is present in a pattern, the one that is 3510backtracked onto first acts. For example, consider this pattern, where A, B, 3511etc. are complex pattern fragments: 3512<pre> 3513 (A(*COMMIT)B(*THEN)C|ABD) 3514</pre> 3515If A matches but B fails, the backtrack to (*COMMIT) causes the entire match to 3516fail. However, if A and B match, but C fails, the backtrack to (*THEN) causes 3517the next alternative (ABD) to be tried. This behaviour is consistent, but is 3518not always the same as Perl's. It means that if two or more backtracking verbs 3519appear in succession, all the the last of them has no effect. Consider this 3520example: 3521<pre> 3522 ...(*COMMIT)(*PRUNE)... 3523</pre> 3524If there is a matching failure to the right, backtracking onto (*PRUNE) causes 3525it to be triggered, and its action is taken. There can never be a backtrack 3526onto (*COMMIT). 3527<a name="btrepeat"></a></P> 3528<br><b> 3529Backtracking verbs in repeated groups 3530</b><br> 3531<P> 3532PCRE2 sometimes differs from Perl in its handling of backtracking verbs in 3533repeated groups. For example, consider: 3534<pre> 3535 /(a(*COMMIT)b)+ac/ 3536</pre> 3537If the subject is "abac", Perl matches unless its optimizations are disabled, 3538but PCRE2 always fails because the (*COMMIT) in the second repeat of the group 3539acts. 3540<a name="btassert"></a></P> 3541<br><b> 3542Backtracking verbs in assertions 3543</b><br> 3544<P> 3545(*FAIL) in any assertion has its normal effect: it forces an immediate 3546backtrack. The behaviour of the other backtracking verbs depends on whether or 3547not the assertion is standalone or acting as the condition in a conditional 3548subpattern. 3549</P> 3550<P> 3551(*ACCEPT) in a standalone positive assertion causes the assertion to succeed 3552without any further processing; captured strings and a (*MARK) name (if set) 3553are retained. In a standalone negative assertion, (*ACCEPT) causes the 3554assertion to fail without any further processing; captured substrings and any 3555(*MARK) name are discarded. 3556</P> 3557<P> 3558If the assertion is a condition, (*ACCEPT) causes the condition to be true for 3559a positive assertion and false for a negative one; captured substrings are 3560retained in both cases. 3561</P> 3562<P> 3563The remaining verbs act only when a later failure causes a backtrack to 3564reach them. This means that their effect is confined to the assertion, 3565because lookaround assertions are atomic. A backtrack that occurs after an 3566assertion is complete does not jump back into the assertion. Note in particular 3567that a (*MARK) name that is set in an assertion is not "seen" by an instance of 3568(*SKIP:NAME) latter in the pattern. 3569</P> 3570<P> 3571The effect of (*THEN) is not allowed to escape beyond an assertion. If there 3572are no more branches to try, (*THEN) causes a positive assertion to be false, 3573and a negative assertion to be true. 3574</P> 3575<P> 3576The other backtracking verbs are not treated specially if they appear in a 3577standalone positive assertion. In a conditional positive assertion, 3578backtracking (from within the assertion) into (*COMMIT), (*SKIP), or (*PRUNE) 3579causes the condition to be false. However, for both standalone and conditional 3580negative assertions, backtracking into (*COMMIT), (*SKIP), or (*PRUNE) causes 3581the assertion to be true, without considering any further alternative branches. 3582<a name="btsub"></a></P> 3583<br><b> 3584Backtracking verbs in subroutines 3585</b><br> 3586<P> 3587These behaviours occur whether or not the subpattern is called recursively. 3588</P> 3589<P> 3590(*ACCEPT) in a subpattern called as a subroutine causes the subroutine match to 3591succeed without any further processing. Matching then continues after the 3592subroutine call. Perl documents this behaviour. Perl's treatment of the other 3593verbs in subroutines is different in some cases. 3594</P> 3595<P> 3596(*FAIL) in a subpattern called as a subroutine has its normal effect: it forces 3597an immediate backtrack. 3598</P> 3599<P> 3600(*COMMIT), (*SKIP), and (*PRUNE) cause the subroutine match to fail when 3601triggered by being backtracked to in a subpattern called as a subroutine. There 3602is then a backtrack at the outer level. 3603</P> 3604<P> 3605(*THEN), when triggered, skips to the next alternative in the innermost 3606enclosing group within the subpattern that has alternatives (its normal 3607behaviour). However, if there is no such group within the subroutine 3608subpattern, the subroutine match fails and there is a backtrack at the outer 3609level. 3610</P> 3611<br><a name="SEC28" href="#TOC1">SEE ALSO</a><br> 3612<P> 3613<b>pcre2api</b>(3), <b>pcre2callout</b>(3), <b>pcre2matching</b>(3), 3614<b>pcre2syntax</b>(3), <b>pcre2</b>(3). 3615</P> 3616<br><a name="SEC29" href="#TOC1">AUTHOR</a><br> 3617<P> 3618Philip Hazel 3619<br> 3620University Computing Service 3621<br> 3622Cambridge, England. 3623<br> 3624</P> 3625<br><a name="SEC30" href="#TOC1">REVISION</a><br> 3626<P> 3627Last updated: 04 September 2018 3628<br> 3629Copyright © 1997-2018 University of Cambridge. 3630<br> 3631<p> 3632Return to the <a href="index.html">PCRE2 index page</a>. 3633</p> 3634