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