ViewVC logotype

Contents of /code/trunk/doc/html/pcrepattern.html

Parent Directory Parent Directory | Revision Log Revision Log

Revision 518 - (show annotations)
Tue May 18 15:47:01 2010 UTC (9 years, 3 months ago) by ph10
File MIME type: text/html
File size: 110993 byte(s)
Added PCRE_UCP and related stuff to make \w etc use Unicode properties.
1 <html>
2 <head>
3 <title>pcrepattern specification</title>
4 </head>
5 <body bgcolor="#FFFFFF" text="#00005A" link="#0066FF" alink="#3399FF" vlink="#2222BB">
6 <h1>pcrepattern man page</h1>
7 <p>
8 Return to the <a href="index.html">PCRE index page</a>.
9 </p>
10 <p>
11 This page is part of the PCRE HTML documentation. It was generated automatically
12 from the original man page. If there is any nonsense in it, please consult the
13 man page, in case the conversion went wrong.
14 <br>
15 <ul>
16 <li><a name="TOC1" href="#SEC1">PCRE REGULAR EXPRESSION DETAILS</a>
17 <li><a name="TOC2" href="#SEC2">NEWLINE CONVENTIONS</a>
18 <li><a name="TOC3" href="#SEC3">CHARACTERS AND METACHARACTERS</a>
19 <li><a name="TOC4" href="#SEC4">BACKSLASH</a>
20 <li><a name="TOC5" href="#SEC5">CIRCUMFLEX AND DOLLAR</a>
21 <li><a name="TOC6" href="#SEC6">FULL STOP (PERIOD, DOT) AND \N</a>
22 <li><a name="TOC7" href="#SEC7">MATCHING A SINGLE BYTE</a>
24 <li><a name="TOC9" href="#SEC9">POSIX CHARACTER CLASSES</a>
25 <li><a name="TOC10" href="#SEC10">VERTICAL BAR</a>
26 <li><a name="TOC11" href="#SEC11">INTERNAL OPTION SETTING</a>
27 <li><a name="TOC12" href="#SEC12">SUBPATTERNS</a>
28 <li><a name="TOC13" href="#SEC13">DUPLICATE SUBPATTERN NUMBERS</a>
29 <li><a name="TOC14" href="#SEC14">NAMED SUBPATTERNS</a>
30 <li><a name="TOC15" href="#SEC15">REPETITION</a>
32 <li><a name="TOC17" href="#SEC17">BACK REFERENCES</a>
33 <li><a name="TOC18" href="#SEC18">ASSERTIONS</a>
34 <li><a name="TOC19" href="#SEC19">CONDITIONAL SUBPATTERNS</a>
35 <li><a name="TOC20" href="#SEC20">COMMENTS</a>
36 <li><a name="TOC21" href="#SEC21">RECURSIVE PATTERNS</a>
37 <li><a name="TOC22" href="#SEC22">SUBPATTERNS AS SUBROUTINES</a>
38 <li><a name="TOC23" href="#SEC23">ONIGURUMA SUBROUTINE SYNTAX</a>
39 <li><a name="TOC24" href="#SEC24">CALLOUTS</a>
40 <li><a name="TOC25" href="#SEC25">BACKTRACKING CONTROL</a>
41 <li><a name="TOC26" href="#SEC26">SEE ALSO</a>
42 <li><a name="TOC27" href="#SEC27">AUTHOR</a>
43 <li><a name="TOC28" href="#SEC28">REVISION</a>
44 </ul>
45 <br><a name="SEC1" href="#TOC1">PCRE REGULAR EXPRESSION DETAILS</a><br>
46 <P>
47 The syntax and semantics of the regular expressions that are supported by PCRE
48 are described in detail below. There is a quick-reference syntax summary in the
49 <a href="pcresyntax.html"><b>pcresyntax</b></a>
50 page. PCRE tries to match Perl syntax and semantics as closely as it can. PCRE
51 also supports some alternative regular expression syntax (which does not
52 conflict with the Perl syntax) in order to provide some compatibility with
53 regular expressions in Python, .NET, and Oniguruma.
54 </P>
55 <P>
56 Perl's regular expressions are described in its own documentation, and
57 regular expressions in general are covered in a number of books, some of which
58 have copious examples. Jeffrey Friedl's "Mastering Regular Expressions",
59 published by O'Reilly, covers regular expressions in great detail. This
60 description of PCRE's regular expressions is intended as reference material.
61 </P>
62 <P>
63 The original operation of PCRE was on strings of one-byte characters. However,
64 there is now also support for UTF-8 character strings. To use this,
65 PCRE must be built to include UTF-8 support, and you must call
66 <b>pcre_compile()</b> or <b>pcre_compile2()</b> with the PCRE_UTF8 option. There
67 is also a special sequence that can be given at the start of a pattern:
68 <pre>
69 (*UTF8)
70 </pre>
71 Starting a pattern with this sequence is equivalent to setting the PCRE_UTF8
72 option. This feature is not Perl-compatible. How setting UTF-8 mode affects
73 pattern matching is mentioned in several places below. There is also a summary
74 of UTF-8 features in the
75 <a href="pcre.html#utf8support">section on UTF-8 support</a>
76 in the main
77 <a href="pcre.html"><b>pcre</b></a>
78 page.
79 </P>
80 <P>
81 The remainder of this document discusses the patterns that are supported by
82 PCRE when its main matching function, <b>pcre_exec()</b>, is used.
83 From release 6.0, PCRE offers a second matching function,
84 <b>pcre_dfa_exec()</b>, which matches using a different algorithm that is not
85 Perl-compatible. Some of the features discussed below are not available when
86 <b>pcre_dfa_exec()</b> is used. The advantages and disadvantages of the
87 alternative function, and how it differs from the normal function, are
88 discussed in the
89 <a href="pcrematching.html"><b>pcrematching</b></a>
90 page.
91 </P>
92 <br><a name="SEC2" href="#TOC1">NEWLINE CONVENTIONS</a><br>
93 <P>
94 PCRE supports five different conventions for indicating line breaks in
95 strings: a single CR (carriage return) character, a single LF (linefeed)
96 character, the two-character sequence CRLF, any of the three preceding, or any
97 Unicode newline sequence. The
98 <a href="pcreapi.html"><b>pcreapi</b></a>
99 page has
100 <a href="pcreapi.html#newlines">further discussion</a>
101 about newlines, and shows how to set the newline convention in the
102 <i>options</i> arguments for the compiling and matching functions.
103 </P>
104 <P>
105 It is also possible to specify a newline convention by starting a pattern
106 string with one of the following five sequences:
107 <pre>
108 (*CR) carriage return
109 (*LF) linefeed
110 (*CRLF) carriage return, followed by linefeed
111 (*ANYCRLF) any of the three above
112 (*ANY) all Unicode newline sequences
113 </pre>
114 These override the default and the options given to <b>pcre_compile()</b> or
115 <b>pcre_compile2()</b>. For example, on a Unix system where LF is the default
116 newline sequence, the pattern
117 <pre>
118 (*CR)a.b
119 </pre>
120 changes the convention to CR. That pattern matches "a\nb" because LF is no
121 longer a newline. Note that these special settings, which are not
122 Perl-compatible, are recognized only at the very start of a pattern, and that
123 they must be in upper case. If more than one of them is present, the last one
124 is used.
125 </P>
126 <P>
127 The newline convention affects the interpretation of the dot metacharacter when
128 PCRE_DOTALL is not set, and also the behaviour of \N. However, it does not
129 affect what the \R escape sequence matches. By default, this is any Unicode
130 newline sequence, for Perl compatibility. However, this can be changed; see the
131 description of \R in the section entitled
132 <a href="#newlineseq">"Newline sequences"</a>
133 below. A change of \R setting can be combined with a change of newline
134 convention.
135 </P>
136 <br><a name="SEC3" href="#TOC1">CHARACTERS AND METACHARACTERS</a><br>
137 <P>
138 A regular expression is a pattern that is matched against a subject string from
139 left to right. Most characters stand for themselves in a pattern, and match the
140 corresponding characters in the subject. As a trivial example, the pattern
141 <pre>
142 The quick brown fox
143 </pre>
144 matches a portion of a subject string that is identical to itself. When
145 caseless matching is specified (the PCRE_CASELESS option), letters are matched
146 independently of case. In UTF-8 mode, PCRE always understands the concept of
147 case for characters whose values are less than 128, so caseless matching is
148 always possible. For characters with higher values, the concept of case is
149 supported if PCRE is compiled with Unicode property support, but not otherwise.
150 If you want to use caseless matching for characters 128 and above, you must
151 ensure that PCRE is compiled with Unicode property support as well as with
152 UTF-8 support.
153 </P>
154 <P>
155 The power of regular expressions comes from the ability to include alternatives
156 and repetitions in the pattern. These are encoded in the pattern by the use of
157 <i>metacharacters</i>, which do not stand for themselves but instead are
158 interpreted in some special way.
159 </P>
160 <P>
161 There are two different sets of metacharacters: those that are recognized
162 anywhere in the pattern except within square brackets, and those that are
163 recognized within square brackets. Outside square brackets, the metacharacters
164 are as follows:
165 <pre>
166 \ general escape character with several uses
167 ^ assert start of string (or line, in multiline mode)
168 $ assert end of string (or line, in multiline mode)
169 . match any character except newline (by default)
170 [ start character class definition
171 | start of alternative branch
172 ( start subpattern
173 ) end subpattern
174 ? extends the meaning of (
175 also 0 or 1 quantifier
176 also quantifier minimizer
177 * 0 or more quantifier
178 + 1 or more quantifier
179 also "possessive quantifier"
180 { start min/max quantifier
181 </pre>
182 Part of a pattern that is in square brackets is called a "character class". In
183 a character class the only metacharacters are:
184 <pre>
185 \ general escape character
186 ^ negate the class, but only if the first character
187 - indicates character range
188 [ POSIX character class (only if followed by POSIX syntax)
189 ] terminates the character class
190 </pre>
191 The following sections describe the use of each of the metacharacters.
192 </P>
193 <br><a name="SEC4" href="#TOC1">BACKSLASH</a><br>
194 <P>
195 The backslash character has several uses. Firstly, if it is followed by a
196 non-alphanumeric character, it takes away any special meaning that character
197 may have. This use of backslash as an escape character applies both inside and
198 outside character classes.
199 </P>
200 <P>
201 For example, if you want to match a * character, you write \* in the pattern.
202 This escaping action applies whether or not the following character would
203 otherwise be interpreted as a metacharacter, so it is always safe to precede a
204 non-alphanumeric with backslash to specify that it stands for itself. In
205 particular, if you want to match a backslash, you write \\.
206 </P>
207 <P>
208 If a pattern is compiled with the PCRE_EXTENDED option, whitespace in the
209 pattern (other than in a character class) and characters between a # outside
210 a character class and the next newline are ignored. An escaping backslash can
211 be used to include a whitespace or # character as part of the pattern.
212 </P>
213 <P>
214 If you want to remove the special meaning from a sequence of characters, you
215 can do so by putting them between \Q and \E. This is different from Perl in
216 that $ and @ are handled as literals in \Q...\E sequences in PCRE, whereas in
217 Perl, $ and @ cause variable interpolation. Note the following examples:
218 <pre>
219 Pattern PCRE matches Perl matches
221 \Qabc$xyz\E abc$xyz abc followed by the contents of $xyz
222 \Qabc\$xyz\E abc\$xyz abc\$xyz
223 \Qabc\E\$\Qxyz\E abc$xyz abc$xyz
224 </pre>
225 The \Q...\E sequence is recognized both inside and outside character classes.
226 <a name="digitsafterbackslash"></a></P>
227 <br><b>
228 Non-printing characters
229 </b><br>
230 <P>
231 A second use of backslash provides a way of encoding non-printing characters
232 in patterns in a visible manner. There is no restriction on the appearance of
233 non-printing characters, apart from the binary zero that terminates a pattern,
234 but when a pattern is being prepared by text editing, it is often easier to use
235 one of the following escape sequences than the binary character it represents:
236 <pre>
237 \a alarm, that is, the BEL character (hex 07)
238 \cx "control-x", where x is any character
239 \e escape (hex 1B)
240 \f formfeed (hex 0C)
241 \n linefeed (hex 0A)
242 \r carriage return (hex 0D)
243 \t tab (hex 09)
244 \ddd character with octal code ddd, or back reference
245 \xhh character with hex code hh
246 \x{hhh..} character with hex code hhh..
247 </pre>
248 The precise effect of \cx is as follows: if x is a lower case letter, it
249 is converted to upper case. Then bit 6 of the character (hex 40) is inverted.
250 Thus \cz becomes hex 1A, but \c{ becomes hex 3B, while \c; becomes hex
251 7B.
252 </P>
253 <P>
254 After \x, from zero to two hexadecimal digits are read (letters can be in
255 upper or lower case). Any number of hexadecimal digits may appear between \x{
256 and }, but the value of the character code must be less than 256 in non-UTF-8
257 mode, and less than 2**31 in UTF-8 mode. That is, the maximum value in
258 hexadecimal is 7FFFFFFF. Note that this is bigger than the largest Unicode code
259 point, which is 10FFFF.
260 </P>
261 <P>
262 If characters other than hexadecimal digits appear between \x{ and }, or if
263 there is no terminating }, this form of escape is not recognized. Instead, the
264 initial \x will be interpreted as a basic hexadecimal escape, with no
265 following digits, giving a character whose value is zero.
266 </P>
267 <P>
268 Characters whose value is less than 256 can be defined by either of the two
269 syntaxes for \x. There is no difference in the way they are handled. For
270 example, \xdc is exactly the same as \x{dc}.
271 </P>
272 <P>
273 After \0 up to two further octal digits are read. If there are fewer than two
274 digits, just those that are present are used. Thus the sequence \0\x\07
275 specifies two binary zeros followed by a BEL character (code value 7). Make
276 sure you supply two digits after the initial zero if the pattern character that
277 follows is itself an octal digit.
278 </P>
279 <P>
280 The handling of a backslash followed by a digit other than 0 is complicated.
281 Outside a character class, PCRE reads it and any following digits as a decimal
282 number. If the number is less than 10, or if there have been at least that many
283 previous capturing left parentheses in the expression, the entire sequence is
284 taken as a <i>back reference</i>. A description of how this works is given
285 <a href="#backreferences">later,</a>
286 following the discussion of
287 <a href="#subpattern">parenthesized subpatterns.</a>
288 </P>
289 <P>
290 Inside a character class, or if the decimal number is greater than 9 and there
291 have not been that many capturing subpatterns, PCRE re-reads up to three octal
292 digits following the backslash, and uses them to generate a data character. Any
293 subsequent digits stand for themselves. In non-UTF-8 mode, the value of a
294 character specified in octal must be less than \400. In UTF-8 mode, values up
295 to \777 are permitted. For example:
296 <pre>
297 \040 is another way of writing a space
298 \40 is the same, provided there are fewer than 40 previous capturing subpatterns
299 \7 is always a back reference
300 \11 might be a back reference, or another way of writing a tab
301 \011 is always a tab
302 \0113 is a tab followed by the character "3"
303 \113 might be a back reference, otherwise the character with octal code 113
304 \377 might be a back reference, otherwise the byte consisting entirely of 1 bits
305 \81 is either a back reference, or a binary zero followed by the two characters "8" and "1"
306 </pre>
307 Note that octal values of 100 or greater must not be introduced by a leading
308 zero, because no more than three octal digits are ever read.
309 </P>
310 <P>
311 All the sequences that define a single character value can be used both inside
312 and outside character classes. In addition, inside a character class, the
313 sequence \b is interpreted as the backspace character (hex 08). The sequences
314 \B, \N, \R, and \X are not special inside a character class. Like any other
315 unrecognized escape sequences, they are treated as the literal characters "B",
316 "N", "R", and "X" by default, but cause an error if the PCRE_EXTRA option is
317 set. Outside a character class, these sequences have different meanings.
318 </P>
319 <br><b>
320 Absolute and relative back references
321 </b><br>
322 <P>
323 The sequence \g followed by an unsigned or a negative number, optionally
324 enclosed in braces, is an absolute or relative back reference. A named back
325 reference can be coded as \g{name}. Back references are discussed
326 <a href="#backreferences">later,</a>
327 following the discussion of
328 <a href="#subpattern">parenthesized subpatterns.</a>
329 </P>
330 <br><b>
331 Absolute and relative subroutine calls
332 </b><br>
333 <P>
334 For compatibility with Oniguruma, the non-Perl syntax \g followed by a name or
335 a number enclosed either in angle brackets or single quotes, is an alternative
336 syntax for referencing a subpattern as a "subroutine". Details are discussed
337 <a href="#onigurumasubroutines">later.</a>
338 Note that \g{...} (Perl syntax) and \g&#60;...&#62; (Oniguruma syntax) are <i>not</i>
339 synonymous. The former is a back reference; the latter is a
340 <a href="#subpatternsassubroutines">subroutine</a>
341 call.
342 <a name="genericchartypes"></a></P>
343 <br><b>
344 Generic character types
345 </b><br>
346 <P>
347 Another use of backslash is for specifying generic character types:
348 <pre>
349 \d any decimal digit
350 \D any character that is not a decimal digit
351 \h any horizontal whitespace character
352 \H any character that is not a horizontal whitespace character
353 \s any whitespace character
354 \S any character that is not a whitespace character
355 \v any vertical whitespace character
356 \V any character that is not a vertical whitespace character
357 \w any "word" character
358 \W any "non-word" character
359 </pre>
360 There is also the single sequence \N, which matches a non-newline character.
361 This is the same as
362 <a href="#fullstopdot">the "." metacharacter</a>
363 when PCRE_DOTALL is not set.
364 </P>
365 <P>
366 Each pair of lower and upper case escape sequences partitions the complete set
367 of characters into two disjoint sets. Any given character matches one, and only
368 one, of each pair.
369 </P>
370 <P>
371 These character type sequences can appear both inside and outside character
372 classes. They each match one character of the appropriate type. If the current
373 matching point is at the end of the subject string, all of them fail, since
374 there is no character to match.
375 </P>
376 <P>
377 For compatibility with Perl, \s does not match the VT character (code 11).
378 This makes it different from the the POSIX "space" class. The \s characters
379 are HT (9), LF (10), FF (12), CR (13), and space (32). If "use locale;" is
380 included in a Perl script, \s may match the VT character. In PCRE, it never
381 does.
382 </P>
383 <P>
384 In UTF-8 mode, characters with values greater than 128 never match \d, \s, or
385 \w, and always match \D, \S, and \W. This is true even when Unicode
386 character property support is available. These sequences retain their original
387 meanings from before UTF-8 support was available, mainly for efficiency
388 reasons. Note that this also affects \b, because it is defined in terms of \w
389 and \W.
390 </P>
391 <P>
392 The sequences \h, \H, \v, and \V are Perl 5.10 features. In contrast to the
393 other sequences, these do match certain high-valued codepoints in UTF-8 mode.
394 The horizontal space characters are:
395 <pre>
396 U+0009 Horizontal tab
397 U+0020 Space
398 U+00A0 Non-break space
399 U+1680 Ogham space mark
400 U+180E Mongolian vowel separator
401 U+2000 En quad
402 U+2001 Em quad
403 U+2002 En space
404 U+2003 Em space
405 U+2004 Three-per-em space
406 U+2005 Four-per-em space
407 U+2006 Six-per-em space
408 U+2007 Figure space
409 U+2008 Punctuation space
410 U+2009 Thin space
411 U+200A Hair space
412 U+202F Narrow no-break space
413 U+205F Medium mathematical space
414 U+3000 Ideographic space
415 </pre>
416 The vertical space characters are:
417 <pre>
418 U+000A Linefeed
419 U+000B Vertical tab
420 U+000C Formfeed
421 U+000D Carriage return
422 U+0085 Next line
423 U+2028 Line separator
424 U+2029 Paragraph separator
425 </PRE>
426 </P>
427 <P>
428 A "word" character is an underscore or any character less than 256 that is a
429 letter or digit. The definition of letters and digits is controlled by PCRE's
430 low-valued character tables, and may vary if locale-specific matching is taking
431 place (see
432 <a href="pcreapi.html#localesupport">"Locale support"</a>
433 in the
434 <a href="pcreapi.html"><b>pcreapi</b></a>
435 page). For example, in a French locale such as "fr_FR" in Unix-like systems,
436 or "french" in Windows, some character codes greater than 128 are used for
437 accented letters, and these are matched by \w. The use of locales with Unicode
438 is discouraged.
439 <a name="newlineseq"></a></P>
440 <br><b>
441 Newline sequences
442 </b><br>
443 <P>
444 Outside a character class, by default, the escape sequence \R matches any
445 Unicode newline sequence. This is a Perl 5.10 feature. In non-UTF-8 mode \R is
446 equivalent to the following:
447 <pre>
448 (?&#62;\r\n|\n|\x0b|\f|\r|\x85)
449 </pre>
450 This is an example of an "atomic group", details of which are given
451 <a href="#atomicgroup">below.</a>
452 This particular group matches either the two-character sequence CR followed by
453 LF, or one of the single characters LF (linefeed, U+000A), VT (vertical tab,
454 U+000B), FF (formfeed, U+000C), CR (carriage return, U+000D), or NEL (next
455 line, U+0085). The two-character sequence is treated as a single unit that
456 cannot be split.
457 </P>
458 <P>
459 In UTF-8 mode, two additional characters whose codepoints are greater than 255
460 are added: LS (line separator, U+2028) and PS (paragraph separator, U+2029).
461 Unicode character property support is not needed for these characters to be
462 recognized.
463 </P>
464 <P>
465 It is possible to restrict \R to match only CR, LF, or CRLF (instead of the
466 complete set of Unicode line endings) by setting the option PCRE_BSR_ANYCRLF
467 either at compile time or when the pattern is matched. (BSR is an abbrevation
468 for "backslash R".) This can be made the default when PCRE is built; if this is
469 the case, the other behaviour can be requested via the PCRE_BSR_UNICODE option.
470 It is also possible to specify these settings by starting a pattern string with
471 one of the following sequences:
472 <pre>
473 (*BSR_ANYCRLF) CR, LF, or CRLF only
474 (*BSR_UNICODE) any Unicode newline sequence
475 </pre>
476 These override the default and the options given to <b>pcre_compile()</b> or
477 <b>pcre_compile2()</b>, but they can be overridden by options given to
478 <b>pcre_exec()</b> or <b>pcre_dfa_exec()</b>. Note that these special settings,
479 which are not Perl-compatible, are recognized only at the very start of a
480 pattern, and that they must be in upper case. If more than one of them is
481 present, the last one is used. They can be combined with a change of newline
482 convention, for example, a pattern can start with:
483 <pre>
485 </pre>
486 Inside a character class, \R is treated as an unrecognized escape sequence,
487 and so matches the letter "R" by default, but causes an error if PCRE_EXTRA is
488 set.
489 <a name="uniextseq"></a></P>
490 <br><b>
491 Unicode character properties
492 </b><br>
493 <P>
494 When PCRE is built with Unicode character property support, three additional
495 escape sequences that match characters with specific properties are available.
496 When not in UTF-8 mode, these sequences are of course limited to testing
497 characters whose codepoints are less than 256, but they do work in this mode.
498 The extra escape sequences are:
499 <pre>
500 \p{<i>xx</i>} a character with the <i>xx</i> property
501 \P{<i>xx</i>} a character without the <i>xx</i> property
502 \X an extended Unicode sequence
503 </pre>
504 The property names represented by <i>xx</i> above are limited to the Unicode
505 script names, the general category properties, "Any", which matches any
506 character (including newline), and some special PCRE properties (described
507 in the
508 <a href="#extraprops">next section).</a>
509 Other Perl properties such as "InMusicalSymbols" are not currently supported by
510 PCRE. Note that \P{Any} does not match any characters, so always causes a
511 match failure.
512 </P>
513 <P>
514 Sets of Unicode characters are defined as belonging to certain scripts. A
515 character from one of these sets can be matched using a script name. For
516 example:
517 <pre>
518 \p{Greek}
519 \P{Han}
520 </pre>
521 Those that are not part of an identified script are lumped together as
522 "Common". The current list of scripts is:
523 </P>
524 <P>
525 Arabic,
526 Armenian,
527 Avestan,
528 Balinese,
529 Bamum,
530 Bengali,
531 Bopomofo,
532 Braille,
533 Buginese,
534 Buhid,
535 Canadian_Aboriginal,
536 Carian,
537 Cham,
538 Cherokee,
539 Common,
540 Coptic,
541 Cuneiform,
542 Cypriot,
543 Cyrillic,
544 Deseret,
545 Devanagari,
546 Egyptian_Hieroglyphs,
547 Ethiopic,
548 Georgian,
549 Glagolitic,
550 Gothic,
551 Greek,
552 Gujarati,
553 Gurmukhi,
554 Han,
555 Hangul,
556 Hanunoo,
557 Hebrew,
558 Hiragana,
559 Imperial_Aramaic,
560 Inherited,
561 Inscriptional_Pahlavi,
562 Inscriptional_Parthian,
563 Javanese,
564 Kaithi,
565 Kannada,
566 Katakana,
567 Kayah_Li,
568 Kharoshthi,
569 Khmer,
570 Lao,
571 Latin,
572 Lepcha,
573 Limbu,
574 Linear_B,
575 Lisu,
576 Lycian,
577 Lydian,
578 Malayalam,
579 Meetei_Mayek,
580 Mongolian,
581 Myanmar,
582 New_Tai_Lue,
583 Nko,
584 Ogham,
585 Old_Italic,
586 Old_Persian,
587 Old_South_Arabian,
588 Old_Turkic,
589 Ol_Chiki,
590 Oriya,
591 Osmanya,
592 Phags_Pa,
593 Phoenician,
594 Rejang,
595 Runic,
596 Samaritan,
597 Saurashtra,
598 Shavian,
599 Sinhala,
600 Sundanese,
601 Syloti_Nagri,
602 Syriac,
603 Tagalog,
604 Tagbanwa,
605 Tai_Le,
606 Tai_Tham,
607 Tai_Viet,
608 Tamil,
609 Telugu,
610 Thaana,
611 Thai,
612 Tibetan,
613 Tifinagh,
614 Ugaritic,
615 Vai,
616 Yi.
617 </P>
618 <P>
619 Each character has exactly one Unicode general category property, specified by
620 a two-letter abbreviation. For compatibility with Perl, negation can be
621 specified by including a circumflex between the opening brace and the property
622 name. For example, \p{^Lu} is the same as \P{Lu}.
623 </P>
624 <P>
625 If only one letter is specified with \p or \P, it includes all the general
626 category properties that start with that letter. In this case, in the absence
627 of negation, the curly brackets in the escape sequence are optional; these two
628 examples have the same effect:
629 <pre>
630 \p{L}
631 \pL
632 </pre>
633 The following general category property codes are supported:
634 <pre>
635 C Other
636 Cc Control
637 Cf Format
638 Cn Unassigned
639 Co Private use
640 Cs Surrogate
642 L Letter
643 Ll Lower case letter
644 Lm Modifier letter
645 Lo Other letter
646 Lt Title case letter
647 Lu Upper case letter
649 M Mark
650 Mc Spacing mark
651 Me Enclosing mark
652 Mn Non-spacing mark
654 N Number
655 Nd Decimal number
656 Nl Letter number
657 No Other number
659 P Punctuation
660 Pc Connector punctuation
661 Pd Dash punctuation
662 Pe Close punctuation
663 Pf Final punctuation
664 Pi Initial punctuation
665 Po Other punctuation
666 Ps Open punctuation
668 S Symbol
669 Sc Currency symbol
670 Sk Modifier symbol
671 Sm Mathematical symbol
672 So Other symbol
674 Z Separator
675 Zl Line separator
676 Zp Paragraph separator
677 Zs Space separator
678 </pre>
679 The special property L& is also supported: it matches a character that has
680 the Lu, Ll, or Lt property, in other words, a letter that is not classified as
681 a modifier or "other".
682 </P>
683 <P>
684 The Cs (Surrogate) property applies only to characters in the range U+D800 to
685 U+DFFF. Such characters are not valid in UTF-8 strings (see RFC 3629) and so
686 cannot be tested by PCRE, unless UTF-8 validity checking has been turned off
687 (see the discussion of PCRE_NO_UTF8_CHECK in the
688 <a href="pcreapi.html"><b>pcreapi</b></a>
689 page). Perl does not support the Cs property.
690 </P>
691 <P>
692 The long synonyms for property names that Perl supports (such as \p{Letter})
693 are not supported by PCRE, nor is it permitted to prefix any of these
694 properties with "Is".
695 </P>
696 <P>
697 No character that is in the Unicode table has the Cn (unassigned) property.
698 Instead, this property is assumed for any code point that is not in the
699 Unicode table.
700 </P>
701 <P>
702 Specifying caseless matching does not affect these escape sequences. For
703 example, \p{Lu} always matches only upper case letters.
704 </P>
705 <P>
706 The \X escape matches any number of Unicode characters that form an extended
707 Unicode sequence. \X is equivalent to
708 <pre>
709 (?&#62;\PM\pM*)
710 </pre>
711 That is, it matches a character without the "mark" property, followed by zero
712 or more characters with the "mark" property, and treats the sequence as an
713 atomic group
714 <a href="#atomicgroup">(see below).</a>
715 Characters with the "mark" property are typically accents that affect the
716 preceding character. None of them have codepoints less than 256, so in
717 non-UTF-8 mode \X matches any one character.
718 </P>
719 <P>
720 Matching characters by Unicode property is not fast, because PCRE has to search
721 a structure that contains data for over fifteen thousand characters. That is
722 why the traditional escape sequences such as \d and \w do not use Unicode
723 properties in PCRE.
724 <a name="extraprops"></a></P>
725 <br><b>
726 PCRE's additional properties
727 </b><br>
728 <P>
729 As well as the standard Unicode properties described in the previous
730 section, PCRE supports four more that make it possible to convert traditional
731 escape sequences such as \w and \s and POSIX character classes to use Unicode
732 properties. These are:
733 <pre>
734 Xan Any alphanumeric character
735 Xps Any POSIX space character
736 Xsp Any Perl space character
737 Xwd Any Perl "word" character
738 </pre>
739 Xan matches characters that have either the L (letter) or the N (number)
740 property. Xps matches the characters tab, linefeed, vertical tab, formfeed, or
741 carriage return, and any other character that has the Z (separator) property.
742 Xsp is the same as Xps, except that vertical tab is excluded. Xwd matches the
743 same characters as Xan, plus underscore.
744 <a name="resetmatchstart"></a></P>
745 <br><b>
746 Resetting the match start
747 </b><br>
748 <P>
749 The escape sequence \K, which is a Perl 5.10 feature, causes any previously
750 matched characters not to be included in the final matched sequence. For
751 example, the pattern:
752 <pre>
753 foo\Kbar
754 </pre>
755 matches "foobar", but reports that it has matched "bar". This feature is
756 similar to a lookbehind assertion
757 <a href="#lookbehind">(described below).</a>
758 However, in this case, the part of the subject before the real match does not
759 have to be of fixed length, as lookbehind assertions do. The use of \K does
760 not interfere with the setting of
761 <a href="#subpattern">captured substrings.</a>
762 For example, when the pattern
763 <pre>
764 (foo)\Kbar
765 </pre>
766 matches "foobar", the first substring is still set to "foo".
767 </P>
768 <P>
769 Perl documents that the use of \K within assertions is "not well defined". In
770 PCRE, \K is acted upon when it occurs inside positive assertions, but is
771 ignored in negative assertions.
772 <a name="smallassertions"></a></P>
773 <br><b>
774 Simple assertions
775 </b><br>
776 <P>
777 The final use of backslash is for certain simple assertions. An assertion
778 specifies a condition that has to be met at a particular point in a match,
779 without consuming any characters from the subject string. The use of
780 subpatterns for more complicated assertions is described
781 <a href="#bigassertions">below.</a>
782 The backslashed assertions are:
783 <pre>
784 \b matches at a word boundary
785 \B matches when not at a word boundary
786 \A matches at the start of the subject
787 \Z matches at the end of the subject
788 also matches before a newline at the end of the subject
789 \z matches only at the end of the subject
790 \G matches at the first matching position in the subject
791 </pre>
792 Inside a character class, \b has a different meaning; it matches the backspace
793 character. If any other of these assertions appears in a character class, by
794 default it matches the corresponding literal character (for example, \B
795 matches the letter B). However, if the PCRE_EXTRA option is set, an "invalid
796 escape sequence" error is generated instead.
797 </P>
798 <P>
799 A word boundary is a position in the subject string where the current character
800 and the previous character do not both match \w or \W (i.e. one matches
801 \w and the other matches \W), or the start or end of the string if the
802 first or last character matches \w, respectively. Neither PCRE nor Perl has a
803 separte "start of word" or "end of word" metasequence. However, whatever
804 follows \b normally determines which it is. For example, the fragment
805 \ba matches "a" at the start of a word.
806 </P>
807 <P>
808 The \A, \Z, and \z assertions differ from the traditional circumflex and
809 dollar (described in the next section) in that they only ever match at the very
810 start and end of the subject string, whatever options are set. Thus, they are
811 independent of multiline mode. These three assertions are not affected by the
812 PCRE_NOTBOL or PCRE_NOTEOL options, which affect only the behaviour of the
813 circumflex and dollar metacharacters. However, if the <i>startoffset</i>
814 argument of <b>pcre_exec()</b> is non-zero, indicating that matching is to start
815 at a point other than the beginning of the subject, \A can never match. The
816 difference between \Z and \z is that \Z matches before a newline at the end
817 of the string as well as at the very end, whereas \z matches only at the end.
818 </P>
819 <P>
820 The \G assertion is true only when the current matching position is at the
821 start point of the match, as specified by the <i>startoffset</i> argument of
822 <b>pcre_exec()</b>. It differs from \A when the value of <i>startoffset</i> is
823 non-zero. By calling <b>pcre_exec()</b> multiple times with appropriate
824 arguments, you can mimic Perl's /g option, and it is in this kind of
825 implementation where \G can be useful.
826 </P>
827 <P>
828 Note, however, that PCRE's interpretation of \G, as the start of the current
829 match, is subtly different from Perl's, which defines it as the end of the
830 previous match. In Perl, these can be different when the previously matched
831 string was empty. Because PCRE does just one match at a time, it cannot
832 reproduce this behaviour.
833 </P>
834 <P>
835 If all the alternatives of a pattern begin with \G, the expression is anchored
836 to the starting match position, and the "anchored" flag is set in the compiled
837 regular expression.
838 </P>
839 <br><a name="SEC5" href="#TOC1">CIRCUMFLEX AND DOLLAR</a><br>
840 <P>
841 Outside a character class, in the default matching mode, the circumflex
842 character is an assertion that is true only if the current matching point is
843 at the start of the subject string. If the <i>startoffset</i> argument of
844 <b>pcre_exec()</b> is non-zero, circumflex can never match if the PCRE_MULTILINE
845 option is unset. Inside a character class, circumflex has an entirely different
846 meaning
847 <a href="#characterclass">(see below).</a>
848 </P>
849 <P>
850 Circumflex need not be the first character of the pattern if a number of
851 alternatives are involved, but it should be the first thing in each alternative
852 in which it appears if the pattern is ever to match that branch. If all
853 possible alternatives start with a circumflex, that is, if the pattern is
854 constrained to match only at the start of the subject, it is said to be an
855 "anchored" pattern. (There are also other constructs that can cause a pattern
856 to be anchored.)
857 </P>
858 <P>
859 A dollar character is an assertion that is true only if the current matching
860 point is at the end of the subject string, or immediately before a newline
861 at the end of the string (by default). Dollar need not be the last character of
862 the pattern if a number of alternatives are involved, but it should be the last
863 item in any branch in which it appears. Dollar has no special meaning in a
864 character class.
865 </P>
866 <P>
867 The meaning of dollar can be changed so that it matches only at the very end of
868 the string, by setting the PCRE_DOLLAR_ENDONLY option at compile time. This
869 does not affect the \Z assertion.
870 </P>
871 <P>
872 The meanings of the circumflex and dollar characters are changed if the
873 PCRE_MULTILINE option is set. When this is the case, a circumflex matches
874 immediately after internal newlines as well as at the start of the subject
875 string. It does not match after a newline that ends the string. A dollar
876 matches before any newlines in the string, as well as at the very end, when
877 PCRE_MULTILINE is set. When newline is specified as the two-character
878 sequence CRLF, isolated CR and LF characters do not indicate newlines.
879 </P>
880 <P>
881 For example, the pattern /^abc$/ matches the subject string "def\nabc" (where
882 \n represents a newline) in multiline mode, but not otherwise. Consequently,
883 patterns that are anchored in single line mode because all branches start with
884 ^ are not anchored in multiline mode, and a match for circumflex is possible
885 when the <i>startoffset</i> argument of <b>pcre_exec()</b> is non-zero. The
886 PCRE_DOLLAR_ENDONLY option is ignored if PCRE_MULTILINE is set.
887 </P>
888 <P>
889 Note that the sequences \A, \Z, and \z can be used to match the start and
890 end of the subject in both modes, and if all branches of a pattern start with
891 \A it is always anchored, whether or not PCRE_MULTILINE is set.
892 <a name="fullstopdot"></a></P>
893 <br><a name="SEC6" href="#TOC1">FULL STOP (PERIOD, DOT) AND \N</a><br>
894 <P>
895 Outside a character class, a dot in the pattern matches any one character in
896 the subject string except (by default) a character that signifies the end of a
897 line. In UTF-8 mode, the matched character may be more than one byte long.
898 </P>
899 <P>
900 When a line ending is defined as a single character, dot never matches that
901 character; when the two-character sequence CRLF is used, dot does not match CR
902 if it is immediately followed by LF, but otherwise it matches all characters
903 (including isolated CRs and LFs). When any Unicode line endings are being
904 recognized, dot does not match CR or LF or any of the other line ending
905 characters.
906 </P>
907 <P>
908 The behaviour of dot with regard to newlines can be changed. If the PCRE_DOTALL
909 option is set, a dot matches any one character, without exception. If the
910 two-character sequence CRLF is present in the subject string, it takes two dots
911 to match it.
912 </P>
913 <P>
914 The handling of dot is entirely independent of the handling of circumflex and
915 dollar, the only relationship being that they both involve newlines. Dot has no
916 special meaning in a character class.
917 </P>
918 <P>
919 The escape sequence \N always behaves as a dot does when PCRE_DOTALL is not
920 set. In other words, it matches any one character except one that signifies the
921 end of a line.
922 </P>
923 <br><a name="SEC7" href="#TOC1">MATCHING A SINGLE BYTE</a><br>
924 <P>
925 Outside a character class, the escape sequence \C matches any one byte, both
926 in and out of UTF-8 mode. Unlike a dot, it always matches any line-ending
927 characters. The feature is provided in Perl in order to match individual bytes
928 in UTF-8 mode. Because it breaks up UTF-8 characters into individual bytes,
929 what remains in the string may be a malformed UTF-8 string. For this reason,
930 the \C escape sequence is best avoided.
931 </P>
932 <P>
933 PCRE does not allow \C to appear in lookbehind assertions
934 <a href="#lookbehind">(described below),</a>
935 because in UTF-8 mode this would make it impossible to calculate the length of
936 the lookbehind.
937 <a name="characterclass"></a></P>
938 <br><a name="SEC8" href="#TOC1">SQUARE BRACKETS AND CHARACTER CLASSES</a><br>
939 <P>
940 An opening square bracket introduces a character class, terminated by a closing
941 square bracket. A closing square bracket on its own is not special by default.
942 However, if the PCRE_JAVASCRIPT_COMPAT option is set, a lone closing square
943 bracket causes a compile-time error. If a closing square bracket is required as
944 a member of the class, it should be the first data character in the class
945 (after an initial circumflex, if present) or escaped with a backslash.
946 </P>
947 <P>
948 A character class matches a single character in the subject. In UTF-8 mode, the
949 character may be more than one byte long. A matched character must be in the
950 set of characters defined by the class, unless the first character in the class
951 definition is a circumflex, in which case the subject character must not be in
952 the set defined by the class. If a circumflex is actually required as a member
953 of the class, ensure it is not the first character, or escape it with a
954 backslash.
955 </P>
956 <P>
957 For example, the character class [aeiou] matches any lower case vowel, while
958 [^aeiou] matches any character that is not a lower case vowel. Note that a
959 circumflex is just a convenient notation for specifying the characters that
960 are in the class by enumerating those that are not. A class that starts with a
961 circumflex is not an assertion; it still consumes a character from the subject
962 string, and therefore it fails if the current pointer is at the end of the
963 string.
964 </P>
965 <P>
966 In UTF-8 mode, characters with values greater than 255 can be included in a
967 class as a literal string of bytes, or by using the \x{ escaping mechanism.
968 </P>
969 <P>
970 When caseless matching is set, any letters in a class represent both their
971 upper case and lower case versions, so for example, a caseless [aeiou] matches
972 "A" as well as "a", and a caseless [^aeiou] does not match "A", whereas a
973 caseful version would. In UTF-8 mode, PCRE always understands the concept of
974 case for characters whose values are less than 128, so caseless matching is
975 always possible. For characters with higher values, the concept of case is
976 supported if PCRE is compiled with Unicode property support, but not otherwise.
977 If you want to use caseless matching in UTF8-mode for characters 128 and above,
978 you must ensure that PCRE is compiled with Unicode property support as well as
979 with UTF-8 support.
980 </P>
981 <P>
982 Characters that might indicate line breaks are never treated in any special way
983 when matching character classes, whatever line-ending sequence is in use, and
984 whatever setting of the PCRE_DOTALL and PCRE_MULTILINE options is used. A class
985 such as [^a] always matches one of these characters.
986 </P>
987 <P>
988 The minus (hyphen) character can be used to specify a range of characters in a
989 character class. For example, [d-m] matches any letter between d and m,
990 inclusive. If a minus character is required in a class, it must be escaped with
991 a backslash or appear in a position where it cannot be interpreted as
992 indicating a range, typically as the first or last character in the class.
993 </P>
994 <P>
995 It is not possible to have the literal character "]" as the end character of a
996 range. A pattern such as [W-]46] is interpreted as a class of two characters
997 ("W" and "-") followed by a literal string "46]", so it would match "W46]" or
998 "-46]". However, if the "]" is escaped with a backslash it is interpreted as
999 the end of range, so [W-\]46] is interpreted as a class containing a range
1000 followed by two other characters. The octal or hexadecimal representation of
1001 "]" can also be used to end a range.
1002 </P>
1003 <P>
1004 Ranges operate in the collating sequence of character values. They can also be
1005 used for characters specified numerically, for example [\000-\037]. In UTF-8
1006 mode, ranges can include characters whose values are greater than 255, for
1007 example [\x{100}-\x{2ff}].
1008 </P>
1009 <P>
1010 If a range that includes letters is used when caseless matching is set, it
1011 matches the letters in either case. For example, [W-c] is equivalent to
1012 [][\\^_`wxyzabc], matched caselessly, and in non-UTF-8 mode, if character
1013 tables for a French locale are in use, [\xc8-\xcb] matches accented E
1014 characters in both cases. In UTF-8 mode, PCRE supports the concept of case for
1015 characters with values greater than 128 only when it is compiled with Unicode
1016 property support.
1017 </P>
1018 <P>
1019 The character types \d, \D, \p, \P, \s, \S, \w, and \W may also appear
1020 in a character class, and add the characters that they match to the class. For
1021 example, [\dABCDEF] matches any hexadecimal digit. A circumflex can
1022 conveniently be used with the upper case character types to specify a more
1023 restricted set of characters than the matching lower case type. For example,
1024 the class [^\W_] matches any letter or digit, but not underscore.
1025 </P>
1026 <P>
1027 The only metacharacters that are recognized in character classes are backslash,
1028 hyphen (only where it can be interpreted as specifying a range), circumflex
1029 (only at the start), opening square bracket (only when it can be interpreted as
1030 introducing a POSIX class name - see the next section), and the terminating
1031 closing square bracket. However, escaping other non-alphanumeric characters
1032 does no harm.
1033 </P>
1034 <br><a name="SEC9" href="#TOC1">POSIX CHARACTER CLASSES</a><br>
1035 <P>
1036 Perl supports the POSIX notation for character classes. This uses names
1037 enclosed by [: and :] within the enclosing square brackets. PCRE also supports
1038 this notation. For example,
1039 <pre>
1040 [01[:alpha:]%]
1041 </pre>
1042 matches "0", "1", any alphabetic character, or "%". The supported class names
1043 are
1044 <pre>
1045 alnum letters and digits
1046 alpha letters
1047 ascii character codes 0 - 127
1048 blank space or tab only
1049 cntrl control characters
1050 digit decimal digits (same as \d)
1051 graph printing characters, excluding space
1052 lower lower case letters
1053 print printing characters, including space
1054 punct printing characters, excluding letters and digits
1055 space white space (not quite the same as \s)
1056 upper upper case letters
1057 word "word" characters (same as \w)
1058 xdigit hexadecimal digits
1059 </pre>
1060 The "space" characters are HT (9), LF (10), VT (11), FF (12), CR (13), and
1061 space (32). Notice that this list includes the VT character (code 11). This
1062 makes "space" different to \s, which does not include VT (for Perl
1063 compatibility).
1064 </P>
1065 <P>
1066 The name "word" is a Perl extension, and "blank" is a GNU extension from Perl
1067 5.8. Another Perl extension is negation, which is indicated by a ^ character
1068 after the colon. For example,
1069 <pre>
1070 [12[:^digit:]]
1071 </pre>
1072 matches "1", "2", or any non-digit. PCRE (and Perl) also recognize the POSIX
1073 syntax [.ch.] and [=ch=] where "ch" is a "collating element", but these are not
1074 supported, and an error is given if they are encountered.
1075 </P>
1076 <P>
1077 In UTF-8 mode, characters with values greater than 128 do not match any of
1078 the POSIX character classes.
1079 </P>
1080 <br><a name="SEC10" href="#TOC1">VERTICAL BAR</a><br>
1081 <P>
1082 Vertical bar characters are used to separate alternative patterns. For example,
1083 the pattern
1084 <pre>
1085 gilbert|sullivan
1086 </pre>
1087 matches either "gilbert" or "sullivan". Any number of alternatives may appear,
1088 and an empty alternative is permitted (matching the empty string). The matching
1089 process tries each alternative in turn, from left to right, and the first one
1090 that succeeds is used. If the alternatives are within a subpattern
1091 <a href="#subpattern">(defined below),</a>
1092 "succeeds" means matching the rest of the main pattern as well as the
1093 alternative in the subpattern.
1094 </P>
1095 <br><a name="SEC11" href="#TOC1">INTERNAL OPTION SETTING</a><br>
1096 <P>
1097 The settings of the PCRE_CASELESS, PCRE_MULTILINE, PCRE_DOTALL, and
1098 PCRE_EXTENDED options (which are Perl-compatible) can be changed from within
1099 the pattern by a sequence of Perl option letters enclosed between "(?" and ")".
1100 The option letters are
1101 <pre>
1102 i for PCRE_CASELESS
1104 s for PCRE_DOTALL
1105 x for PCRE_EXTENDED
1106 </pre>
1107 For example, (?im) sets caseless, multiline matching. It is also possible to
1108 unset these options by preceding the letter with a hyphen, and a combined
1109 setting and unsetting such as (?im-sx), which sets PCRE_CASELESS and
1110 PCRE_MULTILINE while unsetting PCRE_DOTALL and PCRE_EXTENDED, is also
1111 permitted. If a letter appears both before and after the hyphen, the option is
1112 unset.
1113 </P>
1114 <P>
1115 The PCRE-specific options PCRE_DUPNAMES, PCRE_UNGREEDY, and PCRE_EXTRA can be
1116 changed in the same way as the Perl-compatible options by using the characters
1117 J, U and X respectively.
1118 </P>
1119 <P>
1120 When one of these option changes occurs at top level (that is, not inside
1121 subpattern parentheses), the change applies to the remainder of the pattern
1122 that follows. If the change is placed right at the start of a pattern, PCRE
1123 extracts it into the global options (and it will therefore show up in data
1124 extracted by the <b>pcre_fullinfo()</b> function).
1125 </P>
1126 <P>
1127 An option change within a subpattern (see below for a description of
1128 subpatterns) affects only that part of the current pattern that follows it, so
1129 <pre>
1130 (a(?i)b)c
1131 </pre>
1132 matches abc and aBc and no other strings (assuming PCRE_CASELESS is not used).
1133 By this means, options can be made to have different settings in different
1134 parts of the pattern. Any changes made in one alternative do carry on
1135 into subsequent branches within the same subpattern. For example,
1136 <pre>
1137 (a(?i)b|c)
1138 </pre>
1139 matches "ab", "aB", "c", and "C", even though when matching "C" the first
1140 branch is abandoned before the option setting. This is because the effects of
1141 option settings happen at compile time. There would be some very weird
1142 behaviour otherwise.
1143 </P>
1144 <P>
1145 <b>Note:</b> There are other PCRE-specific options that can be set by the
1146 application when the compile or match functions are called. In some cases the
1147 pattern can contain special leading sequences such as (*CRLF) to override what
1148 the application has set or what has been defaulted. Details are given in the
1149 section entitled
1150 <a href="#newlineseq">"Newline sequences"</a>
1151 above. There is also the (*UTF8) leading sequence that can be used to set UTF-8
1152 mode; this is equivalent to setting the PCRE_UTF8 option.
1153 <a name="subpattern"></a></P>
1154 <br><a name="SEC12" href="#TOC1">SUBPATTERNS</a><br>
1155 <P>
1156 Subpatterns are delimited by parentheses (round brackets), which can be nested.
1157 Turning part of a pattern into a subpattern does two things:
1158 <br>
1159 <br>
1160 1. It localizes a set of alternatives. For example, the pattern
1161 <pre>
1162 cat(aract|erpillar|)
1163 </pre>
1164 matches one of the words "cat", "cataract", or "caterpillar". Without the
1165 parentheses, it would match "cataract", "erpillar" or an empty string.
1166 <br>
1167 <br>
1168 2. It sets up the subpattern as a capturing subpattern. This means that, when
1169 the whole pattern matches, that portion of the subject string that matched the
1170 subpattern is passed back to the caller via the <i>ovector</i> argument of
1171 <b>pcre_exec()</b>. Opening parentheses are counted from left to right (starting
1172 from 1) to obtain numbers for the capturing subpatterns.
1173 </P>
1174 <P>
1175 For example, if the string "the red king" is matched against the pattern
1176 <pre>
1177 the ((red|white) (king|queen))
1178 </pre>
1179 the captured substrings are "red king", "red", and "king", and are numbered 1,
1180 2, and 3, respectively.
1181 </P>
1182 <P>
1183 The fact that plain parentheses fulfil two functions is not always helpful.
1184 There are often times when a grouping subpattern is required without a
1185 capturing requirement. If an opening parenthesis is followed by a question mark
1186 and a colon, the subpattern does not do any capturing, and is not counted when
1187 computing the number of any subsequent capturing subpatterns. For example, if
1188 the string "the white queen" is matched against the pattern
1189 <pre>
1190 the ((?:red|white) (king|queen))
1191 </pre>
1192 the captured substrings are "white queen" and "queen", and are numbered 1 and
1193 2. The maximum number of capturing subpatterns is 65535.
1194 </P>
1195 <P>
1196 As a convenient shorthand, if any option settings are required at the start of
1197 a non-capturing subpattern, the option letters may appear between the "?" and
1198 the ":". Thus the two patterns
1199 <pre>
1200 (?i:saturday|sunday)
1201 (?:(?i)saturday|sunday)
1202 </pre>
1203 match exactly the same set of strings. Because alternative branches are tried
1204 from left to right, and options are not reset until the end of the subpattern
1205 is reached, an option setting in one branch does affect subsequent branches, so
1206 the above patterns match "SUNDAY" as well as "Saturday".
1207 <a name="dupsubpatternnumber"></a></P>
1208 <br><a name="SEC13" href="#TOC1">DUPLICATE SUBPATTERN NUMBERS</a><br>
1209 <P>
1210 Perl 5.10 introduced a feature whereby each alternative in a subpattern uses
1211 the same numbers for its capturing parentheses. Such a subpattern starts with
1212 (?| and is itself a non-capturing subpattern. For example, consider this
1213 pattern:
1214 <pre>
1215 (?|(Sat)ur|(Sun))day
1216 </pre>
1217 Because the two alternatives are inside a (?| group, both sets of capturing
1218 parentheses are numbered one. Thus, when the pattern matches, you can look
1219 at captured substring number one, whichever alternative matched. This construct
1220 is useful when you want to capture part, but not all, of one of a number of
1221 alternatives. Inside a (?| group, parentheses are numbered as usual, but the
1222 number is reset at the start of each branch. The numbers of any capturing
1223 buffers that follow the subpattern start after the highest number used in any
1224 branch. The following example is taken from the Perl documentation.
1225 The numbers underneath show in which buffer the captured content will be
1226 stored.
1227 <pre>
1228 # before ---------------branch-reset----------- after
1229 / ( a ) (?| x ( y ) z | (p (q) r) | (t) u (v) ) ( z ) /x
1230 # 1 2 2 3 2 3 4
1231 </pre>
1232 A back reference to a numbered subpattern uses the most recent value that is
1233 set for that number by any subpattern. The following pattern matches "abcabc"
1234 or "defdef":
1235 <pre>
1236 /(?|(abc)|(def))\1/
1237 </pre>
1238 In contrast, a recursive or "subroutine" call to a numbered subpattern always
1239 refers to the first one in the pattern with the given number. The following
1240 pattern matches "abcabc" or "defabc":
1241 <pre>
1242 /(?|(abc)|(def))(?1)/
1243 </pre>
1244 If a
1245 <a href="#conditions">condition test</a>
1246 for a subpattern's having matched refers to a non-unique number, the test is
1247 true if any of the subpatterns of that number have matched.
1248 </P>
1249 <P>
1250 An alternative approach to using this "branch reset" feature is to use
1251 duplicate named subpatterns, as described in the next section.
1252 </P>
1253 <br><a name="SEC14" href="#TOC1">NAMED SUBPATTERNS</a><br>
1254 <P>
1255 Identifying capturing parentheses by number is simple, but it can be very hard
1256 to keep track of the numbers in complicated regular expressions. Furthermore,
1257 if an expression is modified, the numbers may change. To help with this
1258 difficulty, PCRE supports the naming of subpatterns. This feature was not
1259 added to Perl until release 5.10. Python had the feature earlier, and PCRE
1260 introduced it at release 4.0, using the Python syntax. PCRE now supports both
1261 the Perl and the Python syntax. Perl allows identically numbered subpatterns to
1262 have different names, but PCRE does not.
1263 </P>
1264 <P>
1265 In PCRE, a subpattern can be named in one of three ways: (?&#60;name&#62;...) or
1266 (?'name'...) as in Perl, or (?P&#60;name&#62;...) as in Python. References to capturing
1267 parentheses from other parts of the pattern, such as
1268 <a href="#backreferences">back references,</a>
1269 <a href="#recursion">recursion,</a>
1270 and
1271 <a href="#conditions">conditions,</a>
1272 can be made by name as well as by number.
1273 </P>
1274 <P>
1275 Names consist of up to 32 alphanumeric characters and underscores. Named
1276 capturing parentheses are still allocated numbers as well as names, exactly as
1277 if the names were not present. The PCRE API provides function calls for
1278 extracting the name-to-number translation table from a compiled pattern. There
1279 is also a convenience function for extracting a captured substring by name.
1280 </P>
1281 <P>
1282 By default, a name must be unique within a pattern, but it is possible to relax
1283 this constraint by setting the PCRE_DUPNAMES option at compile time. (Duplicate
1284 names are also always permitted for subpatterns with the same number, set up as
1285 described in the previous section.) Duplicate names can be useful for patterns
1286 where only one instance of the named parentheses can match. Suppose you want to
1287 match the name of a weekday, either as a 3-letter abbreviation or as the full
1288 name, and in both cases you want to extract the abbreviation. This pattern
1289 (ignoring the line breaks) does the job:
1290 <pre>
1291 (?&#60;DN&#62;Mon|Fri|Sun)(?:day)?|
1292 (?&#60;DN&#62;Tue)(?:sday)?|
1293 (?&#60;DN&#62;Wed)(?:nesday)?|
1294 (?&#60;DN&#62;Thu)(?:rsday)?|
1295 (?&#60;DN&#62;Sat)(?:urday)?
1296 </pre>
1297 There are five capturing substrings, but only one is ever set after a match.
1298 (An alternative way of solving this problem is to use a "branch reset"
1299 subpattern, as described in the previous section.)
1300 </P>
1301 <P>
1302 The convenience function for extracting the data by name returns the substring
1303 for the first (and in this example, the only) subpattern of that name that
1304 matched. This saves searching to find which numbered subpattern it was.
1305 </P>
1306 <P>
1307 If you make a back reference to a non-unique named subpattern from elsewhere in
1308 the pattern, the one that corresponds to the first occurrence of the name is
1309 used. In the absence of duplicate numbers (see the previous section) this is
1310 the one with the lowest number. If you use a named reference in a condition
1311 test (see the
1312 <a href="#conditions">section about conditions</a>
1313 below), either to check whether a subpattern has matched, or to check for
1314 recursion, all subpatterns with the same name are tested. If the condition is
1315 true for any one of them, the overall condition is true. This is the same
1316 behaviour as testing by number. For further details of the interfaces for
1317 handling named subpatterns, see the
1318 <a href="pcreapi.html"><b>pcreapi</b></a>
1319 documentation.
1320 </P>
1321 <P>
1322 <b>Warning:</b> You cannot use different names to distinguish between two
1323 subpatterns with the same number because PCRE uses only the numbers when
1324 matching. For this reason, an error is given at compile time if different names
1325 are given to subpatterns with the same number. However, you can give the same
1326 name to subpatterns with the same number, even when PCRE_DUPNAMES is not set.
1327 </P>
1328 <br><a name="SEC15" href="#TOC1">REPETITION</a><br>
1329 <P>
1330 Repetition is specified by quantifiers, which can follow any of the following
1331 items:
1332 <pre>
1333 a literal data character
1334 the dot metacharacter
1335 the \C escape sequence
1336 the \X escape sequence (in UTF-8 mode with Unicode properties)
1337 the \R escape sequence
1338 an escape such as \d that matches a single character
1339 a character class
1340 a back reference (see next section)
1341 a parenthesized subpattern (unless it is an assertion)
1342 a recursive or "subroutine" call to a subpattern
1343 </pre>
1344 The general repetition quantifier specifies a minimum and maximum number of
1345 permitted matches, by giving the two numbers in curly brackets (braces),
1346 separated by a comma. The numbers must be less than 65536, and the first must
1347 be less than or equal to the second. For example:
1348 <pre>
1349 z{2,4}
1350 </pre>
1351 matches "zz", "zzz", or "zzzz". A closing brace on its own is not a special
1352 character. If the second number is omitted, but the comma is present, there is
1353 no upper limit; if the second number and the comma are both omitted, the
1354 quantifier specifies an exact number of required matches. Thus
1355 <pre>
1356 [aeiou]{3,}
1357 </pre>
1358 matches at least 3 successive vowels, but may match many more, while
1359 <pre>
1360 \d{8}
1361 </pre>
1362 matches exactly 8 digits. An opening curly bracket that appears in a position
1363 where a quantifier is not allowed, or one that does not match the syntax of a
1364 quantifier, is taken as a literal character. For example, {,6} is not a
1365 quantifier, but a literal string of four characters.
1366 </P>
1367 <P>
1368 In UTF-8 mode, quantifiers apply to UTF-8 characters rather than to individual
1369 bytes. Thus, for example, \x{100}{2} matches two UTF-8 characters, each of
1370 which is represented by a two-byte sequence. Similarly, when Unicode property
1371 support is available, \X{3} matches three Unicode extended sequences, each of
1372 which may be several bytes long (and they may be of different lengths).
1373 </P>
1374 <P>
1375 The quantifier {0} is permitted, causing the expression to behave as if the
1376 previous item and the quantifier were not present. This may be useful for
1377 subpatterns that are referenced as
1378 <a href="#subpatternsassubroutines">subroutines</a>
1379 from elsewhere in the pattern. Items other than subpatterns that have a {0}
1380 quantifier are omitted from the compiled pattern.
1381 </P>
1382 <P>
1383 For convenience, the three most common quantifiers have single-character
1384 abbreviations:
1385 <pre>
1386 * is equivalent to {0,}
1387 + is equivalent to {1,}
1388 ? is equivalent to {0,1}
1389 </pre>
1390 It is possible to construct infinite loops by following a subpattern that can
1391 match no characters with a quantifier that has no upper limit, for example:
1392 <pre>
1393 (a?)*
1394 </pre>
1395 Earlier versions of Perl and PCRE used to give an error at compile time for
1396 such patterns. However, because there are cases where this can be useful, such
1397 patterns are now accepted, but if any repetition of the subpattern does in fact
1398 match no characters, the loop is forcibly broken.
1399 </P>
1400 <P>
1401 By default, the quantifiers are "greedy", that is, they match as much as
1402 possible (up to the maximum number of permitted times), without causing the
1403 rest of the pattern to fail. The classic example of where this gives problems
1404 is in trying to match comments in C programs. These appear between /* and */
1405 and within the comment, individual * and / characters may appear. An attempt to
1406 match C comments by applying the pattern
1407 <pre>
1408 /\*.*\*/
1409 </pre>
1410 to the string
1411 <pre>
1412 /* first comment */ not comment /* second comment */
1413 </pre>
1414 fails, because it matches the entire string owing to the greediness of the .*
1415 item.
1416 </P>
1417 <P>
1418 However, if a quantifier is followed by a question mark, it ceases to be
1419 greedy, and instead matches the minimum number of times possible, so the
1420 pattern
1421 <pre>
1422 /\*.*?\*/
1423 </pre>
1424 does the right thing with the C comments. The meaning of the various
1425 quantifiers is not otherwise changed, just the preferred number of matches.
1426 Do not confuse this use of question mark with its use as a quantifier in its
1427 own right. Because it has two uses, it can sometimes appear doubled, as in
1428 <pre>
1429 \d??\d
1430 </pre>
1431 which matches one digit by preference, but can match two if that is the only
1432 way the rest of the pattern matches.
1433 </P>
1434 <P>
1435 If the PCRE_UNGREEDY option is set (an option that is not available in Perl),
1436 the quantifiers are not greedy by default, but individual ones can be made
1437 greedy by following them with a question mark. In other words, it inverts the
1438 default behaviour.
1439 </P>
1440 <P>
1441 When a parenthesized subpattern is quantified with a minimum repeat count that
1442 is greater than 1 or with a limited maximum, more memory is required for the
1443 compiled pattern, in proportion to the size of the minimum or maximum.
1444 </P>
1445 <P>
1446 If a pattern starts with .* or .{0,} and the PCRE_DOTALL option (equivalent
1447 to Perl's /s) is set, thus allowing the dot to match newlines, the pattern is
1448 implicitly anchored, because whatever follows will be tried against every
1449 character position in the subject string, so there is no point in retrying the
1450 overall match at any position after the first. PCRE normally treats such a
1451 pattern as though it were preceded by \A.
1452 </P>
1453 <P>
1454 In cases where it is known that the subject string contains no newlines, it is
1455 worth setting PCRE_DOTALL in order to obtain this optimization, or
1456 alternatively using ^ to indicate anchoring explicitly.
1457 </P>
1458 <P>
1459 However, there is one situation where the optimization cannot be used. When .*
1460 is inside capturing parentheses that are the subject of a back reference
1461 elsewhere in the pattern, a match at the start may fail where a later one
1462 succeeds. Consider, for example:
1463 <pre>
1464 (.*)abc\1
1465 </pre>
1466 If the subject is "xyz123abc123" the match point is the fourth character. For
1467 this reason, such a pattern is not implicitly anchored.
1468 </P>
1469 <P>
1470 When a capturing subpattern is repeated, the value captured is the substring
1471 that matched the final iteration. For example, after
1472 <pre>
1473 (tweedle[dume]{3}\s*)+
1474 </pre>
1475 has matched "tweedledum tweedledee" the value of the captured substring is
1476 "tweedledee". However, if there are nested capturing subpatterns, the
1477 corresponding captured values may have been set in previous iterations. For
1478 example, after
1479 <pre>
1480 /(a|(b))+/
1481 </pre>
1482 matches "aba" the value of the second captured substring is "b".
1483 <a name="atomicgroup"></a></P>
1484 <br><a name="SEC16" href="#TOC1">ATOMIC GROUPING AND POSSESSIVE QUANTIFIERS</a><br>
1485 <P>
1486 With both maximizing ("greedy") and minimizing ("ungreedy" or "lazy")
1487 repetition, failure of what follows normally causes the repeated item to be
1488 re-evaluated to see if a different number of repeats allows the rest of the
1489 pattern to match. Sometimes it is useful to prevent this, either to change the
1490 nature of the match, or to cause it fail earlier than it otherwise might, when
1491 the author of the pattern knows there is no point in carrying on.
1492 </P>
1493 <P>
1494 Consider, for example, the pattern \d+foo when applied to the subject line
1495 <pre>
1496 123456bar
1497 </pre>
1498 After matching all 6 digits and then failing to match "foo", the normal
1499 action of the matcher is to try again with only 5 digits matching the \d+
1500 item, and then with 4, and so on, before ultimately failing. "Atomic grouping"
1501 (a term taken from Jeffrey Friedl's book) provides the means for specifying
1502 that once a subpattern has matched, it is not to be re-evaluated in this way.
1503 </P>
1504 <P>
1505 If we use atomic grouping for the previous example, the matcher gives up
1506 immediately on failing to match "foo" the first time. The notation is a kind of
1507 special parenthesis, starting with (?&#62; as in this example:
1508 <pre>
1509 (?&#62;\d+)foo
1510 </pre>
1511 This kind of parenthesis "locks up" the part of the pattern it contains once
1512 it has matched, and a failure further into the pattern is prevented from
1513 backtracking into it. Backtracking past it to previous items, however, works as
1514 normal.
1515 </P>
1516 <P>
1517 An alternative description is that a subpattern of this type matches the string
1518 of characters that an identical standalone pattern would match, if anchored at
1519 the current point in the subject string.
1520 </P>
1521 <P>
1522 Atomic grouping subpatterns are not capturing subpatterns. Simple cases such as
1523 the above example can be thought of as a maximizing repeat that must swallow
1524 everything it can. So, while both \d+ and \d+? are prepared to adjust the
1525 number of digits they match in order to make the rest of the pattern match,
1526 (?&#62;\d+) can only match an entire sequence of digits.
1527 </P>
1528 <P>
1529 Atomic groups in general can of course contain arbitrarily complicated
1530 subpatterns, and can be nested. However, when the subpattern for an atomic
1531 group is just a single repeated item, as in the example above, a simpler
1532 notation, called a "possessive quantifier" can be used. This consists of an
1533 additional + character following a quantifier. Using this notation, the
1534 previous example can be rewritten as
1535 <pre>
1536 \d++foo
1537 </pre>
1538 Note that a possessive quantifier can be used with an entire group, for
1539 example:
1540 <pre>
1541 (abc|xyz){2,3}+
1542 </pre>
1543 Possessive quantifiers are always greedy; the setting of the PCRE_UNGREEDY
1544 option is ignored. They are a convenient notation for the simpler forms of
1545 atomic group. However, there is no difference in the meaning of a possessive
1546 quantifier and the equivalent atomic group, though there may be a performance
1547 difference; possessive quantifiers should be slightly faster.
1548 </P>
1549 <P>
1550 The possessive quantifier syntax is an extension to the Perl 5.8 syntax.
1551 Jeffrey Friedl originated the idea (and the name) in the first edition of his
1552 book. Mike McCloskey liked it, so implemented it when he built Sun's Java
1553 package, and PCRE copied it from there. It ultimately found its way into Perl
1554 at release 5.10.
1555 </P>
1556 <P>
1557 PCRE has an optimization that automatically "possessifies" certain simple
1558 pattern constructs. For example, the sequence A+B is treated as A++B because
1559 there is no point in backtracking into a sequence of A's when B must follow.
1560 </P>
1561 <P>
1562 When a pattern contains an unlimited repeat inside a subpattern that can itself
1563 be repeated an unlimited number of times, the use of an atomic group is the
1564 only way to avoid some failing matches taking a very long time indeed. The
1565 pattern
1566 <pre>
1567 (\D+|&#60;\d+&#62;)*[!?]
1568 </pre>
1569 matches an unlimited number of substrings that either consist of non-digits, or
1570 digits enclosed in &#60;&#62;, followed by either ! or ?. When it matches, it runs
1571 quickly. However, if it is applied to
1572 <pre>
1573 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
1574 </pre>
1575 it takes a long time before reporting failure. This is because the string can
1576 be divided between the internal \D+ repeat and the external * repeat in a
1577 large number of ways, and all have to be tried. (The example uses [!?] rather
1578 than a single character at the end, because both PCRE and Perl have an
1579 optimization that allows for fast failure when a single character is used. They
1580 remember the last single character that is required for a match, and fail early
1581 if it is not present in the string.) If the pattern is changed so that it uses
1582 an atomic group, like this:
1583 <pre>
1584 ((?&#62;\D+)|&#60;\d+&#62;)*[!?]
1585 </pre>
1586 sequences of non-digits cannot be broken, and failure happens quickly.
1587 <a name="backreferences"></a></P>
1588 <br><a name="SEC17" href="#TOC1">BACK REFERENCES</a><br>
1589 <P>
1590 Outside a character class, a backslash followed by a digit greater than 0 (and
1591 possibly further digits) is a back reference to a capturing subpattern earlier
1592 (that is, to its left) in the pattern, provided there have been that many
1593 previous capturing left parentheses.
1594 </P>
1595 <P>
1596 However, if the decimal number following the backslash is less than 10, it is
1597 always taken as a back reference, and causes an error only if there are not
1598 that many capturing left parentheses in the entire pattern. In other words, the
1599 parentheses that are referenced need not be to the left of the reference for
1600 numbers less than 10. A "forward back reference" of this type can make sense
1601 when a repetition is involved and the subpattern to the right has participated
1602 in an earlier iteration.
1603 </P>
1604 <P>
1605 It is not possible to have a numerical "forward back reference" to a subpattern
1606 whose number is 10 or more using this syntax because a sequence such as \50 is
1607 interpreted as a character defined in octal. See the subsection entitled
1608 "Non-printing characters"
1609 <a href="#digitsafterbackslash">above</a>
1610 for further details of the handling of digits following a backslash. There is
1611 no such problem when named parentheses are used. A back reference to any
1612 subpattern is possible using named parentheses (see below).
1613 </P>
1614 <P>
1615 Another way of avoiding the ambiguity inherent in the use of digits following a
1616 backslash is to use the \g escape sequence, which is a feature introduced in
1617 Perl 5.10. This escape must be followed by an unsigned number or a negative
1618 number, optionally enclosed in braces. These examples are all identical:
1619 <pre>
1620 (ring), \1
1621 (ring), \g1
1622 (ring), \g{1}
1623 </pre>
1624 An unsigned number specifies an absolute reference without the ambiguity that
1625 is present in the older syntax. It is also useful when literal digits follow
1626 the reference. A negative number is a relative reference. Consider this
1627 example:
1628 <pre>
1629 (abc(def)ghi)\g{-1}
1630 </pre>
1631 The sequence \g{-1} is a reference to the most recently started capturing
1632 subpattern before \g, that is, is it equivalent to \2. Similarly, \g{-2}
1633 would be equivalent to \1. The use of relative references can be helpful in
1634 long patterns, and also in patterns that are created by joining together
1635 fragments that contain references within themselves.
1636 </P>
1637 <P>
1638 A back reference matches whatever actually matched the capturing subpattern in
1639 the current subject string, rather than anything matching the subpattern
1640 itself (see
1641 <a href="#subpatternsassubroutines">"Subpatterns as subroutines"</a>
1642 below for a way of doing that). So the pattern
1643 <pre>
1644 (sens|respons)e and \1ibility
1645 </pre>
1646 matches "sense and sensibility" and "response and responsibility", but not
1647 "sense and responsibility". If caseful matching is in force at the time of the
1648 back reference, the case of letters is relevant. For example,
1649 <pre>
1650 ((?i)rah)\s+\1
1651 </pre>
1652 matches "rah rah" and "RAH RAH", but not "RAH rah", even though the original
1653 capturing subpattern is matched caselessly.
1654 </P>
1655 <P>
1656 There are several different ways of writing back references to named
1657 subpatterns. The .NET syntax \k{name} and the Perl syntax \k&#60;name&#62; or
1658 \k'name' are supported, as is the Python syntax (?P=name). Perl 5.10's unified
1659 back reference syntax, in which \g can be used for both numeric and named
1660 references, is also supported. We could rewrite the above example in any of
1661 the following ways:
1662 <pre>
1663 (?&#60;p1&#62;(?i)rah)\s+\k&#60;p1&#62;
1664 (?'p1'(?i)rah)\s+\k{p1}
1665 (?P&#60;p1&#62;(?i)rah)\s+(?P=p1)
1666 (?&#60;p1&#62;(?i)rah)\s+\g{p1}
1667 </pre>
1668 A subpattern that is referenced by name may appear in the pattern before or
1669 after the reference.
1670 </P>
1671 <P>
1672 There may be more than one back reference to the same subpattern. If a
1673 subpattern has not actually been used in a particular match, any back
1674 references to it always fail by default. For example, the pattern
1675 <pre>
1676 (a|(bc))\2
1677 </pre>
1678 always fails if it starts to match "a" rather than "bc". However, if the
1679 PCRE_JAVASCRIPT_COMPAT option is set at compile time, a back reference to an
1680 unset value matches an empty string.
1681 </P>
1682 <P>
1683 Because there may be many capturing parentheses in a pattern, all digits
1684 following a backslash are taken as part of a potential back reference number.
1685 If the pattern continues with a digit character, some delimiter must be used to
1686 terminate the back reference. If the PCRE_EXTENDED option is set, this can be
1687 whitespace. Otherwise, the \g{ syntax or an empty comment (see
1688 <a href="#comments">"Comments"</a>
1689 below) can be used.
1690 </P>
1691 <br><b>
1692 Recursive back references
1693 </b><br>
1694 <P>
1695 A back reference that occurs inside the parentheses to which it refers fails
1696 when the subpattern is first used, so, for example, (a\1) never matches.
1697 However, such references can be useful inside repeated subpatterns. For
1698 example, the pattern
1699 <pre>
1700 (a|b\1)+
1701 </pre>
1702 matches any number of "a"s and also "aba", "ababbaa" etc. At each iteration of
1703 the subpattern, the back reference matches the character string corresponding
1704 to the previous iteration. In order for this to work, the pattern must be such
1705 that the first iteration does not need to match the back reference. This can be
1706 done using alternation, as in the example above, or by a quantifier with a
1707 minimum of zero.
1708 </P>
1709 <P>
1710 Back references of this type cause the group that they reference to be treated
1711 as an
1712 <a href="#atomicgroup">atomic group.</a>
1713 Once the whole group has been matched, a subsequent matching failure cannot
1714 cause backtracking into the middle of the group.
1715 <a name="bigassertions"></a></P>
1716 <br><a name="SEC18" href="#TOC1">ASSERTIONS</a><br>
1717 <P>
1718 An assertion is a test on the characters following or preceding the current
1719 matching point that does not actually consume any characters. The simple
1720 assertions coded as \b, \B, \A, \G, \Z, \z, ^ and $ are described
1721 <a href="#smallassertions">above.</a>
1722 </P>
1723 <P>
1724 More complicated assertions are coded as subpatterns. There are two kinds:
1725 those that look ahead of the current position in the subject string, and those
1726 that look behind it. An assertion subpattern is matched in the normal way,
1727 except that it does not cause the current matching position to be changed.
1728 </P>
1729 <P>
1730 Assertion subpatterns are not capturing subpatterns, and may not be repeated,
1731 because it makes no sense to assert the same thing several times. If any kind
1732 of assertion contains capturing subpatterns within it, these are counted for
1733 the purposes of numbering the capturing subpatterns in the whole pattern.
1734 However, substring capturing is carried out only for positive assertions,
1735 because it does not make sense for negative assertions.
1736 </P>
1737 <br><b>
1738 Lookahead assertions
1739 </b><br>
1740 <P>
1741 Lookahead assertions start with (?= for positive assertions and (?! for
1742 negative assertions. For example,
1743 <pre>
1744 \w+(?=;)
1745 </pre>
1746 matches a word followed by a semicolon, but does not include the semicolon in
1747 the match, and
1748 <pre>
1749 foo(?!bar)
1750 </pre>
1751 matches any occurrence of "foo" that is not followed by "bar". Note that the
1752 apparently similar pattern
1753 <pre>
1754 (?!foo)bar
1755 </pre>
1756 does not find an occurrence of "bar" that is preceded by something other than
1757 "foo"; it finds any occurrence of "bar" whatsoever, because the assertion
1758 (?!foo) is always true when the next three characters are "bar". A
1759 lookbehind assertion is needed to achieve the other effect.
1760 </P>
1761 <P>
1762 If you want to force a matching failure at some point in a pattern, the most
1763 convenient way to do it is with (?!) because an empty string always matches, so
1764 an assertion that requires there not to be an empty string must always fail.
1765 The Perl 5.10 backtracking control verb (*FAIL) or (*F) is essentially a
1766 synonym for (?!).
1767 <a name="lookbehind"></a></P>
1768 <br><b>
1769 Lookbehind assertions
1770 </b><br>
1771 <P>
1772 Lookbehind assertions start with (?&#60;= for positive assertions and (?&#60;! for
1773 negative assertions. For example,
1774 <pre>
1775 (?&#60;!foo)bar
1776 </pre>
1777 does find an occurrence of "bar" that is not preceded by "foo". The contents of
1778 a lookbehind assertion are restricted such that all the strings it matches must
1779 have a fixed length. However, if there are several top-level alternatives, they
1780 do not all have to have the same fixed length. Thus
1781 <pre>
1782 (?&#60;=bullock|donkey)
1783 </pre>
1784 is permitted, but
1785 <pre>
1786 (?&#60;!dogs?|cats?)
1787 </pre>
1788 causes an error at compile time. Branches that match different length strings
1789 are permitted only at the top level of a lookbehind assertion. This is an
1790 extension compared with Perl (5.8 and 5.10), which requires all branches to
1791 match the same length of string. An assertion such as
1792 <pre>
1793 (?&#60;=ab(c|de))
1794 </pre>
1795 is not permitted, because its single top-level branch can match two different
1796 lengths, but it is acceptable to PCRE if rewritten to use two top-level
1797 branches:
1798 <pre>
1799 (?&#60;=abc|abde)
1800 </pre>
1801 In some cases, the Perl 5.10 escape sequence \K
1802 <a href="#resetmatchstart">(see above)</a>
1803 can be used instead of a lookbehind assertion to get round the fixed-length
1804 restriction.
1805 </P>
1806 <P>
1807 The implementation of lookbehind assertions is, for each alternative, to
1808 temporarily move the current position back by the fixed length and then try to
1809 match. If there are insufficient characters before the current position, the
1810 assertion fails.
1811 </P>
1812 <P>
1813 PCRE does not allow the \C escape (which matches a single byte in UTF-8 mode)
1814 to appear in lookbehind assertions, because it makes it impossible to calculate
1815 the length of the lookbehind. The \X and \R escapes, which can match
1816 different numbers of bytes, are also not permitted.
1817 </P>
1818 <P>
1819 <a href="#subpatternsassubroutines">"Subroutine"</a>
1820 calls (see below) such as (?2) or (?&X) are permitted in lookbehinds, as long
1821 as the subpattern matches a fixed-length string.
1822 <a href="#recursion">Recursion,</a>
1823 however, is not supported.
1824 </P>
1825 <P>
1826 Possessive quantifiers can be used in conjunction with lookbehind assertions to
1827 specify efficient matching of fixed-length strings at the end of subject
1828 strings. Consider a simple pattern such as
1829 <pre>
1830 abcd$
1831 </pre>
1832 when applied to a long string that does not match. Because matching proceeds
1833 from left to right, PCRE will look for each "a" in the subject and then see if
1834 what follows matches the rest of the pattern. If the pattern is specified as
1835 <pre>
1836 ^.*abcd$
1837 </pre>
1838 the initial .* matches the entire string at first, but when this fails (because
1839 there is no following "a"), it backtracks to match all but the last character,
1840 then all but the last two characters, and so on. Once again the search for "a"
1841 covers the entire string, from right to left, so we are no better off. However,
1842 if the pattern is written as
1843 <pre>
1844 ^.*+(?&#60;=abcd)
1845 </pre>
1846 there can be no backtracking for the .*+ item; it can match only the entire
1847 string. The subsequent lookbehind assertion does a single test on the last four
1848 characters. If it fails, the match fails immediately. For long strings, this
1849 approach makes a significant difference to the processing time.
1850 </P>
1851 <br><b>
1852 Using multiple assertions
1853 </b><br>
1854 <P>
1855 Several assertions (of any sort) may occur in succession. For example,
1856 <pre>
1857 (?&#60;=\d{3})(?&#60;!999)foo
1858 </pre>
1859 matches "foo" preceded by three digits that are not "999". Notice that each of
1860 the assertions is applied independently at the same point in the subject
1861 string. First there is a check that the previous three characters are all
1862 digits, and then there is a check that the same three characters are not "999".
1863 This pattern does <i>not</i> match "foo" preceded by six characters, the first
1864 of which are digits and the last three of which are not "999". For example, it
1865 doesn't match "123abcfoo". A pattern to do that is
1866 <pre>
1867 (?&#60;=\d{3}...)(?&#60;!999)foo
1868 </pre>
1869 This time the first assertion looks at the preceding six characters, checking
1870 that the first three are digits, and then the second assertion checks that the
1871 preceding three characters are not "999".
1872 </P>
1873 <P>
1874 Assertions can be nested in any combination. For example,
1875 <pre>
1876 (?&#60;=(?&#60;!foo)bar)baz
1877 </pre>
1878 matches an occurrence of "baz" that is preceded by "bar" which in turn is not
1879 preceded by "foo", while
1880 <pre>
1881 (?&#60;=\d{3}(?!999)...)foo
1882 </pre>
1883 is another pattern that matches "foo" preceded by three digits and any three
1884 characters that are not "999".
1885 <a name="conditions"></a></P>
1886 <br><a name="SEC19" href="#TOC1">CONDITIONAL SUBPATTERNS</a><br>
1887 <P>
1888 It is possible to cause the matching process to obey a subpattern
1889 conditionally or to choose between two alternative subpatterns, depending on
1890 the result of an assertion, or whether a specific capturing subpattern has
1891 already been matched. The two possible forms of conditional subpattern are:
1892 <pre>
1893 (?(condition)yes-pattern)
1894 (?(condition)yes-pattern|no-pattern)
1895 </pre>
1896 If the condition is satisfied, the yes-pattern is used; otherwise the
1897 no-pattern (if present) is used. If there are more than two alternatives in the
1898 subpattern, a compile-time error occurs.
1899 </P>
1900 <P>
1901 There are four kinds of condition: references to subpatterns, references to
1902 recursion, a pseudo-condition called DEFINE, and assertions.
1903 </P>
1904 <br><b>
1905 Checking for a used subpattern by number
1906 </b><br>
1907 <P>
1908 If the text between the parentheses consists of a sequence of digits, the
1909 condition is true if a capturing subpattern of that number has previously
1910 matched. If there is more than one capturing subpattern with the same number
1911 (see the earlier
1912 <a href="#recursion">section about duplicate subpattern numbers),</a>
1913 the condition is true if any of them have been set. An alternative notation is
1914 to precede the digits with a plus or minus sign. In this case, the subpattern
1915 number is relative rather than absolute. The most recently opened parentheses
1916 can be referenced by (?(-1), the next most recent by (?(-2), and so on. In
1917 looping constructs it can also make sense to refer to subsequent groups with
1918 constructs such as (?(+2).
1919 </P>
1920 <P>
1921 Consider the following pattern, which contains non-significant white space to
1922 make it more readable (assume the PCRE_EXTENDED option) and to divide it into
1923 three parts for ease of discussion:
1924 <pre>
1925 ( \( )? [^()]+ (?(1) \) )
1926 </pre>
1927 The first part matches an optional opening parenthesis, and if that
1928 character is present, sets it as the first captured substring. The second part
1929 matches one or more characters that are not parentheses. The third part is a
1930 conditional subpattern that tests whether the first set of parentheses matched
1931 or not. If they did, that is, if subject started with an opening parenthesis,
1932 the condition is true, and so the yes-pattern is executed and a closing
1933 parenthesis is required. Otherwise, since no-pattern is not present, the
1934 subpattern matches nothing. In other words, this pattern matches a sequence of
1935 non-parentheses, optionally enclosed in parentheses.
1936 </P>
1937 <P>
1938 If you were embedding this pattern in a larger one, you could use a relative
1939 reference:
1940 <pre>
1941 ...other stuff... ( \( )? [^()]+ (?(-1) \) ) ...
1942 </pre>
1943 This makes the fragment independent of the parentheses in the larger pattern.
1944 </P>
1945 <br><b>
1946 Checking for a used subpattern by name
1947 </b><br>
1948 <P>
1949 Perl uses the syntax (?(&#60;name&#62;)...) or (?('name')...) to test for a used
1950 subpattern by name. For compatibility with earlier versions of PCRE, which had
1951 this facility before Perl, the syntax (?(name)...) is also recognized. However,
1952 there is a possible ambiguity with this syntax, because subpattern names may
1953 consist entirely of digits. PCRE looks first for a named subpattern; if it
1954 cannot find one and the name consists entirely of digits, PCRE looks for a
1955 subpattern of that number, which must be greater than zero. Using subpattern
1956 names that consist entirely of digits is not recommended.
1957 </P>
1958 <P>
1959 Rewriting the above example to use a named subpattern gives this:
1960 <pre>
1961 (?&#60;OPEN&#62; \( )? [^()]+ (?(&#60;OPEN&#62;) \) )
1962 </pre>
1963 If the name used in a condition of this kind is a duplicate, the test is
1964 applied to all subpatterns of the same name, and is true if any one of them has
1965 matched.
1966 </P>
1967 <br><b>
1968 Checking for pattern recursion
1969 </b><br>
1970 <P>
1971 If the condition is the string (R), and there is no subpattern with the name R,
1972 the condition is true if a recursive call to the whole pattern or any
1973 subpattern has been made. If digits or a name preceded by ampersand follow the
1974 letter R, for example:
1975 <pre>
1976 (?(R3)...) or (?(R&name)...)
1977 </pre>
1978 the condition is true if the most recent recursion is into a subpattern whose
1979 number or name is given. This condition does not check the entire recursion
1980 stack. If the name used in a condition of this kind is a duplicate, the test is
1981 applied to all subpatterns of the same name, and is true if any one of them is
1982 the most recent recursion.
1983 </P>
1984 <P>
1985 At "top level", all these recursion test conditions are false.
1986 <a href="#recursion">The syntax for recursive patterns</a>
1987 is described below.
1988 </P>
1989 <br><b>
1990 Defining subpatterns for use by reference only
1991 </b><br>
1992 <P>
1993 If the condition is the string (DEFINE), and there is no subpattern with the
1994 name DEFINE, the condition is always false. In this case, there may be only one
1995 alternative in the subpattern. It is always skipped if control reaches this
1996 point in the pattern; the idea of DEFINE is that it can be used to define
1997 "subroutines" that can be referenced from elsewhere. (The use of
1998 <a href="#subpatternsassubroutines">"subroutines"</a>
1999 is described below.) For example, a pattern to match an IPv4 address could be
2000 written like this (ignore whitespace and line breaks):
2001 <pre>
2002 (?(DEFINE) (?&#60;byte&#62; 2[0-4]\d | 25[0-5] | 1\d\d | [1-9]?\d) )
2003 \b (?&byte) (\.(?&byte)){3} \b
2004 </pre>
2005 The first part of the pattern is a DEFINE group inside which a another group
2006 named "byte" is defined. This matches an individual component of an IPv4
2007 address (a number less than 256). When matching takes place, this part of the
2008 pattern is skipped because DEFINE acts like a false condition. The rest of the
2009 pattern uses references to the named group to match the four dot-separated
2010 components of an IPv4 address, insisting on a word boundary at each end.
2011 </P>
2012 <br><b>
2013 Assertion conditions
2014 </b><br>
2015 <P>
2016 If the condition is not in any of the above formats, it must be an assertion.
2017 This may be a positive or negative lookahead or lookbehind assertion. Consider
2018 this pattern, again containing non-significant white space, and with the two
2019 alternatives on the second line:
2020 <pre>
2021 (?(?=[^a-z]*[a-z])
2022 \d{2}-[a-z]{3}-\d{2} | \d{2}-\d{2}-\d{2} )
2023 </pre>
2024 The condition is a positive lookahead assertion that matches an optional
2025 sequence of non-letters followed by a letter. In other words, it tests for the
2026 presence of at least one letter in the subject. If a letter is found, the
2027 subject is matched against the first alternative; otherwise it is matched
2028 against the second. This pattern matches strings in one of the two forms
2029 dd-aaa-dd or dd-dd-dd, where aaa are letters and dd are digits.
2030 <a name="comments"></a></P>
2031 <br><a name="SEC20" href="#TOC1">COMMENTS</a><br>
2032 <P>
2033 The sequence (?# marks the start of a comment that continues up to the next
2034 closing parenthesis. Nested parentheses are not permitted. The characters
2035 that make up a comment play no part in the pattern matching at all.
2036 </P>
2037 <P>
2038 If the PCRE_EXTENDED option is set, an unescaped # character outside a
2039 character class introduces a comment that continues to immediately after the
2040 next newline in the pattern.
2041 <a name="recursion"></a></P>
2042 <br><a name="SEC21" href="#TOC1">RECURSIVE PATTERNS</a><br>
2043 <P>
2044 Consider the problem of matching a string in parentheses, allowing for
2045 unlimited nested parentheses. Without the use of recursion, the best that can
2046 be done is to use a pattern that matches up to some fixed depth of nesting. It
2047 is not possible to handle an arbitrary nesting depth.
2048 </P>
2049 <P>
2050 For some time, Perl has provided a facility that allows regular expressions to
2051 recurse (amongst other things). It does this by interpolating Perl code in the
2052 expression at run time, and the code can refer to the expression itself. A Perl
2053 pattern using code interpolation to solve the parentheses problem can be
2054 created like this:
2055 <pre>
2056 $re = qr{\( (?: (?&#62;[^()]+) | (?p{$re}) )* \)}x;
2057 </pre>
2058 The (?p{...}) item interpolates Perl code at run time, and in this case refers
2059 recursively to the pattern in which it appears.
2060 </P>
2061 <P>
2062 Obviously, PCRE cannot support the interpolation of Perl code. Instead, it
2063 supports special syntax for recursion of the entire pattern, and also for
2064 individual subpattern recursion. After its introduction in PCRE and Python,
2065 this kind of recursion was subsequently introduced into Perl at release 5.10.
2066 </P>
2067 <P>
2068 A special item that consists of (? followed by a number greater than zero and a
2069 closing parenthesis is a recursive call of the subpattern of the given number,
2070 provided that it occurs inside that subpattern. (If not, it is a
2071 <a href="#subpatternsassubroutines">"subroutine"</a>
2072 call, which is described in the next section.) The special item (?R) or (?0) is
2073 a recursive call of the entire regular expression.
2074 </P>
2075 <P>
2076 This PCRE pattern solves the nested parentheses problem (assume the
2077 PCRE_EXTENDED option is set so that white space is ignored):
2078 <pre>
2079 \( ( [^()]++ | (?R) )* \)
2080 </pre>
2081 First it matches an opening parenthesis. Then it matches any number of
2082 substrings which can either be a sequence of non-parentheses, or a recursive
2083 match of the pattern itself (that is, a correctly parenthesized substring).
2084 Finally there is a closing parenthesis. Note the use of a possessive quantifier
2085 to avoid backtracking into sequences of non-parentheses.
2086 </P>
2087 <P>
2088 If this were part of a larger pattern, you would not want to recurse the entire
2089 pattern, so instead you could use this:
2090 <pre>
2091 ( \( ( [^()]++ | (?1) )* \) )
2092 </pre>
2093 We have put the pattern into parentheses, and caused the recursion to refer to
2094 them instead of the whole pattern.
2095 </P>
2096 <P>
2097 In a larger pattern, keeping track of parenthesis numbers can be tricky. This
2098 is made easier by the use of relative references (a Perl 5.10 feature).
2099 Instead of (?1) in the pattern above you can write (?-2) to refer to the second
2100 most recently opened parentheses preceding the recursion. In other words, a
2101 negative number counts capturing parentheses leftwards from the point at which
2102 it is encountered.
2103 </P>
2104 <P>
2105 It is also possible to refer to subsequently opened parentheses, by writing
2106 references such as (?+2). However, these cannot be recursive because the
2107 reference is not inside the parentheses that are referenced. They are always
2108 <a href="#subpatternsassubroutines">"subroutine"</a>
2109 calls, as described in the next section.
2110 </P>
2111 <P>
2112 An alternative approach is to use named parentheses instead. The Perl syntax
2113 for this is (?&name); PCRE's earlier syntax (?P&#62;name) is also supported. We
2114 could rewrite the above example as follows:
2115 <pre>
2116 (?&#60;pn&#62; \( ( [^()]++ | (?&pn) )* \) )
2117 </pre>
2118 If there is more than one subpattern with the same name, the earliest one is
2119 used.
2120 </P>
2121 <P>
2122 This particular example pattern that we have been looking at contains nested
2123 unlimited repeats, and so the use of a possessive quantifier for matching
2124 strings of non-parentheses is important when applying the pattern to strings
2125 that do not match. For example, when this pattern is applied to
2126 <pre>
2127 (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()
2128 </pre>
2129 it yields "no match" quickly. However, if a possessive quantifier is not used,
2130 the match runs for a very long time indeed because there are so many different
2131 ways the + and * repeats can carve up the subject, and all have to be tested
2132 before failure can be reported.
2133 </P>
2134 <P>
2135 At the end of a match, the values of capturing parentheses are those from
2136 the outermost level. If you want to obtain intermediate values, a callout
2137 function can be used (see below and the
2138 <a href="pcrecallout.html"><b>pcrecallout</b></a>
2139 documentation). If the pattern above is matched against
2140 <pre>
2141 (ab(cd)ef)
2142 </pre>
2143 the value for the inner capturing parentheses (numbered 2) is "ef", which is
2144 the last value taken on at the top level. If a capturing subpattern is not
2145 matched at the top level, its final value is unset, even if it is (temporarily)
2146 set at a deeper level.
2147 </P>
2148 <P>
2149 If there are more than 15 capturing parentheses in a pattern, PCRE has to
2150 obtain extra memory to store data during a recursion, which it does by using
2151 <b>pcre_malloc</b>, freeing it via <b>pcre_free</b> afterwards. If no memory can
2152 be obtained, the match fails with the PCRE_ERROR_NOMEMORY error.
2153 </P>
2154 <P>
2155 Do not confuse the (?R) item with the condition (R), which tests for recursion.
2156 Consider this pattern, which matches text in angle brackets, allowing for
2157 arbitrary nesting. Only digits are allowed in nested brackets (that is, when
2158 recursing), whereas any characters are permitted at the outer level.
2159 <pre>
2160 &#60; (?: (?(R) \d++ | [^&#60;&#62;]*+) | (?R)) * &#62;
2161 </pre>
2162 In this pattern, (?(R) is the start of a conditional subpattern, with two
2163 different alternatives for the recursive and non-recursive cases. The (?R) item
2164 is the actual recursive call.
2165 <a name="recursiondifference"></a></P>
2166 <br><b>
2167 Recursion difference from Perl
2168 </b><br>
2169 <P>
2170 In PCRE (like Python, but unlike Perl), a recursive subpattern call is always
2171 treated as an atomic group. That is, once it has matched some of the subject
2172 string, it is never re-entered, even if it contains untried alternatives and
2173 there is a subsequent matching failure. This can be illustrated by the
2174 following pattern, which purports to match a palindromic string that contains
2175 an odd number of characters (for example, "a", "aba", "abcba", "abcdcba"):
2176 <pre>
2177 ^(.|(.)(?1)\2)$
2178 </pre>
2179 The idea is that it either matches a single character, or two identical
2180 characters surrounding a sub-palindrome. In Perl, this pattern works; in PCRE
2181 it does not if the pattern is longer than three characters. Consider the
2182 subject string "abcba":
2183 </P>
2184 <P>
2185 At the top level, the first character is matched, but as it is not at the end
2186 of the string, the first alternative fails; the second alternative is taken
2187 and the recursion kicks in. The recursive call to subpattern 1 successfully
2188 matches the next character ("b"). (Note that the beginning and end of line
2189 tests are not part of the recursion).
2190 </P>
2191 <P>
2192 Back at the top level, the next character ("c") is compared with what
2193 subpattern 2 matched, which was "a". This fails. Because the recursion is
2194 treated as an atomic group, there are now no backtracking points, and so the
2195 entire match fails. (Perl is able, at this point, to re-enter the recursion and
2196 try the second alternative.) However, if the pattern is written with the
2197 alternatives in the other order, things are different:
2198 <pre>
2199 ^((.)(?1)\2|.)$
2200 </pre>
2201 This time, the recursing alternative is tried first, and continues to recurse
2202 until it runs out of characters, at which point the recursion fails. But this
2203 time we do have another alternative to try at the higher level. That is the big
2204 difference: in the previous case the remaining alternative is at a deeper
2205 recursion level, which PCRE cannot use.
2206 </P>
2207 <P>
2208 To change the pattern so that matches all palindromic strings, not just those
2209 with an odd number of characters, it is tempting to change the pattern to this:
2210 <pre>
2211 ^((.)(?1)\2|.?)$
2212 </pre>
2213 Again, this works in Perl, but not in PCRE, and for the same reason. When a
2214 deeper recursion has matched a single character, it cannot be entered again in
2215 order to match an empty string. The solution is to separate the two cases, and
2216 write out the odd and even cases as alternatives at the higher level:
2217 <pre>
2218 ^(?:((.)(?1)\2|)|((.)(?3)\4|.))
2219 </pre>
2220 If you want to match typical palindromic phrases, the pattern has to ignore all
2221 non-word characters, which can be done like this:
2222 <pre>
2223 ^\W*+(?:((.)\W*+(?1)\W*+\2|)|((.)\W*+(?3)\W*+\4|\W*+.\W*+))\W*+$
2224 </pre>
2225 If run with the PCRE_CASELESS option, this pattern matches phrases such as "A
2226 man, a plan, a canal: Panama!" and it works well in both PCRE and Perl. Note
2227 the use of the possessive quantifier *+ to avoid backtracking into sequences of
2228 non-word characters. Without this, PCRE takes a great deal longer (ten times or
2229 more) to match typical phrases, and Perl takes so long that you think it has
2230 gone into a loop.
2231 </P>
2232 <P>
2233 <b>WARNING</b>: The palindrome-matching patterns above work only if the subject
2234 string does not start with a palindrome that is shorter than the entire string.
2235 For example, although "abcba" is correctly matched, if the subject is "ababa",
2236 PCRE finds the palindrome "aba" at the start, then fails at top level because
2237 the end of the string does not follow. Once again, it cannot jump back into the
2238 recursion to try other alternatives, so the entire match fails.
2239 <a name="subpatternsassubroutines"></a></P>
2240 <br><a name="SEC22" href="#TOC1">SUBPATTERNS AS SUBROUTINES</a><br>
2241 <P>
2242 If the syntax for a recursive subpattern reference (either by number or by
2243 name) is used outside the parentheses to which it refers, it operates like a
2244 subroutine in a programming language. The "called" subpattern may be defined
2245 before or after the reference. A numbered reference can be absolute or
2246 relative, as in these examples:
2247 <pre>
2248 (...(absolute)...)...(?2)...
2249 (...(relative)...)...(?-1)...
2250 (...(?+1)...(relative)...
2251 </pre>
2252 An earlier example pointed out that the pattern
2253 <pre>
2254 (sens|respons)e and \1ibility
2255 </pre>
2256 matches "sense and sensibility" and "response and responsibility", but not
2257 "sense and responsibility". If instead the pattern
2258 <pre>
2259 (sens|respons)e and (?1)ibility
2260 </pre>
2261 is used, it does match "sense and responsibility" as well as the other two
2262 strings. Another example is given in the discussion of DEFINE above.
2263 </P>
2264 <P>
2265 Like recursive subpatterns, a subroutine call is always treated as an atomic
2266 group. That is, once it has matched some of the subject string, it is never
2267 re-entered, even if it contains untried alternatives and there is a subsequent
2268 matching failure. Any capturing parentheses that are set during the subroutine
2269 call revert to their previous values afterwards.
2270 </P>
2271 <P>
2272 When a subpattern is used as a subroutine, processing options such as
2273 case-independence are fixed when the subpattern is defined. They cannot be
2274 changed for different calls. For example, consider this pattern:
2275 <pre>
2276 (abc)(?i:(?-1))
2277 </pre>
2278 It matches "abcabc". It does not match "abcABC" because the change of
2279 processing option does not affect the called subpattern.
2280 <a name="onigurumasubroutines"></a></P>
2281 <br><a name="SEC23" href="#TOC1">ONIGURUMA SUBROUTINE SYNTAX</a><br>
2282 <P>
2283 For compatibility with Oniguruma, the non-Perl syntax \g followed by a name or
2284 a number enclosed either in angle brackets or single quotes, is an alternative
2285 syntax for referencing a subpattern as a subroutine, possibly recursively. Here
2286 are two of the examples used above, rewritten using this syntax:
2287 <pre>
2288 (?&#60;pn&#62; \( ( (?&#62;[^()]+) | \g&#60;pn&#62; )* \) )
2289 (sens|respons)e and \g'1'ibility
2290 </pre>
2291 PCRE supports an extension to Oniguruma: if a number is preceded by a
2292 plus or a minus sign it is taken as a relative reference. For example:
2293 <pre>
2294 (abc)(?i:\g&#60;-1&#62;)
2295 </pre>
2296 Note that \g{...} (Perl syntax) and \g&#60;...&#62; (Oniguruma syntax) are <i>not</i>
2297 synonymous. The former is a back reference; the latter is a subroutine call.
2298 </P>
2299 <br><a name="SEC24" href="#TOC1">CALLOUTS</a><br>
2300 <P>
2301 Perl has a feature whereby using the sequence (?{...}) causes arbitrary Perl
2302 code to be obeyed in the middle of matching a regular expression. This makes it
2303 possible, amongst other things, to extract different substrings that match the
2304 same pair of parentheses when there is a repetition.
2305 </P>
2306 <P>
2307 PCRE provides a similar feature, but of course it cannot obey arbitrary Perl
2308 code. The feature is called "callout". The caller of PCRE provides an external
2309 function by putting its entry point in the global variable <i>pcre_callout</i>.
2310 By default, this variable contains NULL, which disables all calling out.
2311 </P>
2312 <P>
2313 Within a regular expression, (?C) indicates the points at which the external
2314 function is to be called. If you want to identify different callout points, you
2315 can put a number less than 256 after the letter C. The default value is zero.
2316 For example, this pattern has two callout points:
2317 <pre>
2318 (?C1)abc(?C2)def
2319 </pre>
2320 If the PCRE_AUTO_CALLOUT flag is passed to <b>pcre_compile()</b>, callouts are
2321 automatically installed before each item in the pattern. They are all numbered
2322 255.
2323 </P>
2324 <P>
2325 During matching, when PCRE reaches a callout point (and <i>pcre_callout</i> is
2326 set), the external function is called. It is provided with the number of the
2327 callout, the position in the pattern, and, optionally, one item of data
2328 originally supplied by the caller of <b>pcre_exec()</b>. The callout function
2329 may cause matching to proceed, to backtrack, or to fail altogether. A complete
2330 description of the interface to the callout function is given in the
2331 <a href="pcrecallout.html"><b>pcrecallout</b></a>
2332 documentation.
2333 <a name="backtrackcontrol"></a></P>
2334 <br><a name="SEC25" href="#TOC1">BACKTRACKING CONTROL</a><br>
2335 <P>
2336 Perl 5.10 introduced a number of "Special Backtracking Control Verbs", which
2337 are described in the Perl documentation as "experimental and subject to change
2338 or removal in a future version of Perl". It goes on to say: "Their usage in
2339 production code should be noted to avoid problems during upgrades." The same
2340 remarks apply to the PCRE features described in this section.
2341 </P>
2342 <P>
2343 Since these verbs are specifically related to backtracking, most of them can be
2344 used only when the pattern is to be matched using <b>pcre_exec()</b>, which uses
2345 a backtracking algorithm. With the exception of (*FAIL), which behaves like a
2346 failing negative assertion, they cause an error if encountered by
2347 <b>pcre_dfa_exec()</b>.
2348 </P>
2349 <P>
2350 If any of these verbs are used in an assertion or subroutine subpattern
2351 (including recursive subpatterns), their effect is confined to that subpattern;
2352 it does not extend to the surrounding pattern. Note that such subpatterns are
2353 processed as anchored at the point where they are tested.
2354 </P>
2355 <P>
2356 The new verbs make use of what was previously invalid syntax: an opening
2357 parenthesis followed by an asterisk. They are generally of the form
2358 (*VERB) or (*VERB:NAME). Some may take either form, with differing behaviour,
2359 depending on whether or not an argument is present. An name is a sequence of
2360 letters, digits, and underscores. If the name is empty, that is, if the closing
2361 parenthesis immediately follows the colon, the effect is as if the colon were
2362 not there. Any number of these verbs may occur in a pattern.
2363 </P>
2364 <P>
2365 PCRE contains some optimizations that are used to speed up matching by running
2366 some checks at the start of each match attempt. For example, it may know the
2367 minimum length of matching subject, or that a particular character must be
2368 present. When one of these optimizations suppresses the running of a match, any
2369 included backtracking verbs will not, of course, be processed. You can suppress
2370 the start-of-match optimizations by setting the PCRE_NO_START_OPTIMIZE option
2371 when calling <b>pcre_exec()</b>.
2372 </P>
2373 <br><b>
2374 Verbs that act immediately
2375 </b><br>
2376 <P>
2377 The following verbs act as soon as they are encountered. They may not be
2378 followed by a name.
2379 <pre>
2380 (*ACCEPT)
2381 </pre>
2382 This verb causes the match to end successfully, skipping the remainder of the
2383 pattern. When inside a recursion, only the innermost pattern is ended
2384 immediately. If (*ACCEPT) is inside capturing parentheses, the data so far is
2385 captured. (This feature was added to PCRE at release 8.00.) For example:
2386 <pre>
2387 A((?:A|B(*ACCEPT)|C)D)
2388 </pre>
2389 This matches "AB", "AAD", or "ACD"; when it matches "AB", "B" is captured by
2390 the outer parentheses.
2391 <pre>
2392 (*FAIL) or (*F)
2393 </pre>
2394 This verb causes the match to fail, forcing backtracking to occur. It is
2395 equivalent to (?!) but easier to read. The Perl documentation notes that it is
2396 probably useful only when combined with (?{}) or (??{}). Those are, of course,
2397 Perl features that are not present in PCRE. The nearest equivalent is the
2398 callout feature, as for example in this pattern:
2399 <pre>
2400 a+(?C)(*FAIL)
2401 </pre>
2402 A match with the string "aaaa" always fails, but the callout is taken before
2403 each backtrack happens (in this example, 10 times).
2404 </P>
2405 <br><b>
2406 Recording which path was taken
2407 </b><br>
2408 <P>
2409 There is one verb whose main purpose is to track how a match was arrived at,
2410 though it also has a secondary use in conjunction with advancing the match
2411 starting point (see (*SKIP) below).
2412 <pre>
2413 (*MARK:NAME) or (*:NAME)
2414 </pre>
2415 A name is always required with this verb. There may be as many instances of
2416 (*MARK) as you like in a pattern, and their names do not have to be unique.
2417 </P>
2418 <P>
2419 When a match succeeds, the name of the last-encountered (*MARK) is passed back
2420 to the caller via the <i>pcre_extra</i> data structure, as described in the
2421 <a href="pcreapi.html#extradata">section on <i>pcre_extra</i></a>
2422 in the
2423 <a href="pcreapi.html"><b>pcreapi</b></a>
2424 documentation. No data is returned for a partial match. Here is an example of
2425 <b>pcretest</b> output, where the /K modifier requests the retrieval and
2426 outputting of (*MARK) data:
2427 <pre>
2428 /X(*MARK:A)Y|X(*MARK:B)Z/K
2429 XY
2430 0: XY
2431 MK: A
2432 XZ
2433 0: XZ
2434 MK: B
2435 </pre>
2436 The (*MARK) name is tagged with "MK:" in this output, and in this example it
2437 indicates which of the two alternatives matched. This is a more efficient way
2438 of obtaining this information than putting each alternative in its own
2439 capturing parentheses.
2440 </P>
2441 <P>
2442 A name may also be returned after a failed match if the final path through the
2443 pattern involves (*MARK). However, unless (*MARK) used in conjunction with
2444 (*COMMIT), this is unlikely to happen for an unanchored pattern because, as the
2445 starting point for matching is advanced, the final check is often with an empty
2446 string, causing a failure before (*MARK) is reached. For example:
2447 <pre>
2448 /X(*MARK:A)Y|X(*MARK:B)Z/K
2449 XP
2450 No match
2451 </pre>
2452 There are three potential starting points for this match (starting with X,
2453 starting with P, and with an empty string). If the pattern is anchored, the
2454 result is different:
2455 <pre>
2456 /^X(*MARK:A)Y|^X(*MARK:B)Z/K
2457 XP
2458 No match, mark = B
2459 </pre>
2460 PCRE's start-of-match optimizations can also interfere with this. For example,
2461 if, as a result of a call to <b>pcre_study()</b>, it knows the minimum
2462 subject length for a match, a shorter subject will not be scanned at all.
2463 </P>
2464 <P>
2465 Note that similar anomalies (though different in detail) exist in Perl, no
2466 doubt for the same reasons. The use of (*MARK) data after a failed match of an
2467 unanchored pattern is not recommended, unless (*COMMIT) is involved.
2468 </P>
2469 <br><b>
2470 Verbs that act after backtracking
2471 </b><br>
2472 <P>
2473 The following verbs do nothing when they are encountered. Matching continues
2474 with what follows, but if there is no subsequent match, causing a backtrack to
2475 the verb, a failure is forced. That is, backtracking cannot pass to the left of
2476 the verb. However, when one of these verbs appears inside an atomic group, its
2477 effect is confined to that group, because once the group has been matched,
2478 there is never any backtracking into it. In this situation, backtracking can
2479 "jump back" to the left of the entire atomic group. (Remember also, as stated
2480 above, that this localization also applies in subroutine calls and assertions.)
2481 </P>
2482 <P>
2483 These verbs differ in exactly what kind of failure occurs when backtracking
2484 reaches them.
2485 <pre>
2486 (*COMMIT)
2487 </pre>
2488 This verb, which may not be followed by a name, causes the whole match to fail
2489 outright if the rest of the pattern does not match. Even if the pattern is
2490 unanchored, no further attempts to find a match by advancing the starting point
2491 take place. Once (*COMMIT) has been passed, <b>pcre_exec()</b> is committed to
2492 finding a match at the current starting point, or not at all. For example:
2493 <pre>
2494 a+(*COMMIT)b
2495 </pre>
2496 This matches "xxaab" but not "aacaab". It can be thought of as a kind of
2497 dynamic anchor, or "I've started, so I must finish." The name of the most
2498 recently passed (*MARK) in the path is passed back when (*COMMIT) forces a
2499 match failure.
2500 </P>
2501 <P>
2502 Note that (*COMMIT) at the start of a pattern is not the same as an anchor,
2503 unless PCRE's start-of-match optimizations are turned off, as shown in this
2504 <b>pcretest</b> example:
2505 <pre>
2506 /(*COMMIT)abc/
2507 xyzabc
2508 0: abc
2509 xyzabc\Y
2510 No match
2511 </pre>
2512 PCRE knows that any match must start with "a", so the optimization skips along
2513 the subject to "a" before running the first match attempt, which succeeds. When
2514 the optimization is disabled by the \Y escape in the second subject, the match
2515 starts at "x" and so the (*COMMIT) causes it to fail without trying any other
2516 starting points.
2517 <pre>
2518 (*PRUNE) or (*PRUNE:NAME)
2519 </pre>
2520 This verb causes the match to fail at the current starting position in the
2521 subject if the rest of the pattern does not match. If the pattern is
2522 unanchored, the normal "bumpalong" advance to the next starting character then
2523 happens. Backtracking can occur as usual to the left of (*PRUNE), before it is
2524 reached, or when matching to the right of (*PRUNE), but if there is no match to
2525 the right, backtracking cannot cross (*PRUNE). In simple cases, the use of
2526 (*PRUNE) is just an alternative to an atomic group or possessive quantifier,
2527 but there are some uses of (*PRUNE) that cannot be expressed in any other way.
2528 The behaviour of (*PRUNE:NAME) is the same as (*MARK:NAME)(*PRUNE) when the
2529 match fails completely; the name is passed back if this is the final attempt.
2530 (*PRUNE:NAME) does not pass back a name if the match succeeds. In an anchored
2531 pattern (*PRUNE) has the same effect as (*COMMIT).
2532 <pre>
2533 (*SKIP)
2534 </pre>
2535 This verb, when given without a name, is like (*PRUNE), except that if the
2536 pattern is unanchored, the "bumpalong" advance is not to the next character,
2537 but to the position in the subject where (*SKIP) was encountered. (*SKIP)
2538 signifies that whatever text was matched leading up to it cannot be part of a
2539 successful match. Consider:
2540 <pre>
2541 a+(*SKIP)b
2542 </pre>
2543 If the subject is "aaaac...", after the first match attempt fails (starting at
2544 the first character in the string), the starting point skips on to start the
2545 next attempt at "c". Note that a possessive quantifer does not have the same
2546 effect as this example; although it would suppress backtracking during the
2547 first match attempt, the second attempt would start at the second character
2548 instead of skipping on to "c".
2549 <pre>
2550 (*SKIP:NAME)
2551 </pre>
2552 When (*SKIP) has an associated name, its behaviour is modified. If the
2553 following pattern fails to match, the previous path through the pattern is
2554 searched for the most recent (*MARK) that has the same name. If one is found,
2555 the "bumpalong" advance is to the subject position that corresponds to that
2556 (*MARK) instead of to where (*SKIP) was encountered. If no (*MARK) with a
2557 matching name is found, normal "bumpalong" of one character happens (the
2558 (*SKIP) is ignored).
2559 <pre>
2560 (*THEN) or (*THEN:NAME)
2561 </pre>
2562 This verb causes a skip to the next alternation if the rest of the pattern does
2563 not match. That is, it cancels pending backtracking, but only within the
2564 current alternation. Its name comes from the observation that it can be used
2565 for a pattern-based if-then-else block:
2566 <pre>
2567 ( COND1 (*THEN) FOO | COND2 (*THEN) BAR | COND3 (*THEN) BAZ ) ...
2568 </pre>
2569 If the COND1 pattern matches, FOO is tried (and possibly further items after
2570 the end of the group if FOO succeeds); on failure the matcher skips to the
2571 second alternative and tries COND2, without backtracking into COND1. The
2572 behaviour of (*THEN:NAME) is exactly the same as (*MARK:NAME)(*THEN) if the
2573 overall match fails. If (*THEN) is not directly inside an alternation, it acts
2574 like (*PRUNE).
2575 </P>
2576 <br><a name="SEC26" href="#TOC1">SEE ALSO</a><br>
2577 <P>
2578 <b>pcreapi</b>(3), <b>pcrecallout</b>(3), <b>pcrematching</b>(3),
2579 <b>pcresyntax</b>(3), <b>pcre</b>(3).
2580 </P>
2581 <br><a name="SEC27" href="#TOC1">AUTHOR</a><br>
2582 <P>
2583 Philip Hazel
2584 <br>
2585 University Computing Service
2586 <br>
2587 Cambridge CB2 3QH, England.
2588 <br>
2589 </P>
2590 <br><a name="SEC28" href="#TOC1">REVISION</a><br>
2591 <P>
2592 Last updated: 05 May 2010
2593 <br>
2594 Copyright &copy; 1997-2010 University of Cambridge.
2595 <br>
2596 <p>
2597 Return to the <a href="index.html">PCRE index page</a>.
2598 </p>


Name Value
svn:eol-style native
svn:keywords "Author Date Id Revision Url"

  ViewVC Help
Powered by ViewVC 1.1.5