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