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