• 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
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.
780</P>
781<P>
782Matching characters by Unicode property is not fast, because PCRE2 has to do a
783multistage table lookup in order to find a character's property. That is why
784the traditional escape sequences such as \d and \w do not use Unicode
785properties in PCRE2 by default, though you can make them do so by setting the
786PCRE2_UCP option or by starting the pattern with (*UCP).
787</P>
788<P>
789The extra escape sequences that provide property support are:
790<pre>
791  \p{<i>xx</i>}   a character with the <i>xx</i> property
792  \P{<i>xx</i>}   a character without the <i>xx</i> property
793  \X       a Unicode extended grapheme cluster
794</pre>
795The property names represented by <i>xx</i> above are not case-sensitive, and in
796accordance with Unicode's "loose matching" rules, spaces, hyphens, and
797underscores are ignored. There is support for Unicode script names, Unicode
798general category properties, "Any", which matches any character (including
799newline), Bidi_Class, a number of binary (yes/no) properties, and some special
800PCRE2 properties (described
801<a href="#extraprops">below).</a>
802Certain other Perl properties such as "InMusicalSymbols" are not supported by
803PCRE2. Note that \P{Any} does not match any characters, so always causes a
804match failure.
805</P>
806<br><b>
807Script properties for \p and \P
808</b><br>
809<P>
810There are three different syntax forms for matching a script. Each Unicode
811character has a basic script and, optionally, a list of other scripts ("Script
812Extensions") with which it is commonly used. Using the Adlam script as an
813example, \p{sc:Adlam} matches characters whose basic script is Adlam, whereas
814\p{scx:Adlam} matches, in addition, characters that have Adlam in their
815extensions list. The full names "script" and "script extensions" for the
816property types are recognized, and a equals sign is an alternative to the
817colon. If a script name is given without a property type, for example,
818\p{Adlam}, it is treated as \p{scx:Adlam}. Perl changed to this
819interpretation at release 5.26 and PCRE2 changed at release 10.40.
820</P>
821<P>
822Unassigned characters (and in non-UTF 32-bit mode, characters with code points
823greater than 0x10FFFF) are assigned the "Unknown" script. Others that are not
824part of an identified script are lumped together as "Common". The current list
825of recognized script names and their 4-character abbreviations can be obtained
826by running this command:
827<pre>
828  pcre2test -LS
829
830</PRE>
831</P>
832<br><b>
833The general category property for \p and \P
834</b><br>
835<P>
836Each character has exactly one Unicode general category property, specified by
837a two-letter abbreviation. For compatibility with Perl, negation can be
838specified by including a circumflex between the opening brace and the property
839name. For example, \p{^Lu} is the same as \P{Lu}.
840</P>
841<P>
842If only one letter is specified with \p or \P, it includes all the general
843category properties that start with that letter. In this case, in the absence
844of negation, the curly brackets in the escape sequence are optional; these two
845examples have the same effect:
846<pre>
847  \p{L}
848  \pL
849</pre>
850The following general category property codes are supported:
851<pre>
852  C     Other
853  Cc    Control
854  Cf    Format
855  Cn    Unassigned
856  Co    Private use
857  Cs    Surrogate
858
859  L     Letter
860  Ll    Lower case letter
861  Lm    Modifier letter
862  Lo    Other letter
863  Lt    Title case letter
864  Lu    Upper case letter
865
866  M     Mark
867  Mc    Spacing mark
868  Me    Enclosing mark
869  Mn    Non-spacing mark
870
871  N     Number
872  Nd    Decimal number
873  Nl    Letter number
874  No    Other number
875
876  P     Punctuation
877  Pc    Connector punctuation
878  Pd    Dash punctuation
879  Pe    Close punctuation
880  Pf    Final punctuation
881  Pi    Initial punctuation
882  Po    Other punctuation
883  Ps    Open punctuation
884
885  S     Symbol
886  Sc    Currency symbol
887  Sk    Modifier symbol
888  Sm    Mathematical symbol
889  So    Other symbol
890
891  Z     Separator
892  Zl    Line separator
893  Zp    Paragraph separator
894  Zs    Space separator
895</pre>
896The special property LC, which has the synonym L&, is also supported: it
897matches a character that has the Lu, Ll, or Lt property, in other words, a
898letter that is not classified as a modifier or "other".
899</P>
900<P>
901The Cs (Surrogate) property applies only to characters whose code points are in
902the range U+D800 to U+DFFF. These characters are no different to any other
903character when PCRE2 is not in UTF mode (using the 16-bit or 32-bit library).
904However, they are not valid in Unicode strings and so cannot be tested by PCRE2
905in UTF mode, unless UTF validity checking has been turned off (see the
906discussion of PCRE2_NO_UTF_CHECK in the
907<a href="pcre2api.html"><b>pcre2api</b></a>
908page).
909</P>
910<P>
911The long synonyms for property names that Perl supports (such as \p{Letter})
912are not supported by PCRE2, nor is it permitted to prefix any of these
913properties with "Is".
914</P>
915<P>
916No character that is in the Unicode table has the Cn (unassigned) property.
917Instead, this property is assumed for any code point that is not in the
918Unicode table.
919</P>
920<P>
921Specifying caseless matching does not affect these escape sequences. For
922example, \p{Lu} always matches only upper case letters. This is different from
923the behaviour of current versions of Perl.
924</P>
925<br><b>
926Binary (yes/no) properties for \p and \P
927</b><br>
928<P>
929Unicode defines a number of binary properties, that is, properties whose only
930values are true or false. You can obtain a list of those that are recognized by
931\p and \P, along with their abbreviations, by running this command:
932<pre>
933  pcre2test -LP
934
935</PRE>
936</P>
937<br><b>
938The Bidi_Class property for \p and \P
939</b><br>
940<P>
941<pre>
942  \p{Bidi_Class:&#60;class&#62;}   matches a character with the given class
943  \p{BC:&#60;class&#62;}           matches a character with the given class
944</pre>
945The recognized classes are:
946<pre>
947  AL          Arabic letter
948  AN          Arabic number
949  B           paragraph separator
950  BN          boundary neutral
951  CS          common separator
952  EN          European number
953  ES          European separator
954  ET          European terminator
955  FSI         first strong isolate
956  L           left-to-right
957  LRE         left-to-right embedding
958  LRI         left-to-right isolate
959  LRO         left-to-right override
960  NSM         non-spacing mark
961  ON          other neutral
962  PDF         pop directional format
963  PDI         pop directional isolate
964  R           right-to-left
965  RLE         right-to-left embedding
966  RLI         right-to-left isolate
967  RLO         right-to-left override
968  S           segment separator
969  WS          which space
970</pre>
971An equals sign may be used instead of a colon. The class names are
972case-insensitive; only the short names listed above are recognized.
973</P>
974<br><b>
975Extended grapheme clusters
976</b><br>
977<P>
978The \X escape matches any number of Unicode characters that form an "extended
979grapheme cluster", and treats the sequence as an atomic group
980<a href="#atomicgroup">(see below).</a>
981Unicode supports various kinds of composite character by giving each character
982a grapheme breaking property, and having rules that use these properties to
983define the boundaries of extended grapheme clusters. The rules are defined in
984Unicode Standard Annex 29, "Unicode Text Segmentation". Unicode 11.0.0
985abandoned the use of some previous properties that had been used for emojis.
986Instead it introduced various emoji-specific properties. PCRE2 uses only the
987Extended Pictographic property.
988</P>
989<P>
990\X always matches at least one character. Then it decides whether to add
991additional characters according to the following rules for ending a cluster:
992</P>
993<P>
9941. End at the end of the subject string.
995</P>
996<P>
9972. Do not end between CR and LF; otherwise end after any control character.
998</P>
999<P>
10003. Do not break Hangul (a Korean script) syllable sequences. Hangul characters
1001are of five types: L, V, T, LV, and LVT. An L character may be followed by an
1002L, V, LV, or LVT character; an LV or V character may be followed by a V or T
1003character; an LVT or T character may be followed only by a T character.
1004</P>
1005<P>
10064. Do not end before extending characters or spacing marks or the "zero-width
1007joiner" character. Characters with the "mark" property always have the
1008"extend" grapheme breaking property.
1009</P>
1010<P>
10115. Do not end after prepend characters.
1012</P>
1013<P>
10146. Do not break within emoji modifier sequences or emoji zwj sequences. That
1015is, do not break between characters with the Extended_Pictographic property.
1016Extend and ZWJ characters are allowed between the characters.
1017</P>
1018<P>
10197. Do not break within emoji flag sequences. That is, do not break between
1020regional indicator (RI) characters if there are an odd number of RI characters
1021before the break point.
1022</P>
1023<P>
10248. Otherwise, end the cluster.
1025<a name="extraprops"></a></P>
1026<br><b>
1027PCRE2's additional properties
1028</b><br>
1029<P>
1030As well as the standard Unicode properties described above, PCRE2 supports four
1031more that make it possible to convert traditional escape sequences such as \w
1032and \s to use Unicode properties. PCRE2 uses these non-standard, non-Perl
1033properties internally when PCRE2_UCP is set. However, they may also be used
1034explicitly. These properties are:
1035<pre>
1036  Xan   Any alphanumeric character
1037  Xps   Any POSIX space character
1038  Xsp   Any Perl space character
1039  Xwd   Any Perl "word" character
1040</pre>
1041Xan matches characters that have either the L (letter) or the N (number)
1042property. Xps matches the characters tab, linefeed, vertical tab, form feed, or
1043carriage return, and any other character that has the Z (separator) property.
1044Xsp is the same as Xps; in PCRE1 it used to exclude vertical tab, for Perl
1045compatibility, but Perl changed. Xwd matches the same characters as Xan, plus
1046underscore.
1047</P>
1048<P>
1049There is another non-standard property, Xuc, which matches any character that
1050can be represented by a Universal Character Name in C++ and other programming
1051languages. These are the characters $, @, ` (grave accent), and all characters
1052with Unicode code points greater than or equal to U+00A0, except for the
1053surrogates U+D800 to U+DFFF. Note that most base (ASCII) characters are
1054excluded. (Universal Character Names are of the form \uHHHH or \UHHHHHHHH
1055where H is a hexadecimal digit. Note that the Xuc property does not match these
1056sequences but the characters that they represent.)
1057<a name="resetmatchstart"></a></P>
1058<br><b>
1059Resetting the match start
1060</b><br>
1061<P>
1062In normal use, the escape sequence \K causes any previously matched characters
1063not to be included in the final matched sequence that is returned. For example,
1064the pattern:
1065<pre>
1066  foo\Kbar
1067</pre>
1068matches "foobar", but reports that it has matched "bar". \K does not interact
1069with anchoring in any way. The pattern:
1070<pre>
1071  ^foo\Kbar
1072</pre>
1073matches only when the subject begins with "foobar" (in single line mode),
1074though it again reports the matched string as "bar". This feature is similar to
1075a lookbehind assertion
1076<a href="#lookbehind">(described below).</a>
1077However, in this case, the part of the subject before the real match does not
1078have to be of fixed length, as lookbehind assertions do. The use of \K does
1079not interfere with the setting of
1080<a href="#group">captured substrings.</a>
1081For example, when the pattern
1082<pre>
1083  (foo)\Kbar
1084</pre>
1085matches "foobar", the first substring is still set to "foo".
1086</P>
1087<P>
1088From version 5.32.0 Perl forbids the use of \K in lookaround assertions. From
1089release 10.38 PCRE2 also forbids this by default. However, the
1090PCRE2_EXTRA_ALLOW_LOOKAROUND_BSK option can be used when calling
1091<b>pcre2_compile()</b> to re-enable the previous behaviour. When this option is
1092set, \K is acted upon when it occurs inside positive assertions, but is
1093ignored in negative assertions. Note that when a pattern such as (?=ab\K)
1094matches, the reported start of the match can be greater than the end of the
1095match. Using \K in a lookbehind assertion at the start of a pattern can also
1096lead to odd effects. For example, consider this pattern:
1097<pre>
1098  (?&#60;=\Kfoo)bar
1099</pre>
1100If the subject is "foobar", a call to <b>pcre2_match()</b> with a starting
1101offset of 3 succeeds and reports the matching string as "foobar", that is, the
1102start of the reported match is earlier than where the match started.
1103<a name="smallassertions"></a></P>
1104<br><b>
1105Simple assertions
1106</b><br>
1107<P>
1108The final use of backslash is for certain simple assertions. An assertion
1109specifies a condition that has to be met at a particular point in a match,
1110without consuming any characters from the subject string. The use of
1111groups for more complicated assertions is described
1112<a href="#bigassertions">below.</a>
1113The backslashed assertions are:
1114<pre>
1115  \b     matches at a word boundary
1116  \B     matches when not at a word boundary
1117  \A     matches at the start of the subject
1118  \Z     matches at the end of the subject
1119          also matches before a newline at the end of the subject
1120  \z     matches only at the end of the subject
1121  \G     matches at the first matching position in the subject
1122</pre>
1123Inside a character class, \b has a different meaning; it matches the backspace
1124character. If any other of these assertions appears in a character class, an
1125"invalid escape sequence" error is generated.
1126</P>
1127<P>
1128A word boundary is a position in the subject string where the current character
1129and the previous character do not both match \w or \W (i.e. one matches
1130\w and the other matches \W), or the start or end of the string if the
1131first or last character matches \w, respectively. When PCRE2 is built with
1132Unicode support, the meanings of \w and \W can be changed by setting the
1133PCRE2_UCP option. When this is done, it also affects \b and \B. Neither PCRE2
1134nor Perl has a separate "start of word" or "end of word" metasequence. However,
1135whatever follows \b normally determines which it is. For example, the fragment
1136\ba matches "a" at the start of a word.
1137</P>
1138<P>
1139The \A, \Z, and \z assertions differ from the traditional circumflex and
1140dollar (described in the next section) in that they only ever match at the very
1141start and end of the subject string, whatever options are set. Thus, they are
1142independent of multiline mode. These three assertions are not affected by the
1143PCRE2_NOTBOL or PCRE2_NOTEOL options, which affect only the behaviour of the
1144circumflex and dollar metacharacters. However, if the <i>startoffset</i>
1145argument of <b>pcre2_match()</b> is non-zero, indicating that matching is to
1146start at a point other than the beginning of the subject, \A can never match.
1147The difference between \Z and \z is that \Z matches before a newline at the
1148end of the string as well as at the very end, whereas \z matches only at the
1149end.
1150</P>
1151<P>
1152The \G assertion is true only when the current matching position is at the
1153start point of the matching process, as specified by the <i>startoffset</i>
1154argument of <b>pcre2_match()</b>. It differs from \A when the value of
1155<i>startoffset</i> is non-zero. By calling <b>pcre2_match()</b> multiple times
1156with appropriate arguments, you can mimic Perl's /g option, and it is in this
1157kind of implementation where \G can be useful.
1158</P>
1159<P>
1160Note, however, that PCRE2's implementation of \G, being true at the starting
1161character of the matching process, is subtly different from Perl's, which
1162defines it as true at the end of the previous match. In Perl, these can be
1163different when the previously matched string was empty. Because PCRE2 does just
1164one match at a time, it cannot reproduce this behaviour.
1165</P>
1166<P>
1167If all the alternatives of a pattern begin with \G, the expression is anchored
1168to the starting match position, and the "anchored" flag is set in the compiled
1169regular expression.
1170</P>
1171<br><a name="SEC6" href="#TOC1">CIRCUMFLEX AND DOLLAR</a><br>
1172<P>
1173The circumflex and dollar metacharacters are zero-width assertions. That is,
1174they test for a particular condition being true without consuming any
1175characters from the subject string. These two metacharacters are concerned with
1176matching the starts and ends of lines. If the newline convention is set so that
1177only the two-character sequence CRLF is recognized as a newline, isolated CR
1178and LF characters are treated as ordinary data characters, and are not
1179recognized as newlines.
1180</P>
1181<P>
1182Outside a character class, in the default matching mode, the circumflex
1183character is an assertion that is true only if the current matching point is at
1184the start of the subject string. If the <i>startoffset</i> argument of
1185<b>pcre2_match()</b> is non-zero, or if PCRE2_NOTBOL is set, circumflex can
1186never match if the PCRE2_MULTILINE option is unset. Inside a character class,
1187circumflex has an entirely different meaning
1188<a href="#characterclass">(see below).</a>
1189</P>
1190<P>
1191Circumflex need not be the first character of the pattern if a number of
1192alternatives are involved, but it should be the first thing in each alternative
1193in which it appears if the pattern is ever to match that branch. If all
1194possible alternatives start with a circumflex, that is, if the pattern is
1195constrained to match only at the start of the subject, it is said to be an
1196"anchored" pattern. (There are also other constructs that can cause a pattern
1197to be anchored.)
1198</P>
1199<P>
1200The dollar character is an assertion that is true only if the current matching
1201point is at the end of the subject string, or immediately before a newline at
1202the end of the string (by default), unless PCRE2_NOTEOL is set. Note, however,
1203that it does not actually match the newline. Dollar need not be the last
1204character of the pattern if a number of alternatives are involved, but it
1205should be the last item in any branch in which it appears. Dollar has no
1206special meaning in a character class.
1207</P>
1208<P>
1209The meaning of dollar can be changed so that it matches only at the very end of
1210the string, by setting the PCRE2_DOLLAR_ENDONLY option at compile time. This
1211does not affect the \Z assertion.
1212</P>
1213<P>
1214The meanings of the circumflex and dollar metacharacters are changed if the
1215PCRE2_MULTILINE option is set. When this is the case, a dollar character
1216matches before any newlines in the string, as well as at the very end, and a
1217circumflex matches immediately after internal newlines as well as at the start
1218of the subject string. It does not match after a newline that ends the string,
1219for compatibility with Perl. However, this can be changed by setting the
1220PCRE2_ALT_CIRCUMFLEX option.
1221</P>
1222<P>
1223For example, the pattern /^abc$/ matches the subject string "def\nabc" (where
1224\n represents a newline) in multiline mode, but not otherwise. Consequently,
1225patterns that are anchored in single line mode because all branches start with
1226^ are not anchored in multiline mode, and a match for circumflex is possible
1227when the <i>startoffset</i> argument of <b>pcre2_match()</b> is non-zero. The
1228PCRE2_DOLLAR_ENDONLY option is ignored if PCRE2_MULTILINE is set.
1229</P>
1230<P>
1231When the newline convention (see
1232<a href="#newlines">"Newline conventions"</a>
1233below) recognizes the two-character sequence CRLF as a newline, this is
1234preferred, even if the single characters CR and LF are also recognized as
1235newlines. For example, if the newline convention is "any", a multiline mode
1236circumflex matches before "xyz" in the string "abc\r\nxyz" rather than after
1237CR, even though CR on its own is a valid newline. (It also matches at the very
1238start of the string, of course.)
1239</P>
1240<P>
1241Note that the sequences \A, \Z, and \z can be used to match the start and
1242end of the subject in both modes, and if all branches of a pattern start with
1243\A it is always anchored, whether or not PCRE2_MULTILINE is set.
1244<a name="fullstopdot"></a></P>
1245<br><a name="SEC7" href="#TOC1">FULL STOP (PERIOD, DOT) AND \N</a><br>
1246<P>
1247Outside a character class, a dot in the pattern matches any one character in
1248the subject string except (by default) a character that signifies the end of a
1249line. One or more characters may be specified as line terminators (see
1250<a href="#newlines">"Newline conventions"</a>
1251above).
1252</P>
1253<P>
1254Dot never matches a single line-ending character. When the two-character
1255sequence CRLF is the only line ending, dot does not match CR if it is
1256immediately followed by LF, but otherwise it matches all characters (including
1257isolated CRs and LFs). When ANYCRLF is selected for line endings, no occurences
1258of CR of LF match dot. When all Unicode line endings are being recognized, dot
1259does not match CR or LF or any of the other line ending characters.
1260</P>
1261<P>
1262The behaviour of dot with regard to newlines can be changed. If the
1263PCRE2_DOTALL option is set, a dot matches any one character, without exception.
1264If the two-character sequence CRLF is present in the subject string, it takes
1265two dots to match it.
1266</P>
1267<P>
1268The handling of dot is entirely independent of the handling of circumflex and
1269dollar, the only relationship being that they both involve newlines. Dot has no
1270special meaning in a character class.
1271</P>
1272<P>
1273The escape sequence \N when not followed by an opening brace behaves like a
1274dot, except that it is not affected by the PCRE2_DOTALL option. In other words,
1275it matches any character except one that signifies the end of a line.
1276</P>
1277<P>
1278When \N is followed by an opening brace it has a different meaning. See the
1279section entitled
1280<a href="digitsafterbackslash">"Non-printing characters"</a>
1281above for details. Perl also uses \N{name} to specify characters by Unicode
1282name; PCRE2 does not support this.
1283</P>
1284<br><a name="SEC8" href="#TOC1">MATCHING A SINGLE CODE UNIT</a><br>
1285<P>
1286Outside a character class, the escape sequence \C matches any one code unit,
1287whether or not a UTF mode is set. In the 8-bit library, one code unit is one
1288byte; in the 16-bit library it is a 16-bit unit; in the 32-bit library it is a
128932-bit unit. Unlike a dot, \C always matches line-ending characters. The
1290feature is provided in Perl in order to match individual bytes in UTF-8 mode,
1291but it is unclear how it can usefully be used.
1292</P>
1293<P>
1294Because \C breaks up characters into individual code units, matching one unit
1295with \C in UTF-8 or UTF-16 mode means that the rest of the string may start
1296with a malformed UTF character. This has undefined results, because PCRE2
1297assumes that it is matching character by character in a valid UTF string (by
1298default it checks the subject string's validity at the start of processing
1299unless the PCRE2_NO_UTF_CHECK or PCRE2_MATCH_INVALID_UTF option is used).
1300</P>
1301<P>
1302An application can lock out the use of \C by setting the
1303PCRE2_NEVER_BACKSLASH_C option when compiling a pattern. It is also possible to
1304build PCRE2 with the use of \C permanently disabled.
1305</P>
1306<P>
1307PCRE2 does not allow \C to appear in lookbehind assertions
1308<a href="#lookbehind">(described below)</a>
1309in UTF-8 or UTF-16 modes, because this would make it impossible to calculate
1310the length of the lookbehind. Neither the alternative matching function
1311<b>pcre2_dfa_match()</b> nor the JIT optimizer support \C in these UTF modes.
1312The former gives a match-time error; the latter fails to optimize and so the
1313match is always run using the interpreter.
1314</P>
1315<P>
1316In the 32-bit library, however, \C is always supported (when not explicitly
1317locked out) because it always matches a single code unit, whether or not UTF-32
1318is specified.
1319</P>
1320<P>
1321In general, the \C escape sequence is best avoided. However, one way of using
1322it that avoids the problem of malformed UTF-8 or UTF-16 characters is to use a
1323lookahead to check the length of the next character, as in this pattern, which
1324could be used with a UTF-8 string (ignore white space and line breaks):
1325<pre>
1326  (?| (?=[\x00-\x7f])(\C) |
1327      (?=[\x80-\x{7ff}])(\C)(\C) |
1328      (?=[\x{800}-\x{ffff}])(\C)(\C)(\C) |
1329      (?=[\x{10000}-\x{1fffff}])(\C)(\C)(\C)(\C))
1330</pre>
1331In this example, a group that starts with (?| resets the capturing parentheses
1332numbers in each alternative (see
1333<a href="#dupgroupnumber">"Duplicate Group Numbers"</a>
1334below). The assertions at the start of each branch check the next UTF-8
1335character for values whose encoding uses 1, 2, 3, or 4 bytes, respectively. The
1336character's individual bytes are then captured by the appropriate number of
1337\C groups.
1338<a name="characterclass"></a></P>
1339<br><a name="SEC9" href="#TOC1">SQUARE BRACKETS AND CHARACTER CLASSES</a><br>
1340<P>
1341An opening square bracket introduces a character class, terminated by a closing
1342square bracket. A closing square bracket on its own is not special by default.
1343If a closing square bracket is required as a member of the class, it should be
1344the first data character in the class (after an initial circumflex, if present)
1345or escaped with a backslash. This means that, by default, an empty class cannot
1346be defined. However, if the PCRE2_ALLOW_EMPTY_CLASS option is set, a closing
1347square bracket at the start does end the (empty) class.
1348</P>
1349<P>
1350A character class matches a single character in the subject. A matched
1351character must be in the set of characters defined by the class, unless the
1352first character in the class definition is a circumflex, in which case the
1353subject character must not be in the set defined by the class. If a circumflex
1354is actually required as a member of the class, ensure it is not the first
1355character, or escape it with a backslash.
1356</P>
1357<P>
1358For example, the character class [aeiou] matches any lower case vowel, while
1359[^aeiou] matches any character that is not a lower case vowel. Note that a
1360circumflex is just a convenient notation for specifying the characters that
1361are in the class by enumerating those that are not. A class that starts with a
1362circumflex is not an assertion; it still consumes a character from the subject
1363string, and therefore it fails if the current pointer is at the end of the
1364string.
1365</P>
1366<P>
1367Characters in a class may be specified by their code points using \o, \x, or
1368\N{U+hh..} in the usual way. When caseless matching is set, any letters in a
1369class represent both their upper case and lower case versions, so for example,
1370a caseless [aeiou] matches "A" as well as "a", and a caseless [^aeiou] does not
1371match "A", whereas a caseful version would. Note that there are two ASCII
1372characters, K and S, that, in addition to their lower case ASCII equivalents,
1373are case-equivalent with Unicode U+212A (Kelvin sign) and U+017F (long S)
1374respectively when either PCRE2_UTF or PCRE2_UCP is set.
1375</P>
1376<P>
1377Characters that might indicate line breaks are never treated in any special way
1378when matching character classes, whatever line-ending sequence is in use, and
1379whatever setting of the PCRE2_DOTALL and PCRE2_MULTILINE options is used. A
1380class such as [^a] always matches one of these characters.
1381</P>
1382<P>
1383The generic character type escape sequences \d, \D, \h, \H, \p, \P, \s,
1384\S, \v, \V, \w, and \W may appear in a character class, and add the
1385characters that they match to the class. For example, [\dABCDEF] matches any
1386hexadecimal digit. In UTF modes, the PCRE2_UCP option affects the meanings of
1387\d, \s, \w and their upper case partners, just as it does when they appear
1388outside a character class, as described in the section entitled
1389<a href="#genericchartypes">"Generic character types"</a>
1390above. The escape sequence \b has a different meaning inside a character
1391class; it matches the backspace character. The sequences \B, \R, and \X are
1392not special inside a character class. Like any other unrecognized escape
1393sequences, they cause an error. The same is true for \N when not followed by
1394an opening brace.
1395</P>
1396<P>
1397The minus (hyphen) character can be used to specify a range of characters in a
1398character class. For example, [d-m] matches any letter between d and m,
1399inclusive. If a minus character is required in a class, it must be escaped with
1400a backslash or appear in a position where it cannot be interpreted as
1401indicating a range, typically as the first or last character in the class,
1402or immediately after a range. For example, [b-d-z] matches letters in the range
1403b to d, a hyphen character, or z.
1404</P>
1405<P>
1406Perl treats a hyphen as a literal if it appears before or after a POSIX class
1407(see below) or before or after a character type escape such as as \d or \H.
1408However, unless the hyphen is the last character in the class, Perl outputs a
1409warning in its warning mode, as this is most likely a user error. As PCRE2 has
1410no facility for warning, an error is given in these cases.
1411</P>
1412<P>
1413It is not possible to have the literal character "]" as the end character of a
1414range. A pattern such as [W-]46] is interpreted as a class of two characters
1415("W" and "-") followed by a literal string "46]", so it would match "W46]" or
1416"-46]". However, if the "]" is escaped with a backslash it is interpreted as
1417the end of range, so [W-\]46] is interpreted as a class containing a range
1418followed by two other characters. The octal or hexadecimal representation of
1419"]" can also be used to end a range.
1420</P>
1421<P>
1422Ranges normally include all code points between the start and end characters,
1423inclusive. They can also be used for code points specified numerically, for
1424example [\000-\037]. Ranges can include any characters that are valid for the
1425current mode. In any UTF mode, the so-called "surrogate" characters (those
1426whose code points lie between 0xd800 and 0xdfff inclusive) may not be specified
1427explicitly by default (the PCRE2_EXTRA_ALLOW_SURROGATE_ESCAPES option disables
1428this check). However, ranges such as [\x{d7ff}-\x{e000}], which include the
1429surrogates, are always permitted.
1430</P>
1431<P>
1432There is a special case in EBCDIC environments for ranges whose end points are
1433both specified as literal letters in the same case. For compatibility with
1434Perl, EBCDIC code points within the range that are not letters are omitted. For
1435example, [h-k] matches only four characters, even though the codes for h and k
1436are 0x88 and 0x92, a range of 11 code points. However, if the range is
1437specified numerically, for example, [\x88-\x92] or [h-\x92], all code points
1438are included.
1439</P>
1440<P>
1441If a range that includes letters is used when caseless matching is set, it
1442matches the letters in either case. For example, [W-c] is equivalent to
1443[][\\^_`wxyzabc], matched caselessly, and in a non-UTF mode, if character
1444tables for a French locale are in use, [\xc8-\xcb] matches accented E
1445characters in both cases.
1446</P>
1447<P>
1448A circumflex can conveniently be used with the upper case character types to
1449specify a more restricted set of characters than the matching lower case type.
1450For example, the class [^\W_] matches any letter or digit, but not underscore,
1451whereas [\w] includes underscore. A positive character class should be read as
1452"something OR something OR ..." and a negative class as "NOT something AND NOT
1453something AND NOT ...".
1454</P>
1455<P>
1456The only metacharacters that are recognized in character classes are backslash,
1457hyphen (only where it can be interpreted as specifying a range), circumflex
1458(only at the start), opening square bracket (only when it can be interpreted as
1459introducing a POSIX class name, or for a special compatibility feature - see
1460the next two sections), and the terminating closing square bracket. However,
1461escaping other non-alphanumeric characters does no harm.
1462</P>
1463<br><a name="SEC10" href="#TOC1">POSIX CHARACTER CLASSES</a><br>
1464<P>
1465Perl supports the POSIX notation for character classes. This uses names
1466enclosed by [: and :] within the enclosing square brackets. PCRE2 also supports
1467this notation. For example,
1468<pre>
1469  [01[:alpha:]%]
1470</pre>
1471matches "0", "1", any alphabetic character, or "%". The supported class names
1472are:
1473<pre>
1474  alnum    letters and digits
1475  alpha    letters
1476  ascii    character codes 0 - 127
1477  blank    space or tab only
1478  cntrl    control characters
1479  digit    decimal digits (same as \d)
1480  graph    printing characters, excluding space
1481  lower    lower case letters
1482  print    printing characters, including space
1483  punct    printing characters, excluding letters and digits and space
1484  space    white space (the same as \s from PCRE2 8.34)
1485  upper    upper case letters
1486  word     "word" characters (same as \w)
1487  xdigit   hexadecimal digits
1488</pre>
1489The default "space" characters are HT (9), LF (10), VT (11), FF (12), CR (13),
1490and space (32). If locale-specific matching is taking place, the list of space
1491characters may be different; there may be fewer or more of them. "Space" and
1492\s match the same set of characters.
1493</P>
1494<P>
1495The name "word" is a Perl extension, and "blank" is a GNU extension from Perl
14965.8. Another Perl extension is negation, which is indicated by a ^ character
1497after the colon. For example,
1498<pre>
1499  [12[:^digit:]]
1500</pre>
1501matches "1", "2", or any non-digit. PCRE2 (and Perl) also recognize the POSIX
1502syntax [.ch.] and [=ch=] where "ch" is a "collating element", but these are not
1503supported, and an error is given if they are encountered.
1504</P>
1505<P>
1506By default, characters with values greater than 127 do not match any of the
1507POSIX character classes, although this may be different for characters in the
1508range 128-255 when locale-specific matching is happening. However, if the
1509PCRE2_UCP option is passed to <b>pcre2_compile()</b>, some of the classes are
1510changed so that Unicode character properties are used. This is achieved by
1511replacing certain POSIX classes with other sequences, as follows:
1512<pre>
1513  [:alnum:]  becomes  \p{Xan}
1514  [:alpha:]  becomes  \p{L}
1515  [:blank:]  becomes  \h
1516  [:cntrl:]  becomes  \p{Cc}
1517  [:digit:]  becomes  \p{Nd}
1518  [:lower:]  becomes  \p{Ll}
1519  [:space:]  becomes  \p{Xps}
1520  [:upper:]  becomes  \p{Lu}
1521  [:word:]   becomes  \p{Xwd}
1522</pre>
1523Negated versions, such as [:^alpha:] use \P instead of \p. Three other POSIX
1524classes are handled specially in UCP mode:
1525</P>
1526<P>
1527[:graph:]
1528This matches characters that have glyphs that mark the page when printed. In
1529Unicode property terms, it matches all characters with the L, M, N, P, S, or Cf
1530properties, except for:
1531<pre>
1532  U+061C           Arabic Letter Mark
1533  U+180E           Mongolian Vowel Separator
1534  U+2066 - U+2069  Various "isolate"s
1535
1536</PRE>
1537</P>
1538<P>
1539[:print:]
1540This matches the same characters as [:graph:] plus space characters that are
1541not controls, that is, characters with the Zs property.
1542</P>
1543<P>
1544[:punct:]
1545This matches all characters that have the Unicode P (punctuation) property,
1546plus those characters with code points less than 256 that have the S (Symbol)
1547property.
1548</P>
1549<P>
1550The other POSIX classes are unchanged, and match only characters with code
1551points less than 256.
1552</P>
1553<br><a name="SEC11" href="#TOC1">COMPATIBILITY FEATURE FOR WORD BOUNDARIES</a><br>
1554<P>
1555In the POSIX.2 compliant library that was included in 4.4BSD Unix, the ugly
1556syntax [[:&#60;:]] and [[:&#62;:]] is used for matching "start of word" and "end of
1557word". PCRE2 treats these items as follows:
1558<pre>
1559  [[:&#60;:]]  is converted to  \b(?=\w)
1560  [[:&#62;:]]  is converted to  \b(?&#60;=\w)
1561</pre>
1562Only these exact character sequences are recognized. A sequence such as
1563[a[:&#60;:]b] provokes error for an unrecognized POSIX class name. This support is
1564not compatible with Perl. It is provided to help migrations from other
1565environments, and is best not used in any new patterns. Note that \b matches
1566at the start and the end of a word (see
1567<a href="#smallassertions">"Simple assertions"</a>
1568above), and in a Perl-style pattern the preceding or following character
1569normally shows which is wanted, without the need for the assertions that are
1570used above in order to give exactly the POSIX behaviour.
1571</P>
1572<br><a name="SEC12" href="#TOC1">VERTICAL BAR</a><br>
1573<P>
1574Vertical bar characters are used to separate alternative patterns. For example,
1575the pattern
1576<pre>
1577  gilbert|sullivan
1578</pre>
1579matches either "gilbert" or "sullivan". Any number of alternatives may appear,
1580and an empty alternative is permitted (matching the empty string). The matching
1581process tries each alternative in turn, from left to right, and the first one
1582that succeeds is used. If the alternatives are within a group
1583<a href="#group">(defined below),</a>
1584"succeeds" means matching the rest of the main pattern as well as the
1585alternative in the group.
1586<a name="internaloptions"></a></P>
1587<br><a name="SEC13" href="#TOC1">INTERNAL OPTION SETTING</a><br>
1588<P>
1589The settings of the PCRE2_CASELESS, PCRE2_MULTILINE, PCRE2_DOTALL,
1590PCRE2_EXTENDED, PCRE2_EXTENDED_MORE, and PCRE2_NO_AUTO_CAPTURE options can be
1591changed from within the pattern by a sequence of letters enclosed between "(?"
1592and ")". These options are Perl-compatible, and are described in detail in the
1593<a href="pcre2api.html"><b>pcre2api</b></a>
1594documentation. The option letters are:
1595<pre>
1596  i  for PCRE2_CASELESS
1597  m  for PCRE2_MULTILINE
1598  n  for PCRE2_NO_AUTO_CAPTURE
1599  s  for PCRE2_DOTALL
1600  x  for PCRE2_EXTENDED
1601  xx for PCRE2_EXTENDED_MORE
1602</pre>
1603For example, (?im) sets caseless, multiline matching. It is also possible to
1604unset these options by preceding the relevant letters with a hyphen, for
1605example (?-im). The two "extended" options are not independent; unsetting either
1606one cancels the effects of both of them.
1607</P>
1608<P>
1609A combined setting and unsetting such as (?im-sx), which sets PCRE2_CASELESS
1610and PCRE2_MULTILINE while unsetting PCRE2_DOTALL and PCRE2_EXTENDED, is also
1611permitted. Only one hyphen may appear in the options string. If a letter
1612appears both before and after the hyphen, the option is unset. An empty options
1613setting "(?)" is allowed. Needless to say, it has no effect.
1614</P>
1615<P>
1616If the first character following (? is a circumflex, it causes all of the above
1617options to be unset. Thus, (?^) is equivalent to (?-imnsx). Letters may follow
1618the circumflex to cause some options to be re-instated, but a hyphen may not
1619appear.
1620</P>
1621<P>
1622The PCRE2-specific options PCRE2_DUPNAMES and PCRE2_UNGREEDY can be changed in
1623the same way as the Perl-compatible options by using the characters J and U
1624respectively. However, these are not unset by (?^).
1625</P>
1626<P>
1627When one of these option changes occurs at top level (that is, not inside
1628group parentheses), the change applies to the remainder of the pattern
1629that follows. An option change within a group (see below for a description
1630of groups) affects only that part of the group that follows it, so
1631<pre>
1632  (a(?i)b)c
1633</pre>
1634matches abc and aBc and no other strings (assuming PCRE2_CASELESS is not used).
1635By this means, options can be made to have different settings in different
1636parts of the pattern. Any changes made in one alternative do carry on
1637into subsequent branches within the same group. For example,
1638<pre>
1639  (a(?i)b|c)
1640</pre>
1641matches "ab", "aB", "c", and "C", even though when matching "C" the first
1642branch is abandoned before the option setting. This is because the effects of
1643option settings happen at compile time. There would be some very weird
1644behaviour otherwise.
1645</P>
1646<P>
1647As a convenient shorthand, if any option settings are required at the start of
1648a non-capturing group (see the next section), the option letters may
1649appear between the "?" and the ":". Thus the two patterns
1650<pre>
1651  (?i:saturday|sunday)
1652  (?:(?i)saturday|sunday)
1653</pre>
1654match exactly the same set of strings.
1655</P>
1656<P>
1657<b>Note:</b> There are other PCRE2-specific options, applying to the whole
1658pattern, which can be set by the application when the compiling function is
1659called. In addition, the pattern can contain special leading sequences such as
1660(*CRLF) to override what the application has set or what has been defaulted.
1661Details are given in the section entitled
1662<a href="#newlineseq">"Newline sequences"</a>
1663above. There are also the (*UTF) and (*UCP) leading sequences that can be used
1664to set UTF and Unicode property modes; they are equivalent to setting the
1665PCRE2_UTF and PCRE2_UCP options, respectively. However, the application can set
1666the PCRE2_NEVER_UTF and PCRE2_NEVER_UCP options, which lock out the use of the
1667(*UTF) and (*UCP) sequences.
1668<a name="group"></a></P>
1669<br><a name="SEC14" href="#TOC1">GROUPS</a><br>
1670<P>
1671Groups are delimited by parentheses (round brackets), which can be nested.
1672Turning part of a pattern into a group does two things:
1673<br>
1674<br>
16751. It localizes a set of alternatives. For example, the pattern
1676<pre>
1677  cat(aract|erpillar|)
1678</pre>
1679matches "cataract", "caterpillar", or "cat". Without the parentheses, it would
1680match "cataract", "erpillar" or an empty string.
1681<br>
1682<br>
16832. It creates a "capture group". This means that, when the whole pattern
1684matches, the portion of the subject string that matched the group is passed
1685back to the caller, separately from the portion that matched the whole pattern.
1686(This applies only to the traditional matching function; the DFA matching
1687function does not support capturing.)
1688</P>
1689<P>
1690Opening parentheses are counted from left to right (starting from 1) to obtain
1691numbers for capture groups. For example, if the string "the red king" is
1692matched against the pattern
1693<pre>
1694  the ((red|white) (king|queen))
1695</pre>
1696the captured substrings are "red king", "red", and "king", and are numbered 1,
16972, and 3, respectively.
1698</P>
1699<P>
1700The fact that plain parentheses fulfil two functions is not always helpful.
1701There are often times when grouping is required without capturing. If an
1702opening parenthesis is followed by a question mark and a colon, the group
1703does not do any capturing, and is not counted when computing the number of any
1704subsequent capture groups. For example, if the string "the white queen"
1705is matched against the pattern
1706<pre>
1707  the ((?:red|white) (king|queen))
1708</pre>
1709the captured substrings are "white queen" and "queen", and are numbered 1 and
17102. The maximum number of capture groups is 65535.
1711</P>
1712<P>
1713As a convenient shorthand, if any option settings are required at the start of
1714a non-capturing group, the option letters may appear between the "?" and the
1715":". Thus the two patterns
1716<pre>
1717  (?i:saturday|sunday)
1718  (?:(?i)saturday|sunday)
1719</pre>
1720match exactly the same set of strings. Because alternative branches are tried
1721from left to right, and options are not reset until the end of the group is
1722reached, an option setting in one branch does affect subsequent branches, so
1723the above patterns match "SUNDAY" as well as "Saturday".
1724<a name="dupgroupnumber"></a></P>
1725<br><a name="SEC15" href="#TOC1">DUPLICATE GROUP NUMBERS</a><br>
1726<P>
1727Perl 5.10 introduced a feature whereby each alternative in a group uses the
1728same numbers for its capturing parentheses. Such a group starts with (?| and is
1729itself a non-capturing group. For example, consider this pattern:
1730<pre>
1731  (?|(Sat)ur|(Sun))day
1732</pre>
1733Because the two alternatives are inside a (?| group, both sets of capturing
1734parentheses are numbered one. Thus, when the pattern matches, you can look
1735at captured substring number one, whichever alternative matched. This construct
1736is useful when you want to capture part, but not all, of one of a number of
1737alternatives. Inside a (?| group, parentheses are numbered as usual, but the
1738number is reset at the start of each branch. The numbers of any capturing
1739parentheses that follow the whole group start after the highest number used in
1740any branch. The following example is taken from the Perl documentation. The
1741numbers underneath show in which buffer the captured content will be stored.
1742<pre>
1743  # before  ---------------branch-reset----------- after
1744  / ( a )  (?| x ( y ) z | (p (q) r) | (t) u (v) ) ( z ) /x
1745  # 1            2         2  3        2     3     4
1746</pre>
1747A backreference to a capture group uses the most recent value that is set for
1748the group. The following pattern matches "abcabc" or "defdef":
1749<pre>
1750  /(?|(abc)|(def))\1/
1751</pre>
1752In contrast, a subroutine call to a capture group always refers to the
1753first one in the pattern with the given number. The following pattern matches
1754"abcabc" or "defabc":
1755<pre>
1756  /(?|(abc)|(def))(?1)/
1757</pre>
1758A relative reference such as (?-1) is no different: it is just a convenient way
1759of computing an absolute group number.
1760</P>
1761<P>
1762If a
1763<a href="#conditions">condition test</a>
1764for a group's having matched refers to a non-unique number, the test is
1765true if any group with that number has matched.
1766</P>
1767<P>
1768An alternative approach to using this "branch reset" feature is to use
1769duplicate named groups, as described in the next section.
1770</P>
1771<br><a name="SEC16" href="#TOC1">NAMED CAPTURE GROUPS</a><br>
1772<P>
1773Identifying capture groups by number is simple, but it can be very hard to keep
1774track of the numbers in complicated patterns. Furthermore, if an expression is
1775modified, the numbers may change. To help with this difficulty, PCRE2 supports
1776the naming of capture groups. This feature was not added to Perl until release
17775.10. Python had the feature earlier, and PCRE1 introduced it at release 4.0,
1778using the Python syntax. PCRE2 supports both the Perl and the Python syntax.
1779</P>
1780<P>
1781In PCRE2, a capture group can be named in one of three ways: (?&#60;name&#62;...) or
1782(?'name'...) as in Perl, or (?P&#60;name&#62;...) as in Python. Names may be up to 32
1783code units long. When PCRE2_UTF is not set, they may contain only ASCII
1784alphanumeric characters and underscores, but must start with a non-digit. When
1785PCRE2_UTF is set, the syntax of group names is extended to allow any Unicode
1786letter or Unicode decimal digit. In other words, group names must match one of
1787these patterns:
1788<pre>
1789  ^[_A-Za-z][_A-Za-z0-9]*\z   when PCRE2_UTF is not set
1790  ^[_\p{L}][_\p{L}\p{Nd}]*\z  when PCRE2_UTF is set
1791</pre>
1792References to capture groups from other parts of the pattern, such as
1793<a href="#backreferences">backreferences,</a>
1794<a href="#recursion">recursion,</a>
1795and
1796<a href="#conditions">conditions,</a>
1797can all be made by name as well as by number.
1798</P>
1799<P>
1800Named capture groups are allocated numbers as well as names, exactly as
1801if the names were not present. In both PCRE2 and Perl, capture groups
1802are primarily identified by numbers; any names are just aliases for these
1803numbers. The PCRE2 API provides function calls for extracting the complete
1804name-to-number translation table from a compiled pattern, as well as
1805convenience functions for extracting captured substrings by name.
1806</P>
1807<P>
1808<b>Warning:</b> When more than one capture group has the same number, as
1809described in the previous section, a name given to one of them applies to all
1810of them. Perl allows identically numbered groups to have different names.
1811Consider this pattern, where there are two capture groups, both numbered 1:
1812<pre>
1813  (?|(?&#60;AA&#62;aa)|(?&#60;BB&#62;bb))
1814</pre>
1815Perl allows this, with both names AA and BB as aliases of group 1. Thus, after
1816a successful match, both names yield the same value (either "aa" or "bb").
1817</P>
1818<P>
1819In an attempt to reduce confusion, PCRE2 does not allow the same group number
1820to be associated with more than one name. The example above provokes a
1821compile-time error. However, there is still scope for confusion. Consider this
1822pattern:
1823<pre>
1824  (?|(?&#60;AA&#62;aa)|(bb))
1825</pre>
1826Although the second group number 1 is not explicitly named, the name AA is
1827still an alias for any group 1. Whether the pattern matches "aa" or "bb", a
1828reference by name to group AA yields the matched string.
1829</P>
1830<P>
1831By default, a name must be unique within a pattern, except that duplicate names
1832are permitted for groups with the same number, for example:
1833<pre>
1834  (?|(?&#60;AA&#62;aa)|(?&#60;AA&#62;bb))
1835</pre>
1836The duplicate name constraint can be disabled by setting the PCRE2_DUPNAMES
1837option at compile time, or by the use of (?J) within the pattern, as described
1838in the section entitled
1839<a href="#internaloptions">"Internal Option Setting"</a>
1840above.
1841</P>
1842<P>
1843Duplicate names can be useful for patterns where only one instance of the named
1844capture group can match. Suppose you want to match the name of a weekday,
1845either as a 3-letter abbreviation or as the full name, and in both cases you
1846want to extract the abbreviation. This pattern (ignoring the line breaks) does
1847the job:
1848<pre>
1849  (?J)
1850  (?&#60;DN&#62;Mon|Fri|Sun)(?:day)?|
1851  (?&#60;DN&#62;Tue)(?:sday)?|
1852  (?&#60;DN&#62;Wed)(?:nesday)?|
1853  (?&#60;DN&#62;Thu)(?:rsday)?|
1854  (?&#60;DN&#62;Sat)(?:urday)?
1855</pre>
1856There are five capture groups, but only one is ever set after a match. The
1857convenience functions for extracting the data by name returns the substring for
1858the first (and in this example, the only) group of that name that matched. This
1859saves searching to find which numbered group it was. (An alternative way of
1860solving this problem is to use a "branch reset" group, as described in the
1861previous section.)
1862</P>
1863<P>
1864If you make a backreference to a non-unique named group from elsewhere in the
1865pattern, the groups to which the name refers are checked in the order in which
1866they appear in the overall pattern. The first one that is set is used for the
1867reference. For example, this pattern matches both "foofoo" and "barbar" but not
1868"foobar" or "barfoo":
1869<pre>
1870  (?J)(?:(?&#60;n&#62;foo)|(?&#60;n&#62;bar))\k&#60;n&#62;
1871
1872</PRE>
1873</P>
1874<P>
1875If you make a subroutine call to a non-unique named group, the one that
1876corresponds to the first occurrence of the name is used. In the absence of
1877duplicate numbers this is the one with the lowest number.
1878</P>
1879<P>
1880If you use a named reference in a condition
1881test (see the
1882<a href="#conditions">section about conditions</a>
1883below), either to check whether a capture group has matched, or to check for
1884recursion, all groups with the same name are tested. If the condition is true
1885for any one of them, the overall condition is true. This is the same behaviour
1886as testing by number. For further details of the interfaces for handling named
1887capture groups, see the
1888<a href="pcre2api.html"><b>pcre2api</b></a>
1889documentation.
1890</P>
1891<br><a name="SEC17" href="#TOC1">REPETITION</a><br>
1892<P>
1893Repetition is specified by quantifiers, which can follow any of the following
1894items:
1895<pre>
1896  a literal data character
1897  the dot metacharacter
1898  the \C escape sequence
1899  the \R escape sequence
1900  the \X escape sequence
1901  an escape such as \d or \pL that matches a single character
1902  a character class
1903  a backreference
1904  a parenthesized group (including lookaround assertions)
1905  a subroutine call (recursive or otherwise)
1906</pre>
1907The general repetition quantifier specifies a minimum and maximum number of
1908permitted matches, by giving the two numbers in curly brackets (braces),
1909separated by a comma. The numbers must be less than 65536, and the first must
1910be less than or equal to the second. For example,
1911<pre>
1912  z{2,4}
1913</pre>
1914matches "zz", "zzz", or "zzzz". A closing brace on its own is not a special
1915character. If the second number is omitted, but the comma is present, there is
1916no upper limit; if the second number and the comma are both omitted, the
1917quantifier specifies an exact number of required matches. Thus
1918<pre>
1919  [aeiou]{3,}
1920</pre>
1921matches at least 3 successive vowels, but may match many more, whereas
1922<pre>
1923  \d{8}
1924</pre>
1925matches exactly 8 digits. An opening curly bracket that appears in a position
1926where a quantifier is not allowed, or one that does not match the syntax of a
1927quantifier, is taken as a literal character. For example, {,6} is not a
1928quantifier, but a literal string of four characters.
1929</P>
1930<P>
1931In UTF modes, quantifiers apply to characters rather than to individual code
1932units. Thus, for example, \x{100}{2} matches two characters, each of
1933which is represented by a two-byte sequence in a UTF-8 string. Similarly,
1934\X{3} matches three Unicode extended grapheme clusters, each of which may be
1935several code units long (and they may be of different lengths).
1936</P>
1937<P>
1938The quantifier {0} is permitted, causing the expression to behave as if the
1939previous item and the quantifier were not present. This may be useful for
1940capture groups that are referenced as
1941<a href="#groupsassubroutines">subroutines</a>
1942from elsewhere in the pattern (but see also the section entitled
1943<a href="#subdefine">"Defining capture groups for use by reference only"</a>
1944below). Except for parenthesized groups, items that have a {0} quantifier are
1945omitted from the compiled pattern.
1946</P>
1947<P>
1948For convenience, the three most common quantifiers have single-character
1949abbreviations:
1950<pre>
1951  *    is equivalent to {0,}
1952  +    is equivalent to {1,}
1953  ?    is equivalent to {0,1}
1954</pre>
1955It is possible to construct infinite loops by following a group that can match
1956no characters with a quantifier that has no upper limit, for example:
1957<pre>
1958  (a?)*
1959</pre>
1960Earlier versions of Perl and PCRE1 used to give an error at compile time for
1961such patterns. However, because there are cases where this can be useful, such
1962patterns are now accepted, but whenever an iteration of such a group matches no
1963characters, matching moves on to the next item in the pattern instead of
1964repeatedly matching an empty string. This does not prevent backtracking into
1965any of the iterations if a subsequent item fails to match.
1966</P>
1967<P>
1968By default, quantifiers are "greedy", that is, they match as much as possible
1969(up to the maximum number of permitted times), without causing the rest of the
1970pattern to fail. The classic example of where this gives problems is in trying
1971to match comments in C programs. These appear between /* and */ and within the
1972comment, individual * and / characters may appear. An attempt to match C
1973comments by applying the pattern
1974<pre>
1975  /\*.*\*/
1976</pre>
1977to the string
1978<pre>
1979  /* first comment */  not comment  /* second comment */
1980</pre>
1981fails, because it matches the entire string owing to the greediness of the .*
1982item. However, if a quantifier is followed by a question mark, it ceases to be
1983greedy, and instead matches the minimum number of times possible, so the
1984pattern
1985<pre>
1986  /\*.*?\*/
1987</pre>
1988does the right thing with the C comments. The meaning of the various
1989quantifiers is not otherwise changed, just the preferred number of matches.
1990Do not confuse this use of question mark with its use as a quantifier in its
1991own right. Because it has two uses, it can sometimes appear doubled, as in
1992<pre>
1993  \d??\d
1994</pre>
1995which matches one digit by preference, but can match two if that is the only
1996way the rest of the pattern matches.
1997</P>
1998<P>
1999If the PCRE2_UNGREEDY option is set (an option that is not available in Perl),
2000the quantifiers are not greedy by default, but individual ones can be made
2001greedy by following them with a question mark. In other words, it inverts the
2002default behaviour.
2003</P>
2004<P>
2005When a parenthesized group is quantified with a minimum repeat count that
2006is greater than 1 or with a limited maximum, more memory is required for the
2007compiled pattern, in proportion to the size of the minimum or maximum.
2008</P>
2009<P>
2010If a pattern starts with .* or .{0,} and the PCRE2_DOTALL option (equivalent
2011to Perl's /s) is set, thus allowing the dot to match newlines, the pattern is
2012implicitly anchored, because whatever follows will be tried against every
2013character position in the subject string, so there is no point in retrying the
2014overall match at any position after the first. PCRE2 normally treats such a
2015pattern as though it were preceded by \A.
2016</P>
2017<P>
2018In cases where it is known that the subject string contains no newlines, it is
2019worth setting PCRE2_DOTALL in order to obtain this optimization, or
2020alternatively, using ^ to indicate anchoring explicitly.
2021</P>
2022<P>
2023However, there are some cases where the optimization cannot be used. When .*
2024is inside capturing parentheses that are the subject of a backreference
2025elsewhere in the pattern, a match at the start may fail where a later one
2026succeeds. Consider, for example:
2027<pre>
2028  (.*)abc\1
2029</pre>
2030If the subject is "xyz123abc123" the match point is the fourth character. For
2031this reason, such a pattern is not implicitly anchored.
2032</P>
2033<P>
2034Another case where implicit anchoring is not applied is when the leading .* is
2035inside an atomic group. Once again, a match at the start may fail where a later
2036one succeeds. Consider this pattern:
2037<pre>
2038  (?&#62;.*?a)b
2039</pre>
2040It matches "ab" in the subject "aab". The use of the backtracking control verbs
2041(*PRUNE) and (*SKIP) also disable this optimization, and there is an option,
2042PCRE2_NO_DOTSTAR_ANCHOR, to do so explicitly.
2043</P>
2044<P>
2045When a capture group is repeated, the value captured is the substring that
2046matched the final iteration. For example, after
2047<pre>
2048  (tweedle[dume]{3}\s*)+
2049</pre>
2050has matched "tweedledum tweedledee" the value of the captured substring is
2051"tweedledee". However, if there are nested capture groups, the corresponding
2052captured values may have been set in previous iterations. For example, after
2053<pre>
2054  (a|(b))+
2055</pre>
2056matches "aba" the value of the second captured substring is "b".
2057<a name="atomicgroup"></a></P>
2058<br><a name="SEC18" href="#TOC1">ATOMIC GROUPING AND POSSESSIVE QUANTIFIERS</a><br>
2059<P>
2060With both maximizing ("greedy") and minimizing ("ungreedy" or "lazy")
2061repetition, failure of what follows normally causes the repeated item to be
2062re-evaluated to see if a different number of repeats allows the rest of the
2063pattern to match. Sometimes it is useful to prevent this, either to change the
2064nature of the match, or to cause it fail earlier than it otherwise might, when
2065the author of the pattern knows there is no point in carrying on.
2066</P>
2067<P>
2068Consider, for example, the pattern \d+foo when applied to the subject line
2069<pre>
2070  123456bar
2071</pre>
2072After matching all 6 digits and then failing to match "foo", the normal
2073action of the matcher is to try again with only 5 digits matching the \d+
2074item, and then with 4, and so on, before ultimately failing. "Atomic grouping"
2075(a term taken from Jeffrey Friedl's book) provides the means for specifying
2076that once a group has matched, it is not to be re-evaluated in this way.
2077</P>
2078<P>
2079If we use atomic grouping for the previous example, the matcher gives up
2080immediately on failing to match "foo" the first time. The notation is a kind of
2081special parenthesis, starting with (?&#62; as in this example:
2082<pre>
2083  (?&#62;\d+)foo
2084</pre>
2085Perl 5.28 introduced an experimental alphabetic form starting with (* which may
2086be easier to remember:
2087<pre>
2088  (*atomic:\d+)foo
2089</pre>
2090This kind of parenthesized group "locks up" the part of the pattern it contains
2091once it has matched, and a failure further into the pattern is prevented from
2092backtracking into it. Backtracking past it to previous items, however, works as
2093normal.
2094</P>
2095<P>
2096An alternative description is that a group of this type matches exactly the
2097string of characters that an identical standalone pattern would match, if
2098anchored at the current point in the subject string.
2099</P>
2100<P>
2101Atomic groups are not capture groups. Simple cases such as the above example
2102can be thought of as a maximizing repeat that must swallow everything it can.
2103So, while both \d+ and \d+? are prepared to adjust the number of digits they
2104match in order to make the rest of the pattern match, (?&#62;\d+) can only match
2105an entire sequence of digits.
2106</P>
2107<P>
2108Atomic groups in general can of course contain arbitrarily complicated
2109expressions, and can be nested. However, when the contents of an atomic
2110group is just a single repeated item, as in the example above, a simpler
2111notation, called a "possessive quantifier" can be used. This consists of an
2112additional + character following a quantifier. Using this notation, the
2113previous example can be rewritten as
2114<pre>
2115  \d++foo
2116</pre>
2117Note that a possessive quantifier can be used with an entire group, for
2118example:
2119<pre>
2120  (abc|xyz){2,3}+
2121</pre>
2122Possessive quantifiers are always greedy; the setting of the PCRE2_UNGREEDY
2123option is ignored. They are a convenient notation for the simpler forms of
2124atomic group. However, there is no difference in the meaning of a possessive
2125quantifier and the equivalent atomic group, though there may be a performance
2126difference; possessive quantifiers should be slightly faster.
2127</P>
2128<P>
2129The possessive quantifier syntax is an extension to the Perl 5.8 syntax.
2130Jeffrey Friedl originated the idea (and the name) in the first edition of his
2131book. Mike McCloskey liked it, so implemented it when he built Sun's Java
2132package, and PCRE1 copied it from there. It found its way into Perl at release
21335.10.
2134</P>
2135<P>
2136PCRE2 has an optimization that automatically "possessifies" certain simple
2137pattern constructs. For example, the sequence A+B is treated as A++B because
2138there is no point in backtracking into a sequence of A's when B must follow.
2139This feature can be disabled by the PCRE2_NO_AUTOPOSSESS option, or starting
2140the pattern with (*NO_AUTO_POSSESS).
2141</P>
2142<P>
2143When a pattern contains an unlimited repeat inside a group that can itself be
2144repeated an unlimited number of times, the use of an atomic group is the only
2145way to avoid some failing matches taking a very long time indeed. The pattern
2146<pre>
2147  (\D+|&#60;\d+&#62;)*[!?]
2148</pre>
2149matches an unlimited number of substrings that either consist of non-digits, or
2150digits enclosed in &#60;&#62;, followed by either ! or ?. When it matches, it runs
2151quickly. However, if it is applied to
2152<pre>
2153  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
2154</pre>
2155it takes a long time before reporting failure. This is because the string can
2156be divided between the internal \D+ repeat and the external * repeat in a
2157large number of ways, and all have to be tried. (The example uses [!?] rather
2158than a single character at the end, because both PCRE2 and Perl have an
2159optimization that allows for fast failure when a single character is used. They
2160remember the last single character that is required for a match, and fail early
2161if it is not present in the string.) If the pattern is changed so that it uses
2162an atomic group, like this:
2163<pre>
2164  ((?&#62;\D+)|&#60;\d+&#62;)*[!?]
2165</pre>
2166sequences of non-digits cannot be broken, and failure happens quickly.
2167<a name="backreferences"></a></P>
2168<br><a name="SEC19" href="#TOC1">BACKREFERENCES</a><br>
2169<P>
2170Outside a character class, a backslash followed by a digit greater than 0 (and
2171possibly further digits) is a backreference to a capture group earlier (that
2172is, to its left) in the pattern, provided there have been that many previous
2173capture groups.
2174</P>
2175<P>
2176However, if the decimal number following the backslash is less than 8, it is
2177always taken as a backreference, and causes an error only if there are not that
2178many capture groups in the entire pattern. In other words, the group that is
2179referenced need not be to the left of the reference for numbers less than 8. A
2180"forward backreference" of this type can make sense when a repetition is
2181involved and the group to the right has participated in an earlier iteration.
2182</P>
2183<P>
2184It is not possible to have a numerical "forward backreference" to a group whose
2185number is 8 or more using this syntax because a sequence such as \50 is
2186interpreted as a character defined in octal. See the subsection entitled
2187"Non-printing characters"
2188<a href="#digitsafterbackslash">above</a>
2189for further details of the handling of digits following a backslash. Other
2190forms of backreferencing do not suffer from this restriction. In particular,
2191there is no problem when named capture groups are used (see below).
2192</P>
2193<P>
2194Another way of avoiding the ambiguity inherent in the use of digits following a
2195backslash is to use the \g escape sequence. This escape must be followed by a
2196signed or unsigned number, optionally enclosed in braces. These examples are
2197all identical:
2198<pre>
2199  (ring), \1
2200  (ring), \g1
2201  (ring), \g{1}
2202</pre>
2203An unsigned number specifies an absolute reference without the ambiguity that
2204is present in the older syntax. It is also useful when literal digits follow
2205the reference. A signed number is a relative reference. Consider this example:
2206<pre>
2207  (abc(def)ghi)\g{-1}
2208</pre>
2209The sequence \g{-1} is a reference to the most recently started capture group
2210before \g, that is, is it equivalent to \2 in this example. Similarly,
2211\g{-2} would be equivalent to \1. The use of relative references can be
2212helpful in long patterns, and also in patterns that are created by joining
2213together fragments that contain references within themselves.
2214</P>
2215<P>
2216The sequence \g{+1} is a reference to the next capture group. This kind of
2217forward reference can be useful in patterns that repeat. Perl does not support
2218the use of + in this way.
2219</P>
2220<P>
2221A backreference matches whatever actually most recently matched the capture
2222group in the current subject string, rather than anything at all that matches
2223the group (see
2224<a href="#groupsassubroutines">"Groups as subroutines"</a>
2225below for a way of doing that). So the pattern
2226<pre>
2227  (sens|respons)e and \1ibility
2228</pre>
2229matches "sense and sensibility" and "response and responsibility", but not
2230"sense and responsibility". If caseful matching is in force at the time of the
2231backreference, the case of letters is relevant. For example,
2232<pre>
2233  ((?i)rah)\s+\1
2234</pre>
2235matches "rah rah" and "RAH RAH", but not "RAH rah", even though the original
2236capture group is matched caselessly.
2237</P>
2238<P>
2239There are several different ways of writing backreferences to named capture
2240groups. The .NET syntax \k{name} and the Perl syntax \k&#60;name&#62; or \k'name'
2241are supported, as is the Python syntax (?P=name). Perl 5.10's unified
2242backreference syntax, in which \g can be used for both numeric and named
2243references, is also supported. We could rewrite the above example in any of the
2244following ways:
2245<pre>
2246  (?&#60;p1&#62;(?i)rah)\s+\k&#60;p1&#62;
2247  (?'p1'(?i)rah)\s+\k{p1}
2248  (?P&#60;p1&#62;(?i)rah)\s+(?P=p1)
2249  (?&#60;p1&#62;(?i)rah)\s+\g{p1}
2250</pre>
2251A capture group that is referenced by name may appear in the pattern before or
2252after the reference.
2253</P>
2254<P>
2255There may be more than one backreference to the same group. If a group has not
2256actually been used in a particular match, backreferences to it always fail by
2257default. For example, the pattern
2258<pre>
2259  (a|(bc))\2
2260</pre>
2261always fails if it starts to match "a" rather than "bc". However, if the
2262PCRE2_MATCH_UNSET_BACKREF option is set at compile time, a backreference to an
2263unset value matches an empty string.
2264</P>
2265<P>
2266Because there may be many capture groups in a pattern, all digits following a
2267backslash are taken as part of a potential backreference number. If the pattern
2268continues with a digit character, some delimiter must be used to terminate the
2269backreference. If the PCRE2_EXTENDED or PCRE2_EXTENDED_MORE option is set, this
2270can be white space. Otherwise, the \g{} syntax or an empty comment (see
2271<a href="#comments">"Comments"</a>
2272below) can be used.
2273</P>
2274<br><b>
2275Recursive backreferences
2276</b><br>
2277<P>
2278A backreference that occurs inside the group to which it refers fails when the
2279group is first used, so, for example, (a\1) never matches. However, such
2280references can be useful inside repeated groups. For example, the pattern
2281<pre>
2282  (a|b\1)+
2283</pre>
2284matches any number of "a"s and also "aba", "ababbaa" etc. At each iteration of
2285the group, the backreference matches the character string corresponding to the
2286previous iteration. In order for this to work, the pattern must be such that
2287the first iteration does not need to match the backreference. This can be done
2288using alternation, as in the example above, or by a quantifier with a minimum
2289of zero.
2290</P>
2291<P>
2292For versions of PCRE2 less than 10.25, backreferences of this type used to
2293cause the group that they reference to be treated as an
2294<a href="#atomicgroup">atomic group.</a>
2295This restriction no longer applies, and backtracking into such groups can occur
2296as normal.
2297<a name="bigassertions"></a></P>
2298<br><a name="SEC20" href="#TOC1">ASSERTIONS</a><br>
2299<P>
2300An assertion is a test on the characters following or preceding the current
2301matching point that does not consume any characters. The simple assertions
2302coded as \b, \B, \A, \G, \Z, \z, ^ and $ are described
2303<a href="#smallassertions">above.</a>
2304</P>
2305<P>
2306More complicated assertions are coded as parenthesized groups. There are two
2307kinds: those that look ahead of the current position in the subject string, and
2308those that look behind it, and in each case an assertion may be positive (must
2309match for the assertion to be true) or negative (must not match for the
2310assertion to be true). An assertion group is matched in the normal way,
2311and if it is true, matching continues after it, but with the matching position
2312in the subject string reset to what it was before the assertion was processed.
2313</P>
2314<P>
2315The Perl-compatible lookaround assertions are atomic. If an assertion is true,
2316but there is a subsequent matching failure, there is no backtracking into the
2317assertion. However, there are some cases where non-atomic assertions can be
2318useful. PCRE2 has some support for these, described in the section entitled
2319<a href="#nonatomicassertions">"Non-atomic assertions"</a>
2320below, but they are not Perl-compatible.
2321</P>
2322<P>
2323A lookaround assertion may appear as the condition in a
2324<a href="#conditions">conditional group</a>
2325(see below). In this case, the result of matching the assertion determines
2326which branch of the condition is followed.
2327</P>
2328<P>
2329Assertion groups are not capture groups. If an assertion contains capture
2330groups within it, these are counted for the purposes of numbering the capture
2331groups in the whole pattern. Within each branch of an assertion, locally
2332captured substrings may be referenced in the usual way. For example, a sequence
2333such as (.)\g{-1} can be used to check that two adjacent characters are the
2334same.
2335</P>
2336<P>
2337When a branch within an assertion fails to match, any substrings that were
2338captured are discarded (as happens with any pattern branch that fails to
2339match). A negative assertion is true only when all its branches fail to match;
2340this means that no captured substrings are ever retained after a successful
2341negative assertion. When an assertion contains a matching branch, what happens
2342depends on the type of assertion.
2343</P>
2344<P>
2345For a positive assertion, internally captured substrings in the successful
2346branch are retained, and matching continues with the next pattern item after
2347the assertion. For a negative assertion, a matching branch means that the
2348assertion is not true. If such an assertion is being used as a condition in a
2349<a href="#conditions">conditional group</a>
2350(see below), captured substrings are retained, because matching continues with
2351the "no" branch of the condition. For other failing negative assertions,
2352control passes to the previous backtracking point, thus discarding any captured
2353strings within the assertion.
2354</P>
2355<P>
2356Most assertion groups may be repeated; though it makes no sense to assert the
2357same thing several times, the side effect of capturing in positive assertions
2358may occasionally be useful. However, an assertion that forms the condition for
2359a conditional group may not be quantified. PCRE2 used to restrict the
2360repetition of assertions, but from release 10.35 the only restriction is that
2361an unlimited maximum repetition is changed to be one more than the minimum. For
2362example, {3,} is treated as {3,4}.
2363</P>
2364<br><b>
2365Alphabetic assertion names
2366</b><br>
2367<P>
2368Traditionally, symbolic sequences such as (?= and (?&#60;= have been used to
2369specify lookaround assertions. Perl 5.28 introduced some experimental
2370alphabetic alternatives which might be easier to remember. They all start with
2371(* instead of (? and must be written using lower case letters. PCRE2 supports
2372the following synonyms:
2373<pre>
2374  (*positive_lookahead:  or (*pla: is the same as (?=
2375  (*negative_lookahead:  or (*nla: is the same as (?!
2376  (*positive_lookbehind: or (*plb: is the same as (?&#60;=
2377  (*negative_lookbehind: or (*nlb: is the same as (?&#60;!
2378</pre>
2379For example, (*pla:foo) is the same assertion as (?=foo). In the following
2380sections, the various assertions are described using the original symbolic
2381forms.
2382</P>
2383<br><b>
2384Lookahead assertions
2385</b><br>
2386<P>
2387Lookahead assertions start with (?= for positive assertions and (?! for
2388negative assertions. For example,
2389<pre>
2390  \w+(?=;)
2391</pre>
2392matches a word followed by a semicolon, but does not include the semicolon in
2393the match, and
2394<pre>
2395  foo(?!bar)
2396</pre>
2397matches any occurrence of "foo" that is not followed by "bar". Note that the
2398apparently similar pattern
2399<pre>
2400  (?!foo)bar
2401</pre>
2402does not find an occurrence of "bar" that is preceded by something other than
2403"foo"; it finds any occurrence of "bar" whatsoever, because the assertion
2404(?!foo) is always true when the next three characters are "bar". A
2405lookbehind assertion is needed to achieve the other effect.
2406</P>
2407<P>
2408If you want to force a matching failure at some point in a pattern, the most
2409convenient way to do it is with (?!) because an empty string always matches, so
2410an assertion that requires there not to be an empty string must always fail.
2411The backtracking control verb (*FAIL) or (*F) is a synonym for (?!).
2412<a name="lookbehind"></a></P>
2413<br><b>
2414Lookbehind assertions
2415</b><br>
2416<P>
2417Lookbehind assertions start with (?&#60;= for positive assertions and (?&#60;! for
2418negative assertions. For example,
2419<pre>
2420  (?&#60;!foo)bar
2421</pre>
2422does find an occurrence of "bar" that is not preceded by "foo". The contents of
2423a lookbehind assertion are restricted such that all the strings it matches must
2424have a fixed length. However, if there are several top-level alternatives, they
2425do not all have to have the same fixed length. Thus
2426<pre>
2427  (?&#60;=bullock|donkey)
2428</pre>
2429is permitted, but
2430<pre>
2431  (?&#60;!dogs?|cats?)
2432</pre>
2433causes an error at compile time. Branches that match different length strings
2434are permitted only at the top level of a lookbehind assertion. This is an
2435extension compared with Perl, which requires all branches to match the same
2436length of string. An assertion such as
2437<pre>
2438  (?&#60;=ab(c|de))
2439</pre>
2440is not permitted, because its single top-level branch can match two different
2441lengths, but it is acceptable to PCRE2 if rewritten to use two top-level
2442branches:
2443<pre>
2444  (?&#60;=abc|abde)
2445</pre>
2446In some cases, the escape sequence \K
2447<a href="#resetmatchstart">(see above)</a>
2448can be used instead of a lookbehind assertion to get round the fixed-length
2449restriction.
2450</P>
2451<P>
2452The implementation of lookbehind assertions is, for each alternative, to
2453temporarily move the current position back by the fixed length and then try to
2454match. If there are insufficient characters before the current position, the
2455assertion fails.
2456</P>
2457<P>
2458In UTF-8 and UTF-16 modes, PCRE2 does not allow the \C escape (which matches a
2459single code unit even in a UTF mode) to appear in lookbehind assertions,
2460because it makes it impossible to calculate the length of the lookbehind. The
2461\X and \R escapes, which can match different numbers of code units, are never
2462permitted in lookbehinds.
2463</P>
2464<P>
2465<a href="#groupsassubroutines">"Subroutine"</a>
2466calls (see below) such as (?2) or (?&X) are permitted in lookbehinds, as long
2467as the called capture group matches a fixed-length string. However,
2468<a href="#recursion">recursion,</a>
2469that is, a "subroutine" call into a group that is already active,
2470is not supported.
2471</P>
2472<P>
2473Perl does not support backreferences in lookbehinds. PCRE2 does support them,
2474but only if certain conditions are met. The PCRE2_MATCH_UNSET_BACKREF option
2475must not be set, there must be no use of (?| in the pattern (it creates
2476duplicate group numbers), and if the backreference is by name, the name
2477must be unique. Of course, the referenced group must itself match a fixed
2478length substring. The following pattern matches words containing at least two
2479characters that begin and end with the same character:
2480<pre>
2481   \b(\w)\w++(?&#60;=\1)
2482</PRE>
2483</P>
2484<P>
2485Possessive quantifiers can be used in conjunction with lookbehind assertions to
2486specify efficient matching of fixed-length strings at the end of subject
2487strings. Consider a simple pattern such as
2488<pre>
2489  abcd$
2490</pre>
2491when applied to a long string that does not match. Because matching proceeds
2492from left to right, PCRE2 will look for each "a" in the subject and then see if
2493what follows matches the rest of the pattern. If the pattern is specified as
2494<pre>
2495  ^.*abcd$
2496</pre>
2497the initial .* matches the entire string at first, but when this fails (because
2498there is no following "a"), it backtracks to match all but the last character,
2499then all but the last two characters, and so on. Once again the search for "a"
2500covers the entire string, from right to left, so we are no better off. However,
2501if the pattern is written as
2502<pre>
2503  ^.*+(?&#60;=abcd)
2504</pre>
2505there can be no backtracking for the .*+ item because of the possessive
2506quantifier; it can match only the entire string. The subsequent lookbehind
2507assertion does a single test on the last four characters. If it fails, the
2508match fails immediately. For long strings, this approach makes a significant
2509difference to the processing time.
2510</P>
2511<br><b>
2512Using multiple assertions
2513</b><br>
2514<P>
2515Several assertions (of any sort) may occur in succession. For example,
2516<pre>
2517  (?&#60;=\d{3})(?&#60;!999)foo
2518</pre>
2519matches "foo" preceded by three digits that are not "999". Notice that each of
2520the assertions is applied independently at the same point in the subject
2521string. First there is a check that the previous three characters are all
2522digits, and then there is a check that the same three characters are not "999".
2523This pattern does <i>not</i> match "foo" preceded by six characters, the first
2524of which are digits and the last three of which are not "999". For example, it
2525doesn't match "123abcfoo". A pattern to do that is
2526<pre>
2527  (?&#60;=\d{3}...)(?&#60;!999)foo
2528</pre>
2529This time the first assertion looks at the preceding six characters, checking
2530that the first three are digits, and then the second assertion checks that the
2531preceding three characters are not "999".
2532</P>
2533<P>
2534Assertions can be nested in any combination. For example,
2535<pre>
2536  (?&#60;=(?&#60;!foo)bar)baz
2537</pre>
2538matches an occurrence of "baz" that is preceded by "bar" which in turn is not
2539preceded by "foo", while
2540<pre>
2541  (?&#60;=\d{3}(?!999)...)foo
2542</pre>
2543is another pattern that matches "foo" preceded by three digits and any three
2544characters that are not "999".
2545<a name="nonatomicassertions"></a></P>
2546<br><a name="SEC21" href="#TOC1">NON-ATOMIC ASSERTIONS</a><br>
2547<P>
2548The traditional Perl-compatible lookaround assertions are atomic. That is, if
2549an assertion is true, but there is a subsequent matching failure, there is no
2550backtracking into the assertion. However, there are some cases where non-atomic
2551positive assertions can be useful. PCRE2 provides these using the following
2552syntax:
2553<pre>
2554  (*non_atomic_positive_lookahead:  or (*napla: or (?*
2555  (*non_atomic_positive_lookbehind: or (*naplb: or (?&#60;*
2556</pre>
2557Consider the problem of finding the right-most word in a string that also
2558appears earlier in the string, that is, it must appear at least twice in total.
2559This pattern returns the required result as captured substring 1:
2560<pre>
2561  ^(?x)(*napla: .* \b(\w++)) (?&#62; .*? \b\1\b ){2}
2562</pre>
2563For a subject such as "word1 word2 word3 word2 word3 word4" the result is
2564"word3". How does it work? At the start, ^(?x) anchors the pattern and sets the
2565"x" option, which causes white space (introduced for readability) to be
2566ignored. Inside the assertion, the greedy .* at first consumes the entire
2567string, but then has to backtrack until the rest of the assertion can match a
2568word, which is captured by group 1. In other words, when the assertion first
2569succeeds, it captures the right-most word in the string.
2570</P>
2571<P>
2572The current matching point is then reset to the start of the subject, and the
2573rest of the pattern match checks for two occurrences of the captured word,
2574using an ungreedy .*? to scan from the left. If this succeeds, we are done, but
2575if the last word in the string does not occur twice, this part of the pattern
2576fails. If a traditional atomic lookhead (?= or (*pla: had been used, the
2577assertion could not be re-entered, and the whole match would fail. The pattern
2578would succeed only if the very last word in the subject was found twice.
2579</P>
2580<P>
2581Using a non-atomic lookahead, however, means that when the last word does not
2582occur twice in the string, the lookahead can backtrack and find the second-last
2583word, and so on, until either the match succeeds, or all words have been
2584tested.
2585</P>
2586<P>
2587Two conditions must be met for a non-atomic assertion to be useful: the
2588contents of one or more capturing groups must change after a backtrack into the
2589assertion, and there must be a backreference to a changed group later in the
2590pattern. If this is not the case, the rest of the pattern match fails exactly
2591as before because nothing has changed, so using a non-atomic assertion just
2592wastes resources.
2593</P>
2594<P>
2595There is one exception to backtracking into a non-atomic assertion. If an
2596(*ACCEPT) control verb is triggered, the assertion succeeds atomically. That
2597is, a subsequent match failure cannot backtrack into the assertion.
2598</P>
2599<P>
2600Non-atomic assertions are not supported by the alternative matching function
2601<b>pcre2_dfa_match()</b>. They are supported by JIT, but only if they do not
2602contain any control verbs such as (*ACCEPT). (This may change in future). Note
2603that assertions that appear as conditions for
2604<a href="#conditions">conditional groups</a>
2605(see below) must be atomic.
2606</P>
2607<br><a name="SEC22" href="#TOC1">SCRIPT RUNS</a><br>
2608<P>
2609In concept, a script run is a sequence of characters that are all from the same
2610Unicode script such as Latin or Greek. However, because some scripts are
2611commonly used together, and because some diacritical and other marks are used
2612with multiple scripts, it is not that simple. There is a full description of
2613the rules that PCRE2 uses in the section entitled
2614<a href="pcre2unicode.html#scriptruns">"Script Runs"</a>
2615in the
2616<a href="pcre2unicode.html"><b>pcre2unicode</b></a>
2617documentation.
2618</P>
2619<P>
2620If part of a pattern is enclosed between (*script_run: or (*sr: and a closing
2621parenthesis, it fails if the sequence of characters that it matches are not a
2622script run. After a failure, normal backtracking occurs. Script runs can be
2623used to detect spoofing attacks using characters that look the same, but are
2624from different scripts. The string "paypal.com" is an infamous example, where
2625the letters could be a mixture of Latin and Cyrillic. This pattern ensures that
2626the matched characters in a sequence of non-spaces that follow white space are
2627a script run:
2628<pre>
2629  \s+(*sr:\S+)
2630</pre>
2631To be sure that they are all from the Latin script (for example), a lookahead
2632can be used:
2633<pre>
2634  \s+(?=\p{Latin})(*sr:\S+)
2635</pre>
2636This works as long as the first character is expected to be a character in that
2637script, and not (for example) punctuation, which is allowed with any script. If
2638this is not the case, a more creative lookahead is needed. For example, if
2639digits, underscore, and dots are permitted at the start:
2640<pre>
2641  \s+(?=[0-9_.]*\p{Latin})(*sr:\S+)
2642
2643</PRE>
2644</P>
2645<P>
2646In many cases, backtracking into a script run pattern fragment is not
2647desirable. The script run can employ an atomic group to prevent this. Because
2648this is a common requirement, a shorthand notation is provided by
2649(*atomic_script_run: or (*asr:
2650<pre>
2651  (*asr:...) is the same as (*sr:(?&#62;...))
2652</pre>
2653Note that the atomic group is inside the script run. Putting it outside would
2654not prevent backtracking into the script run pattern.
2655</P>
2656<P>
2657Support for script runs is not available if PCRE2 is compiled without Unicode
2658support. A compile-time error is given if any of the above constructs is
2659encountered. Script runs are not supported by the alternate matching function,
2660<b>pcre2_dfa_match()</b> because they use the same mechanism as capturing
2661parentheses.
2662</P>
2663<P>
2664<b>Warning:</b> The (*ACCEPT) control verb
2665<a href="#acceptverb">(see below)</a>
2666should not be used within a script run group, because it causes an immediate
2667exit from the group, bypassing the script run checking.
2668<a name="conditions"></a></P>
2669<br><a name="SEC23" href="#TOC1">CONDITIONAL GROUPS</a><br>
2670<P>
2671It is possible to cause the matching process to obey a pattern fragment
2672conditionally or to choose between two alternative fragments, depending on
2673the result of an assertion, or whether a specific capture group has
2674already been matched. The two possible forms of conditional group are:
2675<pre>
2676  (?(condition)yes-pattern)
2677  (?(condition)yes-pattern|no-pattern)
2678</pre>
2679If the condition is satisfied, the yes-pattern is used; otherwise the
2680no-pattern (if present) is used. An absent no-pattern is equivalent to an empty
2681string (it always matches). If there are more than two alternatives in the
2682group, a compile-time error occurs. Each of the two alternatives may itself
2683contain nested groups of any form, including conditional groups; the
2684restriction to two alternatives applies only at the level of the condition
2685itself. This pattern fragment is an example where the alternatives are complex:
2686<pre>
2687  (?(1) (A|B|C) | (D | (?(2)E|F) | E) )
2688
2689</PRE>
2690</P>
2691<P>
2692There are five kinds of condition: references to capture groups, references to
2693recursion, two pseudo-conditions called DEFINE and VERSION, and assertions.
2694</P>
2695<br><b>
2696Checking for a used capture group by number
2697</b><br>
2698<P>
2699If the text between the parentheses consists of a sequence of digits, the
2700condition is true if a capture group of that number has previously matched. If
2701there is more than one capture group with the same number (see the earlier
2702<a href="#recursion">section about duplicate group numbers),</a>
2703the condition is true if any of them have matched. An alternative notation is
2704to precede the digits with a plus or minus sign. In this case, the group number
2705is relative rather than absolute. The most recently opened capture group can be
2706referenced by (?(-1), the next most recent by (?(-2), and so on. Inside loops
2707it can also make sense to refer to subsequent groups. The next capture group
2708can be referenced as (?(+1), and so on. (The value zero in any of these forms
2709is not used; it provokes a compile-time error.)
2710</P>
2711<P>
2712Consider the following pattern, which contains non-significant white space to
2713make it more readable (assume the PCRE2_EXTENDED option) and to divide it into
2714three parts for ease of discussion:
2715<pre>
2716  ( \( )?    [^()]+    (?(1) \) )
2717</pre>
2718The first part matches an optional opening parenthesis, and if that
2719character is present, sets it as the first captured substring. The second part
2720matches one or more characters that are not parentheses. The third part is a
2721conditional group that tests whether or not the first capture group
2722matched. If it did, that is, if subject started with an opening parenthesis,
2723the condition is true, and so the yes-pattern is executed and a closing
2724parenthesis is required. Otherwise, since no-pattern is not present, the
2725conditional group matches nothing. In other words, this pattern matches a
2726sequence of non-parentheses, optionally enclosed in parentheses.
2727</P>
2728<P>
2729If you were embedding this pattern in a larger one, you could use a relative
2730reference:
2731<pre>
2732  ...other stuff... ( \( )?    [^()]+    (?(-1) \) ) ...
2733</pre>
2734This makes the fragment independent of the parentheses in the larger pattern.
2735</P>
2736<br><b>
2737Checking for a used capture group by name
2738</b><br>
2739<P>
2740Perl uses the syntax (?(&#60;name&#62;)...) or (?('name')...) to test for a used
2741capture group by name. For compatibility with earlier versions of PCRE1, which
2742had this facility before Perl, the syntax (?(name)...) is also recognized.
2743Note, however, that undelimited names consisting of the letter R followed by
2744digits are ambiguous (see the following section). Rewriting the above example
2745to use a named group gives this:
2746<pre>
2747  (?&#60;OPEN&#62; \( )?    [^()]+    (?(&#60;OPEN&#62;) \) )
2748</pre>
2749If the name used in a condition of this kind is a duplicate, the test is
2750applied to all groups of the same name, and is true if any one of them has
2751matched.
2752</P>
2753<br><b>
2754Checking for pattern recursion
2755</b><br>
2756<P>
2757"Recursion" in this sense refers to any subroutine-like call from one part of
2758the pattern to another, whether or not it is actually recursive. See the
2759sections entitled
2760<a href="#recursion">"Recursive patterns"</a>
2761and
2762<a href="#groupsassubroutines">"Groups as subroutines"</a>
2763below for details of recursion and subroutine calls.
2764</P>
2765<P>
2766If a condition is the string (R), and there is no capture group with the name
2767R, the condition is true if matching is currently in a recursion or subroutine
2768call to the whole pattern or any capture group. If digits follow the letter R,
2769and there is no group with that name, the condition is true if the most recent
2770call is into a group with the given number, which must exist somewhere in the
2771overall pattern. This is a contrived example that is equivalent to a+b:
2772<pre>
2773  ((?(R1)a+|(?1)b))
2774</pre>
2775However, in both cases, if there is a capture group with a matching name, the
2776condition tests for its being set, as described in the section above, instead
2777of testing for recursion. For example, creating a group with the name R1 by
2778adding (?&#60;R1&#62;) to the above pattern completely changes its meaning.
2779</P>
2780<P>
2781If a name preceded by ampersand follows the letter R, for example:
2782<pre>
2783  (?(R&name)...)
2784</pre>
2785the condition is true if the most recent recursion is into a group of that name
2786(which must exist within the pattern).
2787</P>
2788<P>
2789This condition does not check the entire recursion stack. It tests only the
2790current level. If the name used in a condition of this kind is a duplicate, the
2791test is applied to all groups of the same name, and is true if any one of
2792them is the most recent recursion.
2793</P>
2794<P>
2795At "top level", all these recursion test conditions are false.
2796<a name="subdefine"></a></P>
2797<br><b>
2798Defining capture groups for use by reference only
2799</b><br>
2800<P>
2801If the condition is the string (DEFINE), the condition is always false, even if
2802there is a group with the name DEFINE. In this case, there may be only one
2803alternative in the rest of the conditional group. It is always skipped if
2804control reaches this point in the pattern; the idea of DEFINE is that it can be
2805used to define subroutines that can be referenced from elsewhere. (The use of
2806<a href="#groupsassubroutines">subroutines</a>
2807is described below.) For example, a pattern to match an IPv4 address such as
2808"192.168.23.245" could be written like this (ignore white space and line
2809breaks):
2810<pre>
2811  (?(DEFINE) (?&#60;byte&#62; 2[0-4]\d | 25[0-5] | 1\d\d | [1-9]?\d) )
2812  \b (?&byte) (\.(?&byte)){3} \b
2813</pre>
2814The first part of the pattern is a DEFINE group inside which another group
2815named "byte" is defined. This matches an individual component of an IPv4
2816address (a number less than 256). When matching takes place, this part of the
2817pattern is skipped because DEFINE acts like a false condition. The rest of the
2818pattern uses references to the named group to match the four dot-separated
2819components of an IPv4 address, insisting on a word boundary at each end.
2820</P>
2821<br><b>
2822Checking the PCRE2 version
2823</b><br>
2824<P>
2825Programs that link with a PCRE2 library can check the version by calling
2826<b>pcre2_config()</b> with appropriate arguments. Users of applications that do
2827not have access to the underlying code cannot do this. A special "condition"
2828called VERSION exists to allow such users to discover which version of PCRE2
2829they are dealing with by using this condition to match a string such as
2830"yesno". VERSION must be followed either by "=" or "&#62;=" and a version number.
2831For example:
2832<pre>
2833  (?(VERSION&#62;=10.4)yes|no)
2834</pre>
2835This pattern matches "yes" if the PCRE2 version is greater or equal to 10.4, or
2836"no" otherwise. The fractional part of the version number may not contain more
2837than two digits.
2838</P>
2839<br><b>
2840Assertion conditions
2841</b><br>
2842<P>
2843If the condition is not in any of the above formats, it must be a parenthesized
2844assertion. This may be a positive or negative lookahead or lookbehind
2845assertion. However, it must be a traditional atomic assertion, not one of the
2846PCRE2-specific
2847<a href="#nonatomicassertions">non-atomic assertions.</a>
2848</P>
2849<P>
2850Consider this pattern, again containing non-significant white space, and with
2851the two alternatives on the second line:
2852<pre>
2853  (?(?=[^a-z]*[a-z])
2854  \d{2}-[a-z]{3}-\d{2}  |  \d{2}-\d{2}-\d{2} )
2855</pre>
2856The condition is a positive lookahead assertion that matches an optional
2857sequence of non-letters followed by a letter. In other words, it tests for the
2858presence of at least one letter in the subject. If a letter is found, the
2859subject is matched against the first alternative; otherwise it is matched
2860against the second. This pattern matches strings in one of the two forms
2861dd-aaa-dd or dd-dd-dd, where aaa are letters and dd are digits.
2862</P>
2863<P>
2864When an assertion that is a condition contains capture groups, any
2865capturing that occurs in a matching branch is retained afterwards, for both
2866positive and negative assertions, because matching always continues after the
2867assertion, whether it succeeds or fails. (Compare non-conditional assertions,
2868for which captures are retained only for positive assertions that succeed.)
2869<a name="comments"></a></P>
2870<br><a name="SEC24" href="#TOC1">COMMENTS</a><br>
2871<P>
2872There are two ways of including comments in patterns that are processed by
2873PCRE2. In both cases, the start of the comment must not be in a character
2874class, nor in the middle of any other sequence of related characters such as
2875(?: or a group name or number. The characters that make up a comment play
2876no part in the pattern matching.
2877</P>
2878<P>
2879The sequence (?# marks the start of a comment that continues up to the next
2880closing parenthesis. Nested parentheses are not permitted. If the
2881PCRE2_EXTENDED or PCRE2_EXTENDED_MORE option is set, an unescaped # character
2882also introduces a comment, which in this case continues to immediately after
2883the next newline character or character sequence in the pattern. Which
2884characters are interpreted as newlines is controlled by an option passed to the
2885compiling function or by a special sequence at the start of the pattern, as
2886described in the section entitled
2887<a href="#newlines">"Newline conventions"</a>
2888above. Note that the end of this type of comment is a literal newline sequence
2889in the pattern; escape sequences that happen to represent a newline do not
2890count. For example, consider this pattern when PCRE2_EXTENDED is set, and the
2891default newline convention (a single linefeed character) is in force:
2892<pre>
2893  abc #comment \n still comment
2894</pre>
2895On encountering the # character, <b>pcre2_compile()</b> skips along, looking for
2896a newline in the pattern. The sequence \n is still literal at this stage, so
2897it does not terminate the comment. Only an actual character with the code value
28980x0a (the default newline) does so.
2899<a name="recursion"></a></P>
2900<br><a name="SEC25" href="#TOC1">RECURSIVE PATTERNS</a><br>
2901<P>
2902Consider the problem of matching a string in parentheses, allowing for
2903unlimited nested parentheses. Without the use of recursion, the best that can
2904be done is to use a pattern that matches up to some fixed depth of nesting. It
2905is not possible to handle an arbitrary nesting depth.
2906</P>
2907<P>
2908For some time, Perl has provided a facility that allows regular expressions to
2909recurse (amongst other things). It does this by interpolating Perl code in the
2910expression at run time, and the code can refer to the expression itself. A Perl
2911pattern using code interpolation to solve the parentheses problem can be
2912created like this:
2913<pre>
2914  $re = qr{\( (?: (?&#62;[^()]+) | (?p{$re}) )* \)}x;
2915</pre>
2916The (?p{...}) item interpolates Perl code at run time, and in this case refers
2917recursively to the pattern in which it appears.
2918</P>
2919<P>
2920Obviously, PCRE2 cannot support the interpolation of Perl code. Instead, it
2921supports special syntax for recursion of the entire pattern, and also for
2922individual capture group recursion. After its introduction in PCRE1 and Python,
2923this kind of recursion was subsequently introduced into Perl at release 5.10.
2924</P>
2925<P>
2926A special item that consists of (? followed by a number greater than zero and a
2927closing parenthesis is a recursive subroutine call of the capture group of the
2928given number, provided that it occurs inside that group. (If not, it is a
2929<a href="#groupsassubroutines">non-recursive subroutine</a>
2930call, which is described in the next section.) The special item (?R) or (?0) is
2931a recursive call of the entire regular expression.
2932</P>
2933<P>
2934This PCRE2 pattern solves the nested parentheses problem (assume the
2935PCRE2_EXTENDED option is set so that white space is ignored):
2936<pre>
2937  \( ( [^()]++ | (?R) )* \)
2938</pre>
2939First it matches an opening parenthesis. Then it matches any number of
2940substrings which can either be a sequence of non-parentheses, or a recursive
2941match of the pattern itself (that is, a correctly parenthesized substring).
2942Finally there is a closing parenthesis. Note the use of a possessive quantifier
2943to avoid backtracking into sequences of non-parentheses.
2944</P>
2945<P>
2946If this were part of a larger pattern, you would not want to recurse the entire
2947pattern, so instead you could use this:
2948<pre>
2949  ( \( ( [^()]++ | (?1) )* \) )
2950</pre>
2951We have put the pattern into parentheses, and caused the recursion to refer to
2952them instead of the whole pattern.
2953</P>
2954<P>
2955In a larger pattern, keeping track of parenthesis numbers can be tricky. This
2956is made easier by the use of relative references. Instead of (?1) in the
2957pattern above you can write (?-2) to refer to the second most recently opened
2958parentheses preceding the recursion. In other words, a negative number counts
2959capturing parentheses leftwards from the point at which it is encountered.
2960</P>
2961<P>
2962Be aware however, that if
2963<a href="#dupgroupnumber">duplicate capture group numbers</a>
2964are in use, relative references refer to the earliest group with the
2965appropriate number. Consider, for example:
2966<pre>
2967  (?|(a)|(b)) (c) (?-2)
2968</pre>
2969The first two capture groups (a) and (b) are both numbered 1, and group (c)
2970is number 2. When the reference (?-2) is encountered, the second most recently
2971opened parentheses has the number 1, but it is the first such group (the (a)
2972group) to which the recursion refers. This would be the same if an absolute
2973reference (?1) was used. In other words, relative references are just a
2974shorthand for computing a group number.
2975</P>
2976<P>
2977It is also possible to refer to subsequent capture groups, by writing
2978references such as (?+2). However, these cannot be recursive because the
2979reference is not inside the parentheses that are referenced. They are always
2980<a href="#groupsassubroutines">non-recursive subroutine</a>
2981calls, as described in the next section.
2982</P>
2983<P>
2984An alternative approach is to use named parentheses. The Perl syntax for this
2985is (?&name); PCRE1's earlier syntax (?P&#62;name) is also supported. We could
2986rewrite the above example as follows:
2987<pre>
2988  (?&#60;pn&#62; \( ( [^()]++ | (?&pn) )* \) )
2989</pre>
2990If there is more than one group with the same name, the earliest one is
2991used.
2992</P>
2993<P>
2994The example pattern that we have been looking at contains nested unlimited
2995repeats, and so the use of a possessive quantifier for matching strings of
2996non-parentheses is important when applying the pattern to strings that do not
2997match. For example, when this pattern is applied to
2998<pre>
2999  (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()
3000</pre>
3001it yields "no match" quickly. However, if a possessive quantifier is not used,
3002the match runs for a very long time indeed because there are so many different
3003ways the + and * repeats can carve up the subject, and all have to be tested
3004before failure can be reported.
3005</P>
3006<P>
3007At the end of a match, the values of capturing parentheses are those from
3008the outermost level. If you want to obtain intermediate values, a callout
3009function can be used (see below and the
3010<a href="pcre2callout.html"><b>pcre2callout</b></a>
3011documentation). If the pattern above is matched against
3012<pre>
3013  (ab(cd)ef)
3014</pre>
3015the value for the inner capturing parentheses (numbered 2) is "ef", which is
3016the last value taken on at the top level. If a capture group is not matched at
3017the top level, its final captured value is unset, even if it was (temporarily)
3018set at a deeper level during the matching process.
3019</P>
3020<P>
3021Do not confuse the (?R) item with the condition (R), which tests for recursion.
3022Consider this pattern, which matches text in angle brackets, allowing for
3023arbitrary nesting. Only digits are allowed in nested brackets (that is, when
3024recursing), whereas any characters are permitted at the outer level.
3025<pre>
3026  &#60; (?: (?(R) \d++  | [^&#60;&#62;]*+) | (?R)) * &#62;
3027</pre>
3028In this pattern, (?(R) is the start of a conditional group, with two different
3029alternatives for the recursive and non-recursive cases. The (?R) item is the
3030actual recursive call.
3031<a name="recursiondifference"></a></P>
3032<br><b>
3033Differences in recursion processing between PCRE2 and Perl
3034</b><br>
3035<P>
3036Some former differences between PCRE2 and Perl no longer exist.
3037</P>
3038<P>
3039Before release 10.30, recursion processing in PCRE2 differed from Perl in that
3040a recursive subroutine call was always treated as an atomic group. That is,
3041once it had matched some of the subject string, it was never re-entered, even
3042if it contained untried alternatives and there was a subsequent matching
3043failure. (Historical note: PCRE implemented recursion before Perl did.)
3044</P>
3045<P>
3046Starting with release 10.30, recursive subroutine calls are no longer treated
3047as atomic. That is, they can be re-entered to try unused alternatives if there
3048is a matching failure later in the pattern. This is now compatible with the way
3049Perl works. If you want a subroutine call to be atomic, you must explicitly
3050enclose it in an atomic group.
3051</P>
3052<P>
3053Supporting backtracking into recursions simplifies certain types of recursive
3054pattern. For example, this pattern matches palindromic strings:
3055<pre>
3056  ^((.)(?1)\2|.?)$
3057</pre>
3058The second branch in the group matches a single central character in the
3059palindrome when there are an odd number of characters, or nothing when there
3060are an even number of characters, but in order to work it has to be able to try
3061the second case when the rest of the pattern match fails. If you want to match
3062typical palindromic phrases, the pattern has to ignore all non-word characters,
3063which can be done like this:
3064<pre>
3065  ^\W*+((.)\W*+(?1)\W*+\2|\W*+.?)\W*+$
3066</pre>
3067If run with the PCRE2_CASELESS option, this pattern matches phrases such as "A
3068man, a plan, a canal: Panama!". Note the use of the possessive quantifier *+ to
3069avoid backtracking into sequences of non-word characters. Without this, PCRE2
3070takes a great deal longer (ten times or more) to match typical phrases, and
3071Perl takes so long that you think it has gone into a loop.
3072</P>
3073<P>
3074Another way in which PCRE2 and Perl used to differ in their recursion
3075processing is in the handling of captured values. Formerly in Perl, when a
3076group was called recursively or as a subroutine (see the next section), it
3077had no access to any values that were captured outside the recursion, whereas
3078in PCRE2 these values can be referenced. Consider this pattern:
3079<pre>
3080  ^(.)(\1|a(?2))
3081</pre>
3082This pattern matches "bab". The first capturing parentheses match "b", then in
3083the second group, when the backreference \1 fails to match "b", the second
3084alternative matches "a" and then recurses. In the recursion, \1 does now match
3085"b" and so the whole match succeeds. This match used to fail in Perl, but in
3086later versions (I tried 5.024) it now works.
3087<a name="groupsassubroutines"></a></P>
3088<br><a name="SEC26" href="#TOC1">GROUPS AS SUBROUTINES</a><br>
3089<P>
3090If the syntax for a recursive group call (either by number or by name) is used
3091outside the parentheses to which it refers, it operates a bit like a subroutine
3092in a programming language. More accurately, PCRE2 treats the referenced group
3093as an independent subpattern which it tries to match at the current matching
3094position. The called group may be defined before or after the reference. A
3095numbered reference can be absolute or relative, as in these examples:
3096<pre>
3097  (...(absolute)...)...(?2)...
3098  (...(relative)...)...(?-1)...
3099  (...(?+1)...(relative)...
3100</pre>
3101An earlier example pointed out that the pattern
3102<pre>
3103  (sens|respons)e and \1ibility
3104</pre>
3105matches "sense and sensibility" and "response and responsibility", but not
3106"sense and responsibility". If instead the pattern
3107<pre>
3108  (sens|respons)e and (?1)ibility
3109</pre>
3110is used, it does match "sense and responsibility" as well as the other two
3111strings. Another example is given in the discussion of DEFINE above.
3112</P>
3113<P>
3114Like recursions, subroutine calls used to be treated as atomic, but this
3115changed at PCRE2 release 10.30, so backtracking into subroutine calls can now
3116occur. However, any capturing parentheses that are set during the subroutine
3117call revert to their previous values afterwards.
3118</P>
3119<P>
3120Processing options such as case-independence are fixed when a group is
3121defined, so if it is used as a subroutine, such options cannot be changed for
3122different calls. For example, consider this pattern:
3123<pre>
3124  (abc)(?i:(?-1))
3125</pre>
3126It matches "abcabc". It does not match "abcABC" because the change of
3127processing option does not affect the called group.
3128</P>
3129<P>
3130The behaviour of
3131<a href="#backtrackcontrol">backtracking control verbs</a>
3132in groups when called as subroutines is described in the section entitled
3133<a href="#btsub">"Backtracking verbs in subroutines"</a>
3134below.
3135<a name="onigurumasubroutines"></a></P>
3136<br><a name="SEC27" href="#TOC1">ONIGURUMA SUBROUTINE SYNTAX</a><br>
3137<P>
3138For compatibility with Oniguruma, the non-Perl syntax \g followed by a name or
3139a number enclosed either in angle brackets or single quotes, is an alternative
3140syntax for calling a group as a subroutine, possibly recursively. Here are two
3141of the examples used above, rewritten using this syntax:
3142<pre>
3143  (?&#60;pn&#62; \( ( (?&#62;[^()]+) | \g&#60;pn&#62; )* \) )
3144  (sens|respons)e and \g'1'ibility
3145</pre>
3146PCRE2 supports an extension to Oniguruma: if a number is preceded by a
3147plus or a minus sign it is taken as a relative reference. For example:
3148<pre>
3149  (abc)(?i:\g&#60;-1&#62;)
3150</pre>
3151Note that \g{...} (Perl syntax) and \g&#60;...&#62; (Oniguruma syntax) are <i>not</i>
3152synonymous. The former is a backreference; the latter is a subroutine call.
3153</P>
3154<br><a name="SEC28" href="#TOC1">CALLOUTS</a><br>
3155<P>
3156Perl has a feature whereby using the sequence (?{...}) causes arbitrary Perl
3157code to be obeyed in the middle of matching a regular expression. This makes it
3158possible, amongst other things, to extract different substrings that match the
3159same pair of parentheses when there is a repetition.
3160</P>
3161<P>
3162PCRE2 provides a similar feature, but of course it cannot obey arbitrary Perl
3163code. The feature is called "callout". The caller of PCRE2 provides an external
3164function by putting its entry point in a match context using the function
3165<b>pcre2_set_callout()</b>, and then passing that context to <b>pcre2_match()</b>
3166or <b>pcre2_dfa_match()</b>. If no match context is passed, or if the callout
3167entry point is set to NULL, callouts are disabled.
3168</P>
3169<P>
3170Within a regular expression, (?C&#60;arg&#62;) indicates a point at which the external
3171function is to be called. There are two kinds of callout: those with a
3172numerical argument and those with a string argument. (?C) on its own with no
3173argument is treated as (?C0). A numerical argument allows the application to
3174distinguish between different callouts. String arguments were added for release
317510.20 to make it possible for script languages that use PCRE2 to embed short
3176scripts within patterns in a similar way to Perl.
3177</P>
3178<P>
3179During matching, when PCRE2 reaches a callout point, the external function is
3180called. It is provided with the number or string argument of the callout, the
3181position in the pattern, and one item of data that is also set in the match
3182block. The callout function may cause matching to proceed, to backtrack, or to
3183fail.
3184</P>
3185<P>
3186By default, PCRE2 implements a number of optimizations at matching time, and
3187one side-effect is that sometimes callouts are skipped. If you need all
3188possible callouts to happen, you need to set options that disable the relevant
3189optimizations. More details, including a complete description of the
3190programming interface to the callout function, are given in the
3191<a href="pcre2callout.html"><b>pcre2callout</b></a>
3192documentation.
3193</P>
3194<br><b>
3195Callouts with numerical arguments
3196</b><br>
3197<P>
3198If you just want to have a means of identifying different callout points, put a
3199number less than 256 after the letter C. For example, this pattern has two
3200callout points:
3201<pre>
3202  (?C1)abc(?C2)def
3203</pre>
3204If the PCRE2_AUTO_CALLOUT flag is passed to <b>pcre2_compile()</b>, numerical
3205callouts are automatically installed before each item in the pattern. They are
3206all numbered 255. If there is a conditional group in the pattern whose
3207condition is an assertion, an additional callout is inserted just before the
3208condition. An explicit callout may also be set at this position, as in this
3209example:
3210<pre>
3211  (?(?C9)(?=a)abc|def)
3212</pre>
3213Note that this applies only to assertion conditions, not to other types of
3214condition.
3215</P>
3216<br><b>
3217Callouts with string arguments
3218</b><br>
3219<P>
3220A delimited string may be used instead of a number as a callout argument. The
3221starting delimiter must be one of ` ' " ^ % # $ { and the ending delimiter is
3222the same as the start, except for {, where the ending delimiter is }. If the
3223ending delimiter is needed within the string, it must be doubled. For
3224example:
3225<pre>
3226  (?C'ab ''c'' d')xyz(?C{any text})pqr
3227</pre>
3228The doubling is removed before the string is passed to the callout function.
3229<a name="backtrackcontrol"></a></P>
3230<br><a name="SEC29" href="#TOC1">BACKTRACKING CONTROL</a><br>
3231<P>
3232There are a number of special "Backtracking Control Verbs" (to use Perl's
3233terminology) that modify the behaviour of backtracking during matching. They
3234are generally of the form (*VERB) or (*VERB:NAME). Some verbs take either form,
3235and may behave differently depending on whether or not a name argument is
3236present. The names are not required to be unique within the pattern.
3237</P>
3238<P>
3239By default, for compatibility with Perl, a name is any sequence of characters
3240that does not include a closing parenthesis. The name is not processed in
3241any way, and it is not possible to include a closing parenthesis in the name.
3242This can be changed by setting the PCRE2_ALT_VERBNAMES option, but the result
3243is no longer Perl-compatible.
3244</P>
3245<P>
3246When PCRE2_ALT_VERBNAMES is set, backslash processing is applied to verb names
3247and only an unescaped closing parenthesis terminates the name. However, the
3248only backslash items that are permitted are \Q, \E, and sequences such as
3249\x{100} that define character code points. Character type escapes such as \d
3250are faulted.
3251</P>
3252<P>
3253A closing parenthesis can be included in a name either as \) or between \Q
3254and \E. In addition to backslash processing, if the PCRE2_EXTENDED or
3255PCRE2_EXTENDED_MORE option is also set, unescaped whitespace in verb names is
3256skipped, and #-comments are recognized, exactly as in the rest of the pattern.
3257PCRE2_EXTENDED and PCRE2_EXTENDED_MORE do not affect verb names unless
3258PCRE2_ALT_VERBNAMES is also set.
3259</P>
3260<P>
3261The maximum length of a name is 255 in the 8-bit library and 65535 in the
326216-bit and 32-bit libraries. If the name is empty, that is, if the closing
3263parenthesis immediately follows the colon, the effect is as if the colon were
3264not there. Any number of these verbs may occur in a pattern. Except for
3265(*ACCEPT), they may not be quantified.
3266</P>
3267<P>
3268Since these verbs are specifically related to backtracking, most of them can be
3269used only when the pattern is to be matched using the traditional matching
3270function, because that uses a backtracking algorithm. With the exception of
3271(*FAIL), which behaves like a failing negative assertion, the backtracking
3272control verbs cause an error if encountered by the DFA matching function.
3273</P>
3274<P>
3275The behaviour of these verbs in
3276<a href="#btrepeat">repeated groups,</a>
3277<a href="#btassert">assertions,</a>
3278and in
3279<a href="#btsub">capture groups called as subroutines</a>
3280(whether or not recursively) is documented below.
3281<a name="nooptimize"></a></P>
3282<br><b>
3283Optimizations that affect backtracking verbs
3284</b><br>
3285<P>
3286PCRE2 contains some optimizations that are used to speed up matching by running
3287some checks at the start of each match attempt. For example, it may know the
3288minimum length of matching subject, or that a particular character must be
3289present. When one of these optimizations bypasses the running of a match, any
3290included backtracking verbs will not, of course, be processed. You can suppress
3291the start-of-match optimizations by setting the PCRE2_NO_START_OPTIMIZE option
3292when calling <b>pcre2_compile()</b>, or by starting the pattern with
3293(*NO_START_OPT). There is more discussion of this option in the section
3294entitled
3295<a href="pcre2api.html#compiling">"Compiling a pattern"</a>
3296in the
3297<a href="pcre2api.html"><b>pcre2api</b></a>
3298documentation.
3299</P>
3300<P>
3301Experiments with Perl suggest that it too has similar optimizations, and like
3302PCRE2, turning them off can change the result of a match.
3303<a name="acceptverb"></a></P>
3304<br><b>
3305Verbs that act immediately
3306</b><br>
3307<P>
3308The following verbs act as soon as they are encountered.
3309<pre>
3310   (*ACCEPT) or (*ACCEPT:NAME)
3311</pre>
3312This verb causes the match to end successfully, skipping the remainder of the
3313pattern. However, when it is inside a capture group that is called as a
3314subroutine, only that group is ended successfully. Matching then continues
3315at the outer level. If (*ACCEPT) in triggered in a positive assertion, the
3316assertion succeeds; in a negative assertion, the assertion fails.
3317</P>
3318<P>
3319If (*ACCEPT) is inside capturing parentheses, the data so far is captured. For
3320example:
3321<pre>
3322  A((?:A|B(*ACCEPT)|C)D)
3323</pre>
3324This matches "AB", "AAD", or "ACD"; when it matches "AB", "B" is captured by
3325the outer parentheses.
3326</P>
3327<P>
3328(*ACCEPT) is the only backtracking verb that is allowed to be quantified
3329because an ungreedy quantification with a minimum of zero acts only when a
3330backtrack happens. Consider, for example,
3331<pre>
3332  (A(*ACCEPT)??B)C
3333</pre>
3334where A, B, and C may be complex expressions. After matching "A", the matcher
3335processes "BC"; if that fails, causing a backtrack, (*ACCEPT) is triggered and
3336the match succeeds. In both cases, all but C is captured. Whereas (*COMMIT)
3337(see below) means "fail on backtrack", a repeated (*ACCEPT) of this type means
3338"succeed on backtrack".
3339</P>
3340<P>
3341<b>Warning:</b> (*ACCEPT) should not be used within a script run group, because
3342it causes an immediate exit from the group, bypassing the script run checking.
3343<pre>
3344  (*FAIL) or (*FAIL:NAME)
3345</pre>
3346This verb causes a matching failure, forcing backtracking to occur. It may be
3347abbreviated to (*F). It is equivalent to (?!) but easier to read. The Perl
3348documentation notes that it is probably useful only when combined with (?{}) or
3349(??{}). Those are, of course, Perl features that are not present in PCRE2. The
3350nearest equivalent is the callout feature, as for example in this pattern:
3351<pre>
3352  a+(?C)(*FAIL)
3353</pre>
3354A match with the string "aaaa" always fails, but the callout is taken before
3355each backtrack happens (in this example, 10 times).
3356</P>
3357<P>
3358(*ACCEPT:NAME) and (*FAIL:NAME) behave the same as (*MARK:NAME)(*ACCEPT) and
3359(*MARK:NAME)(*FAIL), respectively, that is, a (*MARK) is recorded just before
3360the verb acts.
3361</P>
3362<br><b>
3363Recording which path was taken
3364</b><br>
3365<P>
3366There is one verb whose main purpose is to track how a match was arrived at,
3367though it also has a secondary use in conjunction with advancing the match
3368starting point (see (*SKIP) below).
3369<pre>
3370  (*MARK:NAME) or (*:NAME)
3371</pre>
3372A name is always required with this verb. For all the other backtracking
3373control verbs, a NAME argument is optional.
3374</P>
3375<P>
3376When a match succeeds, the name of the last-encountered mark name on the
3377matching path is passed back to the caller as described in the section entitled
3378<a href="pcre2api.html#matchotherdata">"Other information about the match"</a>
3379in the
3380<a href="pcre2api.html"><b>pcre2api</b></a>
3381documentation. This applies to all instances of (*MARK) and other verbs,
3382including those inside assertions and atomic groups. However, there are
3383differences in those cases when (*MARK) is used in conjunction with (*SKIP) as
3384described below.
3385</P>
3386<P>
3387The mark name that was last encountered on the matching path is passed back. A
3388verb without a NAME argument is ignored for this purpose. Here is an example of
3389<b>pcre2test</b> output, where the "mark" modifier requests the retrieval and
3390outputting of (*MARK) data:
3391<pre>
3392    re&#62; /X(*MARK:A)Y|X(*MARK:B)Z/mark
3393  data&#62; XY
3394   0: XY
3395  MK: A
3396  XZ
3397   0: XZ
3398  MK: B
3399</pre>
3400The (*MARK) name is tagged with "MK:" in this output, and in this example it
3401indicates which of the two alternatives matched. This is a more efficient way
3402of obtaining this information than putting each alternative in its own
3403capturing parentheses.
3404</P>
3405<P>
3406If a verb with a name is encountered in a positive assertion that is true, the
3407name is recorded and passed back if it is the last-encountered. This does not
3408happen for negative assertions or failing positive assertions.
3409</P>
3410<P>
3411After a partial match or a failed match, the last encountered name in the
3412entire match process is returned. For example:
3413<pre>
3414    re&#62; /X(*MARK:A)Y|X(*MARK:B)Z/mark
3415  data&#62; XP
3416  No match, mark = B
3417</pre>
3418Note that in this unanchored example the mark is retained from the match
3419attempt that started at the letter "X" in the subject. Subsequent match
3420attempts starting at "P" and then with an empty string do not get as far as the
3421(*MARK) item, but nevertheless do not reset it.
3422</P>
3423<P>
3424If you are interested in (*MARK) values after failed matches, you should
3425probably set the PCRE2_NO_START_OPTIMIZE option
3426<a href="#nooptimize">(see above)</a>
3427to ensure that the match is always attempted.
3428</P>
3429<br><b>
3430Verbs that act after backtracking
3431</b><br>
3432<P>
3433The following verbs do nothing when they are encountered. Matching continues
3434with what follows, but if there is a subsequent match failure, causing a
3435backtrack to the verb, a failure is forced. That is, backtracking cannot pass
3436to the left of the verb. However, when one of these verbs appears inside an
3437atomic group or in a lookaround assertion that is true, its effect is confined
3438to that group, because once the group has been matched, there is never any
3439backtracking into it. Backtracking from beyond an assertion or an atomic group
3440ignores the entire group, and seeks a preceding backtracking point.
3441</P>
3442<P>
3443These verbs differ in exactly what kind of failure occurs when backtracking
3444reaches them. The behaviour described below is what happens when the verb is
3445not in a subroutine or an assertion. Subsequent sections cover these special
3446cases.
3447<pre>
3448  (*COMMIT) or (*COMMIT:NAME)
3449</pre>
3450This verb causes the whole match to fail outright if there is a later matching
3451failure that causes backtracking to reach it. Even if the pattern is
3452unanchored, no further attempts to find a match by advancing the starting point
3453take place. If (*COMMIT) is the only backtracking verb that is encountered,
3454once it has been passed <b>pcre2_match()</b> is committed to finding a match at
3455the current starting point, or not at all. For example:
3456<pre>
3457  a+(*COMMIT)b
3458</pre>
3459This matches "xxaab" but not "aacaab". It can be thought of as a kind of
3460dynamic anchor, or "I've started, so I must finish."
3461</P>
3462<P>
3463The behaviour of (*COMMIT:NAME) is not the same as (*MARK:NAME)(*COMMIT). It is
3464like (*MARK:NAME) in that the name is remembered for passing back to the
3465caller. However, (*SKIP:NAME) searches only for names that are set with
3466(*MARK), ignoring those set by any of the other backtracking verbs.
3467</P>
3468<P>
3469If there is more than one backtracking verb in a pattern, a different one that
3470follows (*COMMIT) may be triggered first, so merely passing (*COMMIT) during a
3471match does not always guarantee that a match must be at this starting point.
3472</P>
3473<P>
3474Note that (*COMMIT) at the start of a pattern is not the same as an anchor,
3475unless PCRE2's start-of-match optimizations are turned off, as shown in this
3476output from <b>pcre2test</b>:
3477<pre>
3478    re&#62; /(*COMMIT)abc/
3479  data&#62; xyzabc
3480   0: abc
3481  data&#62;
3482  re&#62; /(*COMMIT)abc/no_start_optimize
3483  data&#62; xyzabc
3484  No match
3485</pre>
3486For the first pattern, PCRE2 knows that any match must start with "a", so the
3487optimization skips along the subject to "a" before applying the pattern to the
3488first set of data. The match attempt then succeeds. The second pattern disables
3489the optimization that skips along to the first character. The pattern is now
3490applied starting at "x", and so the (*COMMIT) causes the match to fail without
3491trying any other starting points.
3492<pre>
3493  (*PRUNE) or (*PRUNE:NAME)
3494</pre>
3495This verb causes the match to fail at the current starting position in the
3496subject if there is a later matching failure that causes backtracking to reach
3497it. If the pattern is unanchored, the normal "bumpalong" advance to the next
3498starting character then happens. Backtracking can occur as usual to the left of
3499(*PRUNE), before it is reached, or when matching to the right of (*PRUNE), but
3500if there is no match to the right, backtracking cannot cross (*PRUNE). In
3501simple cases, the use of (*PRUNE) is just an alternative to an atomic group or
3502possessive quantifier, but there are some uses of (*PRUNE) that cannot be
3503expressed in any other way. In an anchored pattern (*PRUNE) has the same effect
3504as (*COMMIT).
3505</P>
3506<P>
3507The behaviour of (*PRUNE:NAME) is not the same as (*MARK:NAME)(*PRUNE). It is
3508like (*MARK:NAME) in that the name is remembered for passing back to the
3509caller. However, (*SKIP:NAME) searches only for names set with (*MARK),
3510ignoring those set by other backtracking verbs.
3511<pre>
3512  (*SKIP)
3513</pre>
3514This verb, when given without a name, is like (*PRUNE), except that if the
3515pattern is unanchored, the "bumpalong" advance is not to the next character,
3516but to the position in the subject where (*SKIP) was encountered. (*SKIP)
3517signifies that whatever text was matched leading up to it cannot be part of a
3518successful match if there is a later mismatch. Consider:
3519<pre>
3520  a+(*SKIP)b
3521</pre>
3522If the subject is "aaaac...", after the first match attempt fails (starting at
3523the first character in the string), the starting point skips on to start the
3524next attempt at "c". Note that a possessive quantifier does not have the same
3525effect as this example; although it would suppress backtracking during the
3526first match attempt, the second attempt would start at the second character
3527instead of skipping on to "c".
3528</P>
3529<P>
3530If (*SKIP) is used to specify a new starting position that is the same as the
3531starting position of the current match, or (by being inside a lookbehind)
3532earlier, the position specified by (*SKIP) is ignored, and instead the normal
3533"bumpalong" occurs.
3534<pre>
3535  (*SKIP:NAME)
3536</pre>
3537When (*SKIP) has an associated name, its behaviour is modified. When such a
3538(*SKIP) is triggered, the previous path through the pattern is searched for the
3539most recent (*MARK) that has the same name. If one is found, the "bumpalong"
3540advance is to the subject position that corresponds to that (*MARK) instead of
3541to where (*SKIP) was encountered. If no (*MARK) with a matching name is found,
3542the (*SKIP) is ignored.
3543</P>
3544<P>
3545The search for a (*MARK) name uses the normal backtracking mechanism, which
3546means that it does not see (*MARK) settings that are inside atomic groups or
3547assertions, because they are never re-entered by backtracking. Compare the
3548following <b>pcre2test</b> examples:
3549<pre>
3550    re&#62; /a(?&#62;(*MARK:X))(*SKIP:X)(*F)|(.)/
3551  data: abc
3552   0: a
3553   1: a
3554  data:
3555    re&#62; /a(?:(*MARK:X))(*SKIP:X)(*F)|(.)/
3556  data: abc
3557   0: b
3558   1: b
3559</pre>
3560In the first example, the (*MARK) setting is in an atomic group, so it is not
3561seen when (*SKIP:X) triggers, causing the (*SKIP) to be ignored. This allows
3562the second branch of the pattern to be tried at the first character position.
3563In the second example, the (*MARK) setting is not in an atomic group. This
3564allows (*SKIP:X) to find the (*MARK) when it backtracks, and this causes a new
3565matching attempt to start at the second character. This time, the (*MARK) is
3566never seen because "a" does not match "b", so the matcher immediately jumps to
3567the second branch of the pattern.
3568</P>
3569<P>
3570Note that (*SKIP:NAME) searches only for names set by (*MARK:NAME). It ignores
3571names that are set by other backtracking verbs.
3572<pre>
3573  (*THEN) or (*THEN:NAME)
3574</pre>
3575This verb causes a skip to the next innermost alternative when backtracking
3576reaches it. That is, it cancels any further backtracking within the current
3577alternative. Its name comes from the observation that it can be used for a
3578pattern-based if-then-else block:
3579<pre>
3580  ( COND1 (*THEN) FOO | COND2 (*THEN) BAR | COND3 (*THEN) BAZ ) ...
3581</pre>
3582If the COND1 pattern matches, FOO is tried (and possibly further items after
3583the end of the group if FOO succeeds); on failure, the matcher skips to the
3584second alternative and tries COND2, without backtracking into COND1. If that
3585succeeds and BAR fails, COND3 is tried. If subsequently BAZ fails, there are no
3586more alternatives, so there is a backtrack to whatever came before the entire
3587group. If (*THEN) is not inside an alternation, it acts like (*PRUNE).
3588</P>
3589<P>
3590The behaviour of (*THEN:NAME) is not the same as (*MARK:NAME)(*THEN). It is
3591like (*MARK:NAME) in that the name is remembered for passing back to the
3592caller. However, (*SKIP:NAME) searches only for names set with (*MARK),
3593ignoring those set by other backtracking verbs.
3594</P>
3595<P>
3596A group that does not contain a | character is just a part of the enclosing
3597alternative; it is not a nested alternation with only one alternative. The
3598effect of (*THEN) extends beyond such a group to the enclosing alternative.
3599Consider this pattern, where A, B, etc. are complex pattern fragments that do
3600not contain any | characters at this level:
3601<pre>
3602  A (B(*THEN)C) | D
3603</pre>
3604If A and B are matched, but there is a failure in C, matching does not
3605backtrack into A; instead it moves to the next alternative, that is, D.
3606However, if the group containing (*THEN) is given an alternative, it
3607behaves differently:
3608<pre>
3609  A (B(*THEN)C | (*FAIL)) | D
3610</pre>
3611The effect of (*THEN) is now confined to the inner group. After a failure in C,
3612matching moves to (*FAIL), which causes the whole group to fail because there
3613are no more alternatives to try. In this case, matching does backtrack into A.
3614</P>
3615<P>
3616Note that a conditional group is not considered as having two alternatives,
3617because only one is ever used. In other words, the | character in a conditional
3618group has a different meaning. Ignoring white space, consider:
3619<pre>
3620  ^.*? (?(?=a) a | b(*THEN)c )
3621</pre>
3622If the subject is "ba", this pattern does not match. Because .*? is ungreedy,
3623it initially matches zero characters. The condition (?=a) then fails, the
3624character "b" is matched, but "c" is not. At this point, matching does not
3625backtrack to .*? as might perhaps be expected from the presence of the |
3626character. The conditional group is part of the single alternative that
3627comprises the whole pattern, and so the match fails. (If there was a backtrack
3628into .*?, allowing it to match "b", the match would succeed.)
3629</P>
3630<P>
3631The verbs just described provide four different "strengths" of control when
3632subsequent matching fails. (*THEN) is the weakest, carrying on the match at the
3633next alternative. (*PRUNE) comes next, failing the match at the current
3634starting position, but allowing an advance to the next character (for an
3635unanchored pattern). (*SKIP) is similar, except that the advance may be more
3636than one character. (*COMMIT) is the strongest, causing the entire match to
3637fail.
3638</P>
3639<br><b>
3640More than one backtracking verb
3641</b><br>
3642<P>
3643If more than one backtracking verb is present in a pattern, the one that is
3644backtracked onto first acts. For example, consider this pattern, where A, B,
3645etc. are complex pattern fragments:
3646<pre>
3647  (A(*COMMIT)B(*THEN)C|ABD)
3648</pre>
3649If A matches but B fails, the backtrack to (*COMMIT) causes the entire match to
3650fail. However, if A and B match, but C fails, the backtrack to (*THEN) causes
3651the next alternative (ABD) to be tried. This behaviour is consistent, but is
3652not always the same as Perl's. It means that if two or more backtracking verbs
3653appear in succession, all the the last of them has no effect. Consider this
3654example:
3655<pre>
3656  ...(*COMMIT)(*PRUNE)...
3657</pre>
3658If there is a matching failure to the right, backtracking onto (*PRUNE) causes
3659it to be triggered, and its action is taken. There can never be a backtrack
3660onto (*COMMIT).
3661<a name="btrepeat"></a></P>
3662<br><b>
3663Backtracking verbs in repeated groups
3664</b><br>
3665<P>
3666PCRE2 sometimes differs from Perl in its handling of backtracking verbs in
3667repeated groups. For example, consider:
3668<pre>
3669  /(a(*COMMIT)b)+ac/
3670</pre>
3671If the subject is "abac", Perl matches unless its optimizations are disabled,
3672but PCRE2 always fails because the (*COMMIT) in the second repeat of the group
3673acts.
3674<a name="btassert"></a></P>
3675<br><b>
3676Backtracking verbs in assertions
3677</b><br>
3678<P>
3679(*FAIL) in any assertion has its normal effect: it forces an immediate
3680backtrack. The behaviour of the other backtracking verbs depends on whether or
3681not the assertion is standalone or acting as the condition in a conditional
3682group.
3683</P>
3684<P>
3685(*ACCEPT) in a standalone positive assertion causes the assertion to succeed
3686without any further processing; captured strings and a mark name (if set) are
3687retained. In a standalone negative assertion, (*ACCEPT) causes the assertion to
3688fail without any further processing; captured substrings and any mark name are
3689discarded.
3690</P>
3691<P>
3692If the assertion is a condition, (*ACCEPT) causes the condition to be true for
3693a positive assertion and false for a negative one; captured substrings are
3694retained in both cases.
3695</P>
3696<P>
3697The remaining verbs act only when a later failure causes a backtrack to
3698reach them. This means that, for the Perl-compatible assertions, their effect
3699is confined to the assertion, because Perl lookaround assertions are atomic. A
3700backtrack that occurs after such an assertion is complete does not jump back
3701into the assertion. Note in particular that a (*MARK) name that is set in an
3702assertion is not "seen" by an instance of (*SKIP:NAME) later in the pattern.
3703</P>
3704<P>
3705PCRE2 now supports non-atomic positive assertions, as described in the section
3706entitled
3707<a href="#nonatomicassertions">"Non-atomic assertions"</a>
3708above. These assertions must be standalone (not used as conditions). They are
3709not Perl-compatible. For these assertions, a later backtrack does jump back
3710into the assertion, and therefore verbs such as (*COMMIT) can be triggered by
3711backtracks from later in the pattern.
3712</P>
3713<P>
3714The effect of (*THEN) is not allowed to escape beyond an assertion. If there
3715are no more branches to try, (*THEN) causes a positive assertion to be false,
3716and a negative assertion to be true.
3717</P>
3718<P>
3719The other backtracking verbs are not treated specially if they appear in a
3720standalone positive assertion. In a conditional positive assertion,
3721backtracking (from within the assertion) into (*COMMIT), (*SKIP), or (*PRUNE)
3722causes the condition to be false. However, for both standalone and conditional
3723negative assertions, backtracking into (*COMMIT), (*SKIP), or (*PRUNE) causes
3724the assertion to be true, without considering any further alternative branches.
3725<a name="btsub"></a></P>
3726<br><b>
3727Backtracking verbs in subroutines
3728</b><br>
3729<P>
3730These behaviours occur whether or not the group is called recursively.
3731</P>
3732<P>
3733(*ACCEPT) in a group called as a subroutine causes the subroutine match to
3734succeed without any further processing. Matching then continues after the
3735subroutine call. Perl documents this behaviour. Perl's treatment of the other
3736verbs in subroutines is different in some cases.
3737</P>
3738<P>
3739(*FAIL) in a group called as a subroutine has its normal effect: it forces
3740an immediate backtrack.
3741</P>
3742<P>
3743(*COMMIT), (*SKIP), and (*PRUNE) cause the subroutine match to fail when
3744triggered by being backtracked to in a group called as a subroutine. There is
3745then a backtrack at the outer level.
3746</P>
3747<P>
3748(*THEN), when triggered, skips to the next alternative in the innermost
3749enclosing group that has alternatives (its normal behaviour). However, if there
3750is no such group within the subroutine's group, the subroutine match fails and
3751there is a backtrack at the outer level.
3752</P>
3753<br><a name="SEC30" href="#TOC1">SEE ALSO</a><br>
3754<P>
3755<b>pcre2api</b>(3), <b>pcre2callout</b>(3), <b>pcre2matching</b>(3),
3756<b>pcre2syntax</b>(3), <b>pcre2</b>(3).
3757</P>
3758<br><a name="SEC31" href="#TOC1">AUTHOR</a><br>
3759<P>
3760Philip Hazel
3761<br>
3762Retired from University Computing Service
3763<br>
3764Cambridge, England.
3765<br>
3766</P>
3767<br><a name="SEC32" href="#TOC1">REVISION</a><br>
3768<P>
3769Last updated: 12 January 2022
3770<br>
3771Copyright &copy; 1997-2022 University of Cambridge.
3772<br>
3773<p>
3774Return to the <a href="index.html">PCRE2 index page</a>.
3775</p>
3776