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