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