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