/[pcre]/code/trunk/doc/html/pcrepattern.html
ViewVC logotype

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 182 - (show annotations)
Wed Jun 13 15:09:54 2007 UTC (12 years, 3 months ago) by ph10
File MIME type: text/html
File size: 83838 byte(s)
More document tidies, pre-release.
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">CHARACTERS AND METACHARACTERS</a>
18 <li><a name="TOC3" href="#SEC3">BACKSLASH</a>
19 <li><a name="TOC4" href="#SEC4">CIRCUMFLEX AND DOLLAR</a>
20 <li><a name="TOC5" href="#SEC5">FULL STOP (PERIOD, DOT)</a>
21 <li><a name="TOC6" href="#SEC6">MATCHING A SINGLE BYTE</a>
22 <li><a name="TOC7" href="#SEC7">SQUARE BRACKETS AND CHARACTER CLASSES</a>
23 <li><a name="TOC8" href="#SEC8">POSIX CHARACTER CLASSES</a>
24 <li><a name="TOC9" href="#SEC9">VERTICAL BAR</a>
25 <li><a name="TOC10" href="#SEC10">INTERNAL OPTION SETTING</a>
26 <li><a name="TOC11" href="#SEC11">SUBPATTERNS</a>
27 <li><a name="TOC12" href="#SEC12">DUPLICATE SUBPATTERN NUMBERS</a>
28 <li><a name="TOC13" href="#SEC13">NAMED SUBPATTERNS</a>
29 <li><a name="TOC14" href="#SEC14">REPETITION</a>
30 <li><a name="TOC15" href="#SEC15">ATOMIC GROUPING AND POSSESSIVE QUANTIFIERS</a>
31 <li><a name="TOC16" href="#SEC16">BACK REFERENCES</a>
32 <li><a name="TOC17" href="#SEC17">ASSERTIONS</a>
33 <li><a name="TOC18" href="#SEC18">CONDITIONAL SUBPATTERNS</a>
34 <li><a name="TOC19" href="#SEC19">COMMENTS</a>
35 <li><a name="TOC20" href="#SEC20">RECURSIVE PATTERNS</a>
36 <li><a name="TOC21" href="#SEC21">SUBPATTERNS AS SUBROUTINES</a>
37 <li><a name="TOC22" href="#SEC22">CALLOUTS</a>
38 <li><a name="TOC23" href="#SEC23">SEE ALSO</a>
39 <li><a name="TOC24" href="#SEC24">AUTHOR</a>
40 <li><a name="TOC25" href="#SEC25">REVISION</a>
41 </ul>
42 <br><a name="SEC1" href="#TOC1">PCRE REGULAR EXPRESSION DETAILS</a><br>
43 <P>
44 The syntax and semantics of the regular expressions supported by PCRE are
45 described below. Regular expressions are also described in the Perl
46 documentation and in a number of books, some of which have copious examples.
47 Jeffrey Friedl's "Mastering Regular Expressions", published by O'Reilly, covers
48 regular expressions in great detail. This description of PCRE's regular
49 expressions is intended as reference material.
50 </P>
51 <P>
52 The original operation of PCRE was on strings of one-byte characters. However,
53 there is now also support for UTF-8 character strings. To use this, you must
54 build PCRE to include UTF-8 support, and then call <b>pcre_compile()</b> with
55 the PCRE_UTF8 option. How this affects pattern matching is mentioned in several
56 places below. There is also a summary of UTF-8 features in the
57 <a href="pcre.html#utf8support">section on UTF-8 support</a>
58 in the main
59 <a href="pcre.html"><b>pcre</b></a>
60 page.
61 </P>
62 <P>
63 The remainder of this document discusses the patterns that are supported by
64 PCRE when its main matching function, <b>pcre_exec()</b>, is used.
65 From release 6.0, PCRE offers a second matching function,
66 <b>pcre_dfa_exec()</b>, which matches using a different algorithm that is not
67 Perl-compatible. Some of the features discussed below are not available when
68 <b>pcre_dfa_exec()</b> is used. The advantages and disadvantages of the
69 alternative function, and how it differs from the normal function, are
70 discussed in the
71 <a href="pcrematching.html"><b>pcrematching</b></a>
72 page.
73 </P>
74 <br><a name="SEC2" href="#TOC1">CHARACTERS AND METACHARACTERS</a><br>
75 <P>
76 A regular expression is a pattern that is matched against a subject string from
77 left to right. Most characters stand for themselves in a pattern, and match the
78 corresponding characters in the subject. As a trivial example, the pattern
79 <pre>
80 The quick brown fox
81 </pre>
82 matches a portion of a subject string that is identical to itself. When
83 caseless matching is specified (the PCRE_CASELESS option), letters are matched
84 independently of case. In UTF-8 mode, PCRE always understands the concept of
85 case for characters whose values are less than 128, so caseless matching is
86 always possible. For characters with higher values, the concept of case is
87 supported if PCRE is compiled with Unicode property support, but not otherwise.
88 If you want to use caseless matching for characters 128 and above, you must
89 ensure that PCRE is compiled with Unicode property support as well as with
90 UTF-8 support.
91 </P>
92 <P>
93 The power of regular expressions comes from the ability to include alternatives
94 and repetitions in the pattern. These are encoded in the pattern by the use of
95 <i>metacharacters</i>, which do not stand for themselves but instead are
96 interpreted in some special way.
97 </P>
98 <P>
99 There are two different sets of metacharacters: those that are recognized
100 anywhere in the pattern except within square brackets, and those that are
101 recognized within square brackets. Outside square brackets, the metacharacters
102 are as follows:
103 <pre>
104 \ general escape character with several uses
105 ^ assert start of string (or line, in multiline mode)
106 $ assert end of string (or line, in multiline mode)
107 . match any character except newline (by default)
108 [ start character class definition
109 | start of alternative branch
110 ( start subpattern
111 ) end subpattern
112 ? extends the meaning of (
113 also 0 or 1 quantifier
114 also quantifier minimizer
115 * 0 or more quantifier
116 + 1 or more quantifier
117 also "possessive quantifier"
118 { start min/max quantifier
119 </pre>
120 Part of a pattern that is in square brackets is called a "character class". In
121 a character class the only metacharacters are:
122 <pre>
123 \ general escape character
124 ^ negate the class, but only if the first character
125 - indicates character range
126 [ POSIX character class (only if followed by POSIX syntax)
127 ] terminates the character class
128 </pre>
129 The following sections describe the use of each of the metacharacters.
130 </P>
131 <br><a name="SEC3" href="#TOC1">BACKSLASH</a><br>
132 <P>
133 The backslash character has several uses. Firstly, if it is followed by a
134 non-alphanumeric character, it takes away any special meaning that character
135 may have. This use of backslash as an escape character applies both inside and
136 outside character classes.
137 </P>
138 <P>
139 For example, if you want to match a * character, you write \* in the pattern.
140 This escaping action applies whether or not the following character would
141 otherwise be interpreted as a metacharacter, so it is always safe to precede a
142 non-alphanumeric with backslash to specify that it stands for itself. In
143 particular, if you want to match a backslash, you write \\.
144 </P>
145 <P>
146 If a pattern is compiled with the PCRE_EXTENDED option, whitespace in the
147 pattern (other than in a character class) and characters between a # outside
148 a character class and the next newline are ignored. An escaping backslash can
149 be used to include a whitespace or # character as part of the pattern.
150 </P>
151 <P>
152 If you want to remove the special meaning from a sequence of characters, you
153 can do so by putting them between \Q and \E. This is different from Perl in
154 that $ and @ are handled as literals in \Q...\E sequences in PCRE, whereas in
155 Perl, $ and @ cause variable interpolation. Note the following examples:
156 <pre>
157 Pattern PCRE matches Perl matches
158
159 \Qabc$xyz\E abc$xyz abc followed by the contents of $xyz
160 \Qabc\$xyz\E abc\$xyz abc\$xyz
161 \Qabc\E\$\Qxyz\E abc$xyz abc$xyz
162 </pre>
163 The \Q...\E sequence is recognized both inside and outside character classes.
164 <a name="digitsafterbackslash"></a></P>
165 <br><b>
166 Non-printing characters
167 </b><br>
168 <P>
169 A second use of backslash provides a way of encoding non-printing characters
170 in patterns in a visible manner. There is no restriction on the appearance of
171 non-printing characters, apart from the binary zero that terminates a pattern,
172 but when a pattern is being prepared by text editing, it is usually easier to
173 use one of the following escape sequences than the binary character it
174 represents:
175 <pre>
176 \a alarm, that is, the BEL character (hex 07)
177 \cx "control-x", where x is any character
178 \e escape (hex 1B)
179 \f formfeed (hex 0C)
180 \n newline (hex 0A)
181 \r carriage return (hex 0D)
182 \t tab (hex 09)
183 \ddd character with octal code ddd, or backreference
184 \xhh character with hex code hh
185 \x{hhh..} character with hex code hhh..
186 </pre>
187 The precise effect of \cx is as follows: if x is a lower case letter, it
188 is converted to upper case. Then bit 6 of the character (hex 40) is inverted.
189 Thus \cz becomes hex 1A, but \c{ becomes hex 3B, while \c; becomes hex
190 7B.
191 </P>
192 <P>
193 After \x, from zero to two hexadecimal digits are read (letters can be in
194 upper or lower case). Any number of hexadecimal digits may appear between \x{
195 and }, but the value of the character code must be less than 256 in non-UTF-8
196 mode, and less than 2**31 in UTF-8 mode (that is, the maximum hexadecimal value
197 is 7FFFFFFF). If characters other than hexadecimal digits appear between \x{
198 and }, or if there is no terminating }, this form of escape is not recognized.
199 Instead, the initial \x will be interpreted as a basic hexadecimal escape,
200 with no following digits, giving a character whose value is zero.
201 </P>
202 <P>
203 Characters whose value is less than 256 can be defined by either of the two
204 syntaxes for \x. There is no difference in the way they are handled. For
205 example, \xdc is exactly the same as \x{dc}.
206 </P>
207 <P>
208 After \0 up to two further octal digits are read. If there are fewer than two
209 digits, just those that are present are used. Thus the sequence \0\x\07
210 specifies two binary zeros followed by a BEL character (code value 7). Make
211 sure you supply two digits after the initial zero if the pattern character that
212 follows is itself an octal digit.
213 </P>
214 <P>
215 The handling of a backslash followed by a digit other than 0 is complicated.
216 Outside a character class, PCRE reads it and any following digits as a decimal
217 number. If the number is less than 10, or if there have been at least that many
218 previous capturing left parentheses in the expression, the entire sequence is
219 taken as a <i>back reference</i>. A description of how this works is given
220 <a href="#backreferences">later,</a>
221 following the discussion of
222 <a href="#subpattern">parenthesized subpatterns.</a>
223 </P>
224 <P>
225 Inside a character class, or if the decimal number is greater than 9 and there
226 have not been that many capturing subpatterns, PCRE re-reads up to three octal
227 digits following the backslash, and uses them to generate a data character. Any
228 subsequent digits stand for themselves. In non-UTF-8 mode, the value of a
229 character specified in octal must be less than \400. In UTF-8 mode, values up
230 to \777 are permitted. For example:
231 <pre>
232 \040 is another way of writing a space
233 \40 is the same, provided there are fewer than 40 previous capturing subpatterns
234 \7 is always a back reference
235 \11 might be a back reference, or another way of writing a tab
236 \011 is always a tab
237 \0113 is a tab followed by the character "3"
238 \113 might be a back reference, otherwise the character with octal code 113
239 \377 might be a back reference, otherwise the byte consisting entirely of 1 bits
240 \81 is either a back reference, or a binary zero followed by the two characters "8" and "1"
241 </pre>
242 Note that octal values of 100 or greater must not be introduced by a leading
243 zero, because no more than three octal digits are ever read.
244 </P>
245 <P>
246 All the sequences that define a single character value can be used both inside
247 and outside character classes. In addition, inside a character class, the
248 sequence \b is interpreted as the backspace character (hex 08), and the
249 sequences \R and \X are interpreted as the characters "R" and "X",
250 respectively. Outside a character class, these sequences have different
251 meanings
252 <a href="#uniextseq">(see below).</a>
253 </P>
254 <br><b>
255 Absolute and relative back references
256 </b><br>
257 <P>
258 The sequence \g followed by a positive or negative number, optionally enclosed
259 in braces, is an absolute or relative back reference. A named back reference
260 can be coded as \g{name}. Back references are discussed
261 <a href="#backreferences">later,</a>
262 following the discussion of
263 <a href="#subpattern">parenthesized subpatterns.</a>
264 </P>
265 <br><b>
266 Generic character types
267 </b><br>
268 <P>
269 Another use of backslash is for specifying generic character types. The
270 following are always recognized:
271 <pre>
272 \d any decimal digit
273 \D any character that is not a decimal digit
274 \h any horizontal whitespace character
275 \H any character that is not a horizontal whitespace character
276 \s any whitespace character
277 \S any character that is not a whitespace character
278 \v any vertical whitespace character
279 \V any character that is not a vertical whitespace character
280 \w any "word" character
281 \W any "non-word" character
282 </pre>
283 Each pair of escape sequences partitions the complete set of characters into
284 two disjoint sets. Any given character matches one, and only one, of each pair.
285 </P>
286 <P>
287 These character type sequences can appear both inside and outside character
288 classes. They each match one character of the appropriate type. If the current
289 matching point is at the end of the subject string, all of them fail, since
290 there is no character to match.
291 </P>
292 <P>
293 For compatibility with Perl, \s does not match the VT character (code 11).
294 This makes it different from the the POSIX "space" class. The \s characters
295 are HT (9), LF (10), FF (12), CR (13), and space (32). If "use locale;" is
296 included in a Perl script, \s may match the VT character. In PCRE, it never
297 does.
298 </P>
299 <P>
300 In UTF-8 mode, characters with values greater than 128 never match \d, \s, or
301 \w, and always match \D, \S, and \W. This is true even when Unicode
302 character property support is available. These sequences retain their original
303 meanings from before UTF-8 support was available, mainly for efficiency
304 reasons.
305 </P>
306 <P>
307 The sequences \h, \H, \v, and \V are Perl 5.10 features. In contrast to the
308 other sequences, these do match certain high-valued codepoints in UTF-8 mode.
309 The horizontal space characters are:
310 <pre>
311 U+0009 Horizontal tab
312 U+0020 Space
313 U+00A0 Non-break space
314 U+1680 Ogham space mark
315 U+180E Mongolian vowel separator
316 U+2000 En quad
317 U+2001 Em quad
318 U+2002 En space
319 U+2003 Em space
320 U+2004 Three-per-em space
321 U+2005 Four-per-em space
322 U+2006 Six-per-em space
323 U+2007 Figure space
324 U+2008 Punctuation space
325 U+2009 Thin space
326 U+200A Hair space
327 U+202F Narrow no-break space
328 U+205F Medium mathematical space
329 U+3000 Ideographic space
330 </pre>
331 The vertical space characters are:
332 <pre>
333 U+000A Linefeed
334 U+000B Vertical tab
335 U+000C Formfeed
336 U+000D Carriage return
337 U+0085 Next line
338 U+2028 Line separator
339 U+2029 Paragraph separator
340 </PRE>
341 </P>
342 <P>
343 A "word" character is an underscore or any character less than 256 that is a
344 letter or digit. The definition of letters and digits is controlled by PCRE's
345 low-valued character tables, and may vary if locale-specific matching is taking
346 place (see
347 <a href="pcreapi.html#localesupport">"Locale support"</a>
348 in the
349 <a href="pcreapi.html"><b>pcreapi</b></a>
350 page). For example, in a French locale such as "fr_FR" in Unix-like systems,
351 or "french" in Windows, some character codes greater than 128 are used for
352 accented letters, and these are matched by \w. The use of locales with Unicode
353 is discouraged.
354 </P>
355 <br><b>
356 Newline sequences
357 </b><br>
358 <P>
359 Outside a character class, the escape sequence \R matches any Unicode newline
360 sequence. This is a Perl 5.10 feature. In non-UTF-8 mode \R is equivalent to
361 the following:
362 <pre>
363 (?&#62;\r\n|\n|\x0b|\f|\r|\x85)
364 </pre>
365 This is an example of an "atomic group", details of which are given
366 <a href="#atomicgroup">below.</a>
367 This particular group matches either the two-character sequence CR followed by
368 LF, or one of the single characters LF (linefeed, U+000A), VT (vertical tab,
369 U+000B), FF (formfeed, U+000C), CR (carriage return, U+000D), or NEL (next
370 line, U+0085). The two-character sequence is treated as a single unit that
371 cannot be split.
372 </P>
373 <P>
374 In UTF-8 mode, two additional characters whose codepoints are greater than 255
375 are added: LS (line separator, U+2028) and PS (paragraph separator, U+2029).
376 Unicode character property support is not needed for these characters to be
377 recognized.
378 </P>
379 <P>
380 Inside a character class, \R matches the letter "R".
381 <a name="uniextseq"></a></P>
382 <br><b>
383 Unicode character properties
384 </b><br>
385 <P>
386 When PCRE is built with Unicode character property support, three additional
387 escape sequences to match character properties are available when UTF-8 mode
388 is selected. They are:
389 <pre>
390 \p{<i>xx</i>} a character with the <i>xx</i> property
391 \P{<i>xx</i>} a character without the <i>xx</i> property
392 \X an extended Unicode sequence
393 </pre>
394 The property names represented by <i>xx</i> above are limited to the Unicode
395 script names, the general category properties, and "Any", which matches any
396 character (including newline). Other properties such as "InMusicalSymbols" are
397 not currently supported by PCRE. Note that \P{Any} does not match any
398 characters, so always causes a match failure.
399 </P>
400 <P>
401 Sets of Unicode characters are defined as belonging to certain scripts. A
402 character from one of these sets can be matched using a script name. For
403 example:
404 <pre>
405 \p{Greek}
406 \P{Han}
407 </pre>
408 Those that are not part of an identified script are lumped together as
409 "Common". The current list of scripts is:
410 </P>
411 <P>
412 Arabic,
413 Armenian,
414 Balinese,
415 Bengali,
416 Bopomofo,
417 Braille,
418 Buginese,
419 Buhid,
420 Canadian_Aboriginal,
421 Cherokee,
422 Common,
423 Coptic,
424 Cuneiform,
425 Cypriot,
426 Cyrillic,
427 Deseret,
428 Devanagari,
429 Ethiopic,
430 Georgian,
431 Glagolitic,
432 Gothic,
433 Greek,
434 Gujarati,
435 Gurmukhi,
436 Han,
437 Hangul,
438 Hanunoo,
439 Hebrew,
440 Hiragana,
441 Inherited,
442 Kannada,
443 Katakana,
444 Kharoshthi,
445 Khmer,
446 Lao,
447 Latin,
448 Limbu,
449 Linear_B,
450 Malayalam,
451 Mongolian,
452 Myanmar,
453 New_Tai_Lue,
454 Nko,
455 Ogham,
456 Old_Italic,
457 Old_Persian,
458 Oriya,
459 Osmanya,
460 Phags_Pa,
461 Phoenician,
462 Runic,
463 Shavian,
464 Sinhala,
465 Syloti_Nagri,
466 Syriac,
467 Tagalog,
468 Tagbanwa,
469 Tai_Le,
470 Tamil,
471 Telugu,
472 Thaana,
473 Thai,
474 Tibetan,
475 Tifinagh,
476 Ugaritic,
477 Yi.
478 </P>
479 <P>
480 Each character has exactly one general category property, specified by a
481 two-letter abbreviation. For compatibility with Perl, negation can be specified
482 by including a circumflex between the opening brace and the property name. For
483 example, \p{^Lu} is the same as \P{Lu}.
484 </P>
485 <P>
486 If only one letter is specified with \p or \P, it includes all the general
487 category properties that start with that letter. In this case, in the absence
488 of negation, the curly brackets in the escape sequence are optional; these two
489 examples have the same effect:
490 <pre>
491 \p{L}
492 \pL
493 </pre>
494 The following general category property codes are supported:
495 <pre>
496 C Other
497 Cc Control
498 Cf Format
499 Cn Unassigned
500 Co Private use
501 Cs Surrogate
502
503 L Letter
504 Ll Lower case letter
505 Lm Modifier letter
506 Lo Other letter
507 Lt Title case letter
508 Lu Upper case letter
509
510 M Mark
511 Mc Spacing mark
512 Me Enclosing mark
513 Mn Non-spacing mark
514
515 N Number
516 Nd Decimal number
517 Nl Letter number
518 No Other number
519
520 P Punctuation
521 Pc Connector punctuation
522 Pd Dash punctuation
523 Pe Close punctuation
524 Pf Final punctuation
525 Pi Initial punctuation
526 Po Other punctuation
527 Ps Open punctuation
528
529 S Symbol
530 Sc Currency symbol
531 Sk Modifier symbol
532 Sm Mathematical symbol
533 So Other symbol
534
535 Z Separator
536 Zl Line separator
537 Zp Paragraph separator
538 Zs Space separator
539 </pre>
540 The special property L& is also supported: it matches a character that has
541 the Lu, Ll, or Lt property, in other words, a letter that is not classified as
542 a modifier or "other".
543 </P>
544 <P>
545 The long synonyms for these properties that Perl supports (such as \p{Letter})
546 are not supported by PCRE, nor is it permitted to prefix any of these
547 properties with "Is".
548 </P>
549 <P>
550 No character that is in the Unicode table has the Cn (unassigned) property.
551 Instead, this property is assumed for any code point that is not in the
552 Unicode table.
553 </P>
554 <P>
555 Specifying caseless matching does not affect these escape sequences. For
556 example, \p{Lu} always matches only upper case letters.
557 </P>
558 <P>
559 The \X escape matches any number of Unicode characters that form an extended
560 Unicode sequence. \X is equivalent to
561 <pre>
562 (?&#62;\PM\pM*)
563 </pre>
564 That is, it matches a character without the "mark" property, followed by zero
565 or more characters with the "mark" property, and treats the sequence as an
566 atomic group
567 <a href="#atomicgroup">(see below).</a>
568 Characters with the "mark" property are typically accents that affect the
569 preceding character.
570 </P>
571 <P>
572 Matching characters by Unicode property is not fast, because PCRE has to search
573 a structure that contains data for over fifteen thousand characters. That is
574 why the traditional escape sequences such as \d and \w do not use Unicode
575 properties in PCRE.
576 <a name="resetmatchstart"></a></P>
577 <br><b>
578 Resetting the match start
579 </b><br>
580 <P>
581 The escape sequence \K, which is a Perl 5.10 feature, causes any previously
582 matched characters not to be included in the final matched sequence. For
583 example, the pattern:
584 <pre>
585 foo\Kbar
586 </pre>
587 matches "foobar", but reports that it has matched "bar". This feature is
588 similar to a lookbehind assertion
589 <a href="#lookbehind">(described below).</a>
590 However, in this case, the part of the subject before the real match does not
591 have to be of fixed length, as lookbehind assertions do. The use of \K does
592 not interfere with the setting of
593 <a href="#subpattern">captured substrings.</a>
594 For example, when the pattern
595 <pre>
596 (foo)\Kbar
597 </pre>
598 matches "foobar", the first substring is still set to "foo".
599 <a name="smallassertions"></a></P>
600 <br><b>
601 Simple assertions
602 </b><br>
603 <P>
604 The final use of backslash is for certain simple assertions. An assertion
605 specifies a condition that has to be met at a particular point in a match,
606 without consuming any characters from the subject string. The use of
607 subpatterns for more complicated assertions is described
608 <a href="#bigassertions">below.</a>
609 The backslashed assertions are:
610 <pre>
611 \b matches at a word boundary
612 \B matches when not at a word boundary
613 \A matches at the start of the subject
614 \Z matches at the end of the subject
615 also matches before a newline at the end of the subject
616 \z matches only at the end of the subject
617 \G matches at the first matching position in the subject
618 </pre>
619 These assertions may not appear in character classes (but note that \b has a
620 different meaning, namely the backspace character, inside a character class).
621 </P>
622 <P>
623 A word boundary is a position in the subject string where the current character
624 and the previous character do not both match \w or \W (i.e. one matches
625 \w and the other matches \W), or the start or end of the string if the
626 first or last character matches \w, respectively.
627 </P>
628 <P>
629 The \A, \Z, and \z assertions differ from the traditional circumflex and
630 dollar (described in the next section) in that they only ever match at the very
631 start and end of the subject string, whatever options are set. Thus, they are
632 independent of multiline mode. These three assertions are not affected by the
633 PCRE_NOTBOL or PCRE_NOTEOL options, which affect only the behaviour of the
634 circumflex and dollar metacharacters. However, if the <i>startoffset</i>
635 argument of <b>pcre_exec()</b> is non-zero, indicating that matching is to start
636 at a point other than the beginning of the subject, \A can never match. The
637 difference between \Z and \z is that \Z matches before a newline at the end
638 of the string as well as at the very end, whereas \z matches only at the end.
639 </P>
640 <P>
641 The \G assertion is true only when the current matching position is at the
642 start point of the match, as specified by the <i>startoffset</i> argument of
643 <b>pcre_exec()</b>. It differs from \A when the value of <i>startoffset</i> is
644 non-zero. By calling <b>pcre_exec()</b> multiple times with appropriate
645 arguments, you can mimic Perl's /g option, and it is in this kind of
646 implementation where \G can be useful.
647 </P>
648 <P>
649 Note, however, that PCRE's interpretation of \G, as the start of the current
650 match, is subtly different from Perl's, which defines it as the end of the
651 previous match. In Perl, these can be different when the previously matched
652 string was empty. Because PCRE does just one match at a time, it cannot
653 reproduce this behaviour.
654 </P>
655 <P>
656 If all the alternatives of a pattern begin with \G, the expression is anchored
657 to the starting match position, and the "anchored" flag is set in the compiled
658 regular expression.
659 </P>
660 <br><a name="SEC4" href="#TOC1">CIRCUMFLEX AND DOLLAR</a><br>
661 <P>
662 Outside a character class, in the default matching mode, the circumflex
663 character is an assertion that is true only if the current matching point is
664 at the start of the subject string. If the <i>startoffset</i> argument of
665 <b>pcre_exec()</b> is non-zero, circumflex can never match if the PCRE_MULTILINE
666 option is unset. Inside a character class, circumflex has an entirely different
667 meaning
668 <a href="#characterclass">(see below).</a>
669 </P>
670 <P>
671 Circumflex need not be the first character of the pattern if a number of
672 alternatives are involved, but it should be the first thing in each alternative
673 in which it appears if the pattern is ever to match that branch. If all
674 possible alternatives start with a circumflex, that is, if the pattern is
675 constrained to match only at the start of the subject, it is said to be an
676 "anchored" pattern. (There are also other constructs that can cause a pattern
677 to be anchored.)
678 </P>
679 <P>
680 A dollar character is an assertion that is true only if the current matching
681 point is at the end of the subject string, or immediately before a newline
682 at the end of the string (by default). Dollar need not be the last character of
683 the pattern if a number of alternatives are involved, but it should be the last
684 item in any branch in which it appears. Dollar has no special meaning in a
685 character class.
686 </P>
687 <P>
688 The meaning of dollar can be changed so that it matches only at the very end of
689 the string, by setting the PCRE_DOLLAR_ENDONLY option at compile time. This
690 does not affect the \Z assertion.
691 </P>
692 <P>
693 The meanings of the circumflex and dollar characters are changed if the
694 PCRE_MULTILINE option is set. When this is the case, a circumflex matches
695 immediately after internal newlines as well as at the start of the subject
696 string. It does not match after a newline that ends the string. A dollar
697 matches before any newlines in the string, as well as at the very end, when
698 PCRE_MULTILINE is set. When newline is specified as the two-character
699 sequence CRLF, isolated CR and LF characters do not indicate newlines.
700 </P>
701 <P>
702 For example, the pattern /^abc$/ matches the subject string "def\nabc" (where
703 \n represents a newline) in multiline mode, but not otherwise. Consequently,
704 patterns that are anchored in single line mode because all branches start with
705 ^ are not anchored in multiline mode, and a match for circumflex is possible
706 when the <i>startoffset</i> argument of <b>pcre_exec()</b> is non-zero. The
707 PCRE_DOLLAR_ENDONLY option is ignored if PCRE_MULTILINE is set.
708 </P>
709 <P>
710 Note that the sequences \A, \Z, and \z can be used to match the start and
711 end of the subject in both modes, and if all branches of a pattern start with
712 \A it is always anchored, whether or not PCRE_MULTILINE is set.
713 </P>
714 <br><a name="SEC5" href="#TOC1">FULL STOP (PERIOD, DOT)</a><br>
715 <P>
716 Outside a character class, a dot in the pattern matches any one character in
717 the subject string except (by default) a character that signifies the end of a
718 line. In UTF-8 mode, the matched character may be more than one byte long.
719 </P>
720 <P>
721 When a line ending is defined as a single character, dot never matches that
722 character; when the two-character sequence CRLF is used, dot does not match CR
723 if it is immediately followed by LF, but otherwise it matches all characters
724 (including isolated CRs and LFs). When any Unicode line endings are being
725 recognized, dot does not match CR or LF or any of the other line ending
726 characters.
727 </P>
728 <P>
729 The behaviour of dot with regard to newlines can be changed. If the PCRE_DOTALL
730 option is set, a dot matches any one character, without exception. If the
731 two-character sequence CRLF is present in the subject string, it takes two dots
732 to match it.
733 </P>
734 <P>
735 The handling of dot is entirely independent of the handling of circumflex and
736 dollar, the only relationship being that they both involve newlines. Dot has no
737 special meaning in a character class.
738 </P>
739 <br><a name="SEC6" href="#TOC1">MATCHING A SINGLE BYTE</a><br>
740 <P>
741 Outside a character class, the escape sequence \C matches any one byte, both
742 in and out of UTF-8 mode. Unlike a dot, it always matches any line-ending
743 characters. The feature is provided in Perl in order to match individual bytes
744 in UTF-8 mode. Because it breaks up UTF-8 characters into individual bytes,
745 what remains in the string may be a malformed UTF-8 string. For this reason,
746 the \C escape sequence is best avoided.
747 </P>
748 <P>
749 PCRE does not allow \C to appear in lookbehind assertions
750 <a href="#lookbehind">(described below),</a>
751 because in UTF-8 mode this would make it impossible to calculate the length of
752 the lookbehind.
753 <a name="characterclass"></a></P>
754 <br><a name="SEC7" href="#TOC1">SQUARE BRACKETS AND CHARACTER CLASSES</a><br>
755 <P>
756 An opening square bracket introduces a character class, terminated by a closing
757 square bracket. A closing square bracket on its own is not special. If a
758 closing square bracket is required as a member of the class, it should be the
759 first data character in the class (after an initial circumflex, if present) or
760 escaped with a backslash.
761 </P>
762 <P>
763 A character class matches a single character in the subject. In UTF-8 mode, the
764 character may occupy more than one byte. A matched character must be in the set
765 of characters defined by the class, unless the first character in the class
766 definition is a circumflex, in which case the subject character must not be in
767 the set defined by the class. If a circumflex is actually required as a member
768 of the class, ensure it is not the first character, or escape it with a
769 backslash.
770 </P>
771 <P>
772 For example, the character class [aeiou] matches any lower case vowel, while
773 [^aeiou] matches any character that is not a lower case vowel. Note that a
774 circumflex is just a convenient notation for specifying the characters that
775 are in the class by enumerating those that are not. A class that starts with a
776 circumflex is not an assertion: it still consumes a character from the subject
777 string, and therefore it fails if the current pointer is at the end of the
778 string.
779 </P>
780 <P>
781 In UTF-8 mode, characters with values greater than 255 can be included in a
782 class as a literal string of bytes, or by using the \x{ escaping mechanism.
783 </P>
784 <P>
785 When caseless matching is set, any letters in a class represent both their
786 upper case and lower case versions, so for example, a caseless [aeiou] matches
787 "A" as well as "a", and a caseless [^aeiou] does not match "A", whereas a
788 caseful version would. In UTF-8 mode, PCRE always understands the concept of
789 case for characters whose values are less than 128, so caseless matching is
790 always possible. For characters with higher values, the concept of case is
791 supported if PCRE is compiled with Unicode property support, but not otherwise.
792 If you want to use caseless matching for characters 128 and above, you must
793 ensure that PCRE is compiled with Unicode property support as well as with
794 UTF-8 support.
795 </P>
796 <P>
797 Characters that might indicate line breaks are never treated in any special way
798 when matching character classes, whatever line-ending sequence is in use, and
799 whatever setting of the PCRE_DOTALL and PCRE_MULTILINE options is used. A class
800 such as [^a] always matches one of these characters.
801 </P>
802 <P>
803 The minus (hyphen) character can be used to specify a range of characters in a
804 character class. For example, [d-m] matches any letter between d and m,
805 inclusive. If a minus character is required in a class, it must be escaped with
806 a backslash or appear in a position where it cannot be interpreted as
807 indicating a range, typically as the first or last character in the class.
808 </P>
809 <P>
810 It is not possible to have the literal character "]" as the end character of a
811 range. A pattern such as [W-]46] is interpreted as a class of two characters
812 ("W" and "-") followed by a literal string "46]", so it would match "W46]" or
813 "-46]". However, if the "]" is escaped with a backslash it is interpreted as
814 the end of range, so [W-\]46] is interpreted as a class containing a range
815 followed by two other characters. The octal or hexadecimal representation of
816 "]" can also be used to end a range.
817 </P>
818 <P>
819 Ranges operate in the collating sequence of character values. They can also be
820 used for characters specified numerically, for example [\000-\037]. In UTF-8
821 mode, ranges can include characters whose values are greater than 255, for
822 example [\x{100}-\x{2ff}].
823 </P>
824 <P>
825 If a range that includes letters is used when caseless matching is set, it
826 matches the letters in either case. For example, [W-c] is equivalent to
827 [][\\^_`wxyzabc], matched caselessly, and in non-UTF-8 mode, if character
828 tables for a French locale are in use, [\xc8-\xcb] matches accented E
829 characters in both cases. In UTF-8 mode, PCRE supports the concept of case for
830 characters with values greater than 128 only when it is compiled with Unicode
831 property support.
832 </P>
833 <P>
834 The character types \d, \D, \p, \P, \s, \S, \w, and \W may also appear
835 in a character class, and add the characters that they match to the class. For
836 example, [\dABCDEF] matches any hexadecimal digit. A circumflex can
837 conveniently be used with the upper case character types to specify a more
838 restricted set of characters than the matching lower case type. For example,
839 the class [^\W_] matches any letter or digit, but not underscore.
840 </P>
841 <P>
842 The only metacharacters that are recognized in character classes are backslash,
843 hyphen (only where it can be interpreted as specifying a range), circumflex
844 (only at the start), opening square bracket (only when it can be interpreted as
845 introducing a POSIX class name - see the next section), and the terminating
846 closing square bracket. However, escaping other non-alphanumeric characters
847 does no harm.
848 </P>
849 <br><a name="SEC8" href="#TOC1">POSIX CHARACTER CLASSES</a><br>
850 <P>
851 Perl supports the POSIX notation for character classes. This uses names
852 enclosed by [: and :] within the enclosing square brackets. PCRE also supports
853 this notation. For example,
854 <pre>
855 [01[:alpha:]%]
856 </pre>
857 matches "0", "1", any alphabetic character, or "%". The supported class names
858 are
859 <pre>
860 alnum letters and digits
861 alpha letters
862 ascii character codes 0 - 127
863 blank space or tab only
864 cntrl control characters
865 digit decimal digits (same as \d)
866 graph printing characters, excluding space
867 lower lower case letters
868 print printing characters, including space
869 punct printing characters, excluding letters and digits
870 space white space (not quite the same as \s)
871 upper upper case letters
872 word "word" characters (same as \w)
873 xdigit hexadecimal digits
874 </pre>
875 The "space" characters are HT (9), LF (10), VT (11), FF (12), CR (13), and
876 space (32). Notice that this list includes the VT character (code 11). This
877 makes "space" different to \s, which does not include VT (for Perl
878 compatibility).
879 </P>
880 <P>
881 The name "word" is a Perl extension, and "blank" is a GNU extension from Perl
882 5.8. Another Perl extension is negation, which is indicated by a ^ character
883 after the colon. For example,
884 <pre>
885 [12[:^digit:]]
886 </pre>
887 matches "1", "2", or any non-digit. PCRE (and Perl) also recognize the POSIX
888 syntax [.ch.] and [=ch=] where "ch" is a "collating element", but these are not
889 supported, and an error is given if they are encountered.
890 </P>
891 <P>
892 In UTF-8 mode, characters with values greater than 128 do not match any of
893 the POSIX character classes.
894 </P>
895 <br><a name="SEC9" href="#TOC1">VERTICAL BAR</a><br>
896 <P>
897 Vertical bar characters are used to separate alternative patterns. For example,
898 the pattern
899 <pre>
900 gilbert|sullivan
901 </pre>
902 matches either "gilbert" or "sullivan". Any number of alternatives may appear,
903 and an empty alternative is permitted (matching the empty string). The matching
904 process tries each alternative in turn, from left to right, and the first one
905 that succeeds is used. If the alternatives are within a subpattern
906 <a href="#subpattern">(defined below),</a>
907 "succeeds" means matching the rest of the main pattern as well as the
908 alternative in the subpattern.
909 </P>
910 <br><a name="SEC10" href="#TOC1">INTERNAL OPTION SETTING</a><br>
911 <P>
912 The settings of the PCRE_CASELESS, PCRE_MULTILINE, PCRE_DOTALL, and
913 PCRE_EXTENDED options can be changed from within the pattern by a sequence of
914 Perl option letters enclosed between "(?" and ")". The option letters are
915 <pre>
916 i for PCRE_CASELESS
917 m for PCRE_MULTILINE
918 s for PCRE_DOTALL
919 x for PCRE_EXTENDED
920 </pre>
921 For example, (?im) sets caseless, multiline matching. It is also possible to
922 unset these options by preceding the letter with a hyphen, and a combined
923 setting and unsetting such as (?im-sx), which sets PCRE_CASELESS and
924 PCRE_MULTILINE while unsetting PCRE_DOTALL and PCRE_EXTENDED, is also
925 permitted. If a letter appears both before and after the hyphen, the option is
926 unset.
927 </P>
928 <P>
929 When an option change occurs at top level (that is, not inside subpattern
930 parentheses), the change applies to the remainder of the pattern that follows.
931 If the change is placed right at the start of a pattern, PCRE extracts it into
932 the global options (and it will therefore show up in data extracted by the
933 <b>pcre_fullinfo()</b> function).
934 </P>
935 <P>
936 An option change within a subpattern (see below for a description of
937 subpatterns) affects only that part of the current pattern that follows it, so
938 <pre>
939 (a(?i)b)c
940 </pre>
941 matches abc and aBc and no other strings (assuming PCRE_CASELESS is not used).
942 By this means, options can be made to have different settings in different
943 parts of the pattern. Any changes made in one alternative do carry on
944 into subsequent branches within the same subpattern. For example,
945 <pre>
946 (a(?i)b|c)
947 </pre>
948 matches "ab", "aB", "c", and "C", even though when matching "C" the first
949 branch is abandoned before the option setting. This is because the effects of
950 option settings happen at compile time. There would be some very weird
951 behaviour otherwise.
952 </P>
953 <P>
954 The PCRE-specific options PCRE_DUPNAMES, PCRE_UNGREEDY, and PCRE_EXTRA can be
955 changed in the same way as the Perl-compatible options by using the characters
956 J, U and X respectively.
957 <a name="subpattern"></a></P>
958 <br><a name="SEC11" href="#TOC1">SUBPATTERNS</a><br>
959 <P>
960 Subpatterns are delimited by parentheses (round brackets), which can be nested.
961 Turning part of a pattern into a subpattern does two things:
962 <br>
963 <br>
964 1. It localizes a set of alternatives. For example, the pattern
965 <pre>
966 cat(aract|erpillar|)
967 </pre>
968 matches one of the words "cat", "cataract", or "caterpillar". Without the
969 parentheses, it would match "cataract", "erpillar" or an empty string.
970 <br>
971 <br>
972 2. It sets up the subpattern as a capturing subpattern. This means that, when
973 the whole pattern matches, that portion of the subject string that matched the
974 subpattern is passed back to the caller via the <i>ovector</i> argument of
975 <b>pcre_exec()</b>. Opening parentheses are counted from left to right (starting
976 from 1) to obtain numbers for the capturing subpatterns.
977 </P>
978 <P>
979 For example, if the string "the red king" is matched against the pattern
980 <pre>
981 the ((red|white) (king|queen))
982 </pre>
983 the captured substrings are "red king", "red", and "king", and are numbered 1,
984 2, and 3, respectively.
985 </P>
986 <P>
987 The fact that plain parentheses fulfil two functions is not always helpful.
988 There are often times when a grouping subpattern is required without a
989 capturing requirement. If an opening parenthesis is followed by a question mark
990 and a colon, the subpattern does not do any capturing, and is not counted when
991 computing the number of any subsequent capturing subpatterns. For example, if
992 the string "the white queen" is matched against the pattern
993 <pre>
994 the ((?:red|white) (king|queen))
995 </pre>
996 the captured substrings are "white queen" and "queen", and are numbered 1 and
997 2. The maximum number of capturing subpatterns is 65535.
998 </P>
999 <P>
1000 As a convenient shorthand, if any option settings are required at the start of
1001 a non-capturing subpattern, the option letters may appear between the "?" and
1002 the ":". Thus the two patterns
1003 <pre>
1004 (?i:saturday|sunday)
1005 (?:(?i)saturday|sunday)
1006 </pre>
1007 match exactly the same set of strings. Because alternative branches are tried
1008 from left to right, and options are not reset until the end of the subpattern
1009 is reached, an option setting in one branch does affect subsequent branches, so
1010 the above patterns match "SUNDAY" as well as "Saturday".
1011 </P>
1012 <br><a name="SEC12" href="#TOC1">DUPLICATE SUBPATTERN NUMBERS</a><br>
1013 <P>
1014 Perl 5.10 introduced a feature whereby each alternative in a subpattern uses
1015 the same numbers for its capturing parentheses. Such a subpattern starts with
1016 (?| and is itself a non-capturing subpattern. For example, consider this
1017 pattern:
1018 <pre>
1019 (?|(Sat)ur|(Sun))day
1020 </pre>
1021 Because the two alternatives are inside a (?| group, both sets of capturing
1022 parentheses are numbered one. Thus, when the pattern matches, you can look
1023 at captured substring number one, whichever alternative matched. This construct
1024 is useful when you want to capture part, but not all, of one of a number of
1025 alternatives. Inside a (?| group, parentheses are numbered as usual, but the
1026 number is reset at the start of each branch. The numbers of any capturing
1027 buffers that follow the subpattern start after the highest number used in any
1028 branch. The following example is taken from the Perl documentation.
1029 The numbers underneath show in which buffer the captured content will be
1030 stored.
1031 <pre>
1032 # before ---------------branch-reset----------- after
1033 / ( a ) (?| x ( y ) z | (p (q) r) | (t) u (v) ) ( z ) /x
1034 # 1 2 2 3 2 3 4
1035 </pre>
1036 A backreference or a recursive call to a numbered subpattern always refers to
1037 the first one in the pattern with the given number.
1038 </P>
1039 <P>
1040 An alternative approach to using this "branch reset" feature is to use
1041 duplicate named subpatterns, as described in the next section.
1042 </P>
1043 <br><a name="SEC13" href="#TOC1">NAMED SUBPATTERNS</a><br>
1044 <P>
1045 Identifying capturing parentheses by number is simple, but it can be very hard
1046 to keep track of the numbers in complicated regular expressions. Furthermore,
1047 if an expression is modified, the numbers may change. To help with this
1048 difficulty, PCRE supports the naming of subpatterns. This feature was not
1049 added to Perl until release 5.10. Python had the feature earlier, and PCRE
1050 introduced it at release 4.0, using the Python syntax. PCRE now supports both
1051 the Perl and the Python syntax.
1052 </P>
1053 <P>
1054 In PCRE, a subpattern can be named in one of three ways: (?&#60;name&#62;...) or
1055 (?'name'...) as in Perl, or (?P&#60;name&#62;...) as in Python. References to capturing
1056 parentheses from other parts of the pattern, such as
1057 <a href="#backreferences">backreferences,</a>
1058 <a href="#recursion">recursion,</a>
1059 and
1060 <a href="#conditions">conditions,</a>
1061 can be made by name as well as by number.
1062 </P>
1063 <P>
1064 Names consist of up to 32 alphanumeric characters and underscores. Named
1065 capturing parentheses are still allocated numbers as well as names, exactly as
1066 if the names were not present. The PCRE API provides function calls for
1067 extracting the name-to-number translation table from a compiled pattern. There
1068 is also a convenience function for extracting a captured substring by name.
1069 </P>
1070 <P>
1071 By default, a name must be unique within a pattern, but it is possible to relax
1072 this constraint by setting the PCRE_DUPNAMES option at compile time. This can
1073 be useful for patterns where only one instance of the named parentheses can
1074 match. Suppose you want to match the name of a weekday, either as a 3-letter
1075 abbreviation or as the full name, and in both cases you want to extract the
1076 abbreviation. This pattern (ignoring the line breaks) does the job:
1077 <pre>
1078 (?&#60;DN&#62;Mon|Fri|Sun)(?:day)?|
1079 (?&#60;DN&#62;Tue)(?:sday)?|
1080 (?&#60;DN&#62;Wed)(?:nesday)?|
1081 (?&#60;DN&#62;Thu)(?:rsday)?|
1082 (?&#60;DN&#62;Sat)(?:urday)?
1083 </pre>
1084 There are five capturing substrings, but only one is ever set after a match.
1085 (An alternative way of solving this problem is to use a "branch reset"
1086 subpattern, as described in the previous section.)
1087 </P>
1088 <P>
1089 The convenience function for extracting the data by name returns the substring
1090 for the first (and in this example, the only) subpattern of that name that
1091 matched. This saves searching to find which numbered subpattern it was. If you
1092 make a reference to a non-unique named subpattern from elsewhere in the
1093 pattern, the one that corresponds to the lowest number is used. For further
1094 details of the interfaces for handling named subpatterns, see the
1095 <a href="pcreapi.html"><b>pcreapi</b></a>
1096 documentation.
1097 </P>
1098 <br><a name="SEC14" href="#TOC1">REPETITION</a><br>
1099 <P>
1100 Repetition is specified by quantifiers, which can follow any of the following
1101 items:
1102 <pre>
1103 a literal data character
1104 the dot metacharacter
1105 the \C escape sequence
1106 the \X escape sequence (in UTF-8 mode with Unicode properties)
1107 the \R escape sequence
1108 an escape such as \d that matches a single character
1109 a character class
1110 a back reference (see next section)
1111 a parenthesized subpattern (unless it is an assertion)
1112 </pre>
1113 The general repetition quantifier specifies a minimum and maximum number of
1114 permitted matches, by giving the two numbers in curly brackets (braces),
1115 separated by a comma. The numbers must be less than 65536, and the first must
1116 be less than or equal to the second. For example:
1117 <pre>
1118 z{2,4}
1119 </pre>
1120 matches "zz", "zzz", or "zzzz". A closing brace on its own is not a special
1121 character. If the second number is omitted, but the comma is present, there is
1122 no upper limit; if the second number and the comma are both omitted, the
1123 quantifier specifies an exact number of required matches. Thus
1124 <pre>
1125 [aeiou]{3,}
1126 </pre>
1127 matches at least 3 successive vowels, but may match many more, while
1128 <pre>
1129 \d{8}
1130 </pre>
1131 matches exactly 8 digits. An opening curly bracket that appears in a position
1132 where a quantifier is not allowed, or one that does not match the syntax of a
1133 quantifier, is taken as a literal character. For example, {,6} is not a
1134 quantifier, but a literal string of four characters.
1135 </P>
1136 <P>
1137 In UTF-8 mode, quantifiers apply to UTF-8 characters rather than to individual
1138 bytes. Thus, for example, \x{100}{2} matches two UTF-8 characters, each of
1139 which is represented by a two-byte sequence. Similarly, when Unicode property
1140 support is available, \X{3} matches three Unicode extended sequences, each of
1141 which may be several bytes long (and they may be of different lengths).
1142 </P>
1143 <P>
1144 The quantifier {0} is permitted, causing the expression to behave as if the
1145 previous item and the quantifier were not present.
1146 </P>
1147 <P>
1148 For convenience, the three most common quantifiers have single-character
1149 abbreviations:
1150 <pre>
1151 * is equivalent to {0,}
1152 + is equivalent to {1,}
1153 ? is equivalent to {0,1}
1154 </pre>
1155 It is possible to construct infinite loops by following a subpattern that can
1156 match no characters with a quantifier that has no upper limit, for example:
1157 <pre>
1158 (a?)*
1159 </pre>
1160 Earlier versions of Perl and PCRE used to give an error at compile time for
1161 such patterns. However, because there are cases where this can be useful, such
1162 patterns are now accepted, but if any repetition of the subpattern does in fact
1163 match no characters, the loop is forcibly broken.
1164 </P>
1165 <P>
1166 By default, the quantifiers are "greedy", that is, they match as much as
1167 possible (up to the maximum number of permitted times), without causing the
1168 rest of the pattern to fail. The classic example of where this gives problems
1169 is in trying to match comments in C programs. These appear between /* and */
1170 and within the comment, individual * and / characters may appear. An attempt to
1171 match C comments by applying the pattern
1172 <pre>
1173 /\*.*\*/
1174 </pre>
1175 to the string
1176 <pre>
1177 /* first comment */ not comment /* second comment */
1178 </pre>
1179 fails, because it matches the entire string owing to the greediness of the .*
1180 item.
1181 </P>
1182 <P>
1183 However, if a quantifier is followed by a question mark, it ceases to be
1184 greedy, and instead matches the minimum number of times possible, so the
1185 pattern
1186 <pre>
1187 /\*.*?\*/
1188 </pre>
1189 does the right thing with the C comments. The meaning of the various
1190 quantifiers is not otherwise changed, just the preferred number of matches.
1191 Do not confuse this use of question mark with its use as a quantifier in its
1192 own right. Because it has two uses, it can sometimes appear doubled, as in
1193 <pre>
1194 \d??\d
1195 </pre>
1196 which matches one digit by preference, but can match two if that is the only
1197 way the rest of the pattern matches.
1198 </P>
1199 <P>
1200 If the PCRE_UNGREEDY option is set (an option that is not available in Perl),
1201 the quantifiers are not greedy by default, but individual ones can be made
1202 greedy by following them with a question mark. In other words, it inverts the
1203 default behaviour.
1204 </P>
1205 <P>
1206 When a parenthesized subpattern is quantified with a minimum repeat count that
1207 is greater than 1 or with a limited maximum, more memory is required for the
1208 compiled pattern, in proportion to the size of the minimum or maximum.
1209 </P>
1210 <P>
1211 If a pattern starts with .* or .{0,} and the PCRE_DOTALL option (equivalent
1212 to Perl's /s) is set, thus allowing the dot to match newlines, the pattern is
1213 implicitly anchored, because whatever follows will be tried against every
1214 character position in the subject string, so there is no point in retrying the
1215 overall match at any position after the first. PCRE normally treats such a
1216 pattern as though it were preceded by \A.
1217 </P>
1218 <P>
1219 In cases where it is known that the subject string contains no newlines, it is
1220 worth setting PCRE_DOTALL in order to obtain this optimization, or
1221 alternatively using ^ to indicate anchoring explicitly.
1222 </P>
1223 <P>
1224 However, there is one situation where the optimization cannot be used. When .*
1225 is inside capturing parentheses that are the subject of a backreference
1226 elsewhere in the pattern, a match at the start may fail where a later one
1227 succeeds. Consider, for example:
1228 <pre>
1229 (.*)abc\1
1230 </pre>
1231 If the subject is "xyz123abc123" the match point is the fourth character. For
1232 this reason, such a pattern is not implicitly anchored.
1233 </P>
1234 <P>
1235 When a capturing subpattern is repeated, the value captured is the substring
1236 that matched the final iteration. For example, after
1237 <pre>
1238 (tweedle[dume]{3}\s*)+
1239 </pre>
1240 has matched "tweedledum tweedledee" the value of the captured substring is
1241 "tweedledee". However, if there are nested capturing subpatterns, the
1242 corresponding captured values may have been set in previous iterations. For
1243 example, after
1244 <pre>
1245 /(a|(b))+/
1246 </pre>
1247 matches "aba" the value of the second captured substring is "b".
1248 <a name="atomicgroup"></a></P>
1249 <br><a name="SEC15" href="#TOC1">ATOMIC GROUPING AND POSSESSIVE QUANTIFIERS</a><br>
1250 <P>
1251 With both maximizing ("greedy") and minimizing ("ungreedy" or "lazy")
1252 repetition, failure of what follows normally causes the repeated item to be
1253 re-evaluated to see if a different number of repeats allows the rest of the
1254 pattern to match. Sometimes it is useful to prevent this, either to change the
1255 nature of the match, or to cause it fail earlier than it otherwise might, when
1256 the author of the pattern knows there is no point in carrying on.
1257 </P>
1258 <P>
1259 Consider, for example, the pattern \d+foo when applied to the subject line
1260 <pre>
1261 123456bar
1262 </pre>
1263 After matching all 6 digits and then failing to match "foo", the normal
1264 action of the matcher is to try again with only 5 digits matching the \d+
1265 item, and then with 4, and so on, before ultimately failing. "Atomic grouping"
1266 (a term taken from Jeffrey Friedl's book) provides the means for specifying
1267 that once a subpattern has matched, it is not to be re-evaluated in this way.
1268 </P>
1269 <P>
1270 If we use atomic grouping for the previous example, the matcher gives up
1271 immediately on failing to match "foo" the first time. The notation is a kind of
1272 special parenthesis, starting with (?&#62; as in this example:
1273 <pre>
1274 (?&#62;\d+)foo
1275 </pre>
1276 This kind of parenthesis "locks up" the part of the pattern it contains once
1277 it has matched, and a failure further into the pattern is prevented from
1278 backtracking into it. Backtracking past it to previous items, however, works as
1279 normal.
1280 </P>
1281 <P>
1282 An alternative description is that a subpattern of this type matches the string
1283 of characters that an identical standalone pattern would match, if anchored at
1284 the current point in the subject string.
1285 </P>
1286 <P>
1287 Atomic grouping subpatterns are not capturing subpatterns. Simple cases such as
1288 the above example can be thought of as a maximizing repeat that must swallow
1289 everything it can. So, while both \d+ and \d+? are prepared to adjust the
1290 number of digits they match in order to make the rest of the pattern match,
1291 (?&#62;\d+) can only match an entire sequence of digits.
1292 </P>
1293 <P>
1294 Atomic groups in general can of course contain arbitrarily complicated
1295 subpatterns, and can be nested. However, when the subpattern for an atomic
1296 group is just a single repeated item, as in the example above, a simpler
1297 notation, called a "possessive quantifier" can be used. This consists of an
1298 additional + character following a quantifier. Using this notation, the
1299 previous example can be rewritten as
1300 <pre>
1301 \d++foo
1302 </pre>
1303 Possessive quantifiers are always greedy; the setting of the PCRE_UNGREEDY
1304 option is ignored. They are a convenient notation for the simpler forms of
1305 atomic group. However, there is no difference in the meaning of a possessive
1306 quantifier and the equivalent atomic group, though there may be a performance
1307 difference; possessive quantifiers should be slightly faster.
1308 </P>
1309 <P>
1310 The possessive quantifier syntax is an extension to the Perl 5.8 syntax.
1311 Jeffrey Friedl originated the idea (and the name) in the first edition of his
1312 book. Mike McCloskey liked it, so implemented it when he built Sun's Java
1313 package, and PCRE copied it from there. It ultimately found its way into Perl
1314 at release 5.10.
1315 </P>
1316 <P>
1317 PCRE has an optimization that automatically "possessifies" certain simple
1318 pattern constructs. For example, the sequence A+B is treated as A++B because
1319 there is no point in backtracking into a sequence of A's when B must follow.
1320 </P>
1321 <P>
1322 When a pattern contains an unlimited repeat inside a subpattern that can itself
1323 be repeated an unlimited number of times, the use of an atomic group is the
1324 only way to avoid some failing matches taking a very long time indeed. The
1325 pattern
1326 <pre>
1327 (\D+|&#60;\d+&#62;)*[!?]
1328 </pre>
1329 matches an unlimited number of substrings that either consist of non-digits, or
1330 digits enclosed in &#60;&#62;, followed by either ! or ?. When it matches, it runs
1331 quickly. However, if it is applied to
1332 <pre>
1333 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
1334 </pre>
1335 it takes a long time before reporting failure. This is because the string can
1336 be divided between the internal \D+ repeat and the external * repeat in a
1337 large number of ways, and all have to be tried. (The example uses [!?] rather
1338 than a single character at the end, because both PCRE and Perl have an
1339 optimization that allows for fast failure when a single character is used. They
1340 remember the last single character that is required for a match, and fail early
1341 if it is not present in the string.) If the pattern is changed so that it uses
1342 an atomic group, like this:
1343 <pre>
1344 ((?&#62;\D+)|&#60;\d+&#62;)*[!?]
1345 </pre>
1346 sequences of non-digits cannot be broken, and failure happens quickly.
1347 <a name="backreferences"></a></P>
1348 <br><a name="SEC16" href="#TOC1">BACK REFERENCES</a><br>
1349 <P>
1350 Outside a character class, a backslash followed by a digit greater than 0 (and
1351 possibly further digits) is a back reference to a capturing subpattern earlier
1352 (that is, to its left) in the pattern, provided there have been that many
1353 previous capturing left parentheses.
1354 </P>
1355 <P>
1356 However, if the decimal number following the backslash is less than 10, it is
1357 always taken as a back reference, and causes an error only if there are not
1358 that many capturing left parentheses in the entire pattern. In other words, the
1359 parentheses that are referenced need not be to the left of the reference for
1360 numbers less than 10. A "forward back reference" of this type can make sense
1361 when a repetition is involved and the subpattern to the right has participated
1362 in an earlier iteration.
1363 </P>
1364 <P>
1365 It is not possible to have a numerical "forward back reference" to a subpattern
1366 whose number is 10 or more using this syntax because a sequence such as \50 is
1367 interpreted as a character defined in octal. See the subsection entitled
1368 "Non-printing characters"
1369 <a href="#digitsafterbackslash">above</a>
1370 for further details of the handling of digits following a backslash. There is
1371 no such problem when named parentheses are used. A back reference to any
1372 subpattern is possible using named parentheses (see below).
1373 </P>
1374 <P>
1375 Another way of avoiding the ambiguity inherent in the use of digits following a
1376 backslash is to use the \g escape sequence, which is a feature introduced in
1377 Perl 5.10. This escape must be followed by a positive or a negative number,
1378 optionally enclosed in braces. These examples are all identical:
1379 <pre>
1380 (ring), \1
1381 (ring), \g1
1382 (ring), \g{1}
1383 </pre>
1384 A positive number specifies an absolute reference without the ambiguity that is
1385 present in the older syntax. It is also useful when literal digits follow the
1386 reference. A negative number is a relative reference. Consider this example:
1387 <pre>
1388 (abc(def)ghi)\g{-1}
1389 </pre>
1390 The sequence \g{-1} is a reference to the most recently started capturing
1391 subpattern before \g, that is, is it equivalent to \2. Similarly, \g{-2}
1392 would be equivalent to \1. The use of relative references can be helpful in
1393 long patterns, and also in patterns that are created by joining together
1394 fragments that contain references within themselves.
1395 </P>
1396 <P>
1397 A back reference matches whatever actually matched the capturing subpattern in
1398 the current subject string, rather than anything matching the subpattern
1399 itself (see
1400 <a href="#subpatternsassubroutines">"Subpatterns as subroutines"</a>
1401 below for a way of doing that). So the pattern
1402 <pre>
1403 (sens|respons)e and \1ibility
1404 </pre>
1405 matches "sense and sensibility" and "response and responsibility", but not
1406 "sense and responsibility". If caseful matching is in force at the time of the
1407 back reference, the case of letters is relevant. For example,
1408 <pre>
1409 ((?i)rah)\s+\1
1410 </pre>
1411 matches "rah rah" and "RAH RAH", but not "RAH rah", even though the original
1412 capturing subpattern is matched caselessly.
1413 </P>
1414 <P>
1415 There are several different ways of writing back references to named
1416 subpatterns. The .NET syntax \k{name} and the Perl syntax \k&#60;name&#62; or
1417 \k'name' are supported, as is the Python syntax (?P=name). Perl 5.10's unified
1418 back reference syntax, in which \g can be used for both numeric and named
1419 references, is also supported. We could rewrite the above example in any of
1420 the following ways:
1421 <pre>
1422 (?&#60;p1&#62;(?i)rah)\s+\k&#60;p1&#62;
1423 (?'p1'(?i)rah)\s+\k{p1}
1424 (?P&#60;p1&#62;(?i)rah)\s+(?P=p1)
1425 (?&#60;p1&#62;(?i)rah)\s+\g{p1}
1426 </pre>
1427 A subpattern that is referenced by name may appear in the pattern before or
1428 after the reference.
1429 </P>
1430 <P>
1431 There may be more than one back reference to the same subpattern. If a
1432 subpattern has not actually been used in a particular match, any back
1433 references to it always fail. For example, the pattern
1434 <pre>
1435 (a|(bc))\2
1436 </pre>
1437 always fails if it starts to match "a" rather than "bc". Because there may be
1438 many capturing parentheses in a pattern, all digits following the backslash are
1439 taken as part of a potential back reference number. If the pattern continues
1440 with a digit character, some delimiter must be used to terminate the back
1441 reference. If the PCRE_EXTENDED option is set, this can be whitespace.
1442 Otherwise an empty comment (see
1443 <a href="#comments">"Comments"</a>
1444 below) can be used.
1445 </P>
1446 <P>
1447 A back reference that occurs inside the parentheses to which it refers fails
1448 when the subpattern is first used, so, for example, (a\1) never matches.
1449 However, such references can be useful inside repeated subpatterns. For
1450 example, the pattern
1451 <pre>
1452 (a|b\1)+
1453 </pre>
1454 matches any number of "a"s and also "aba", "ababbaa" etc. At each iteration of
1455 the subpattern, the back reference matches the character string corresponding
1456 to the previous iteration. In order for this to work, the pattern must be such
1457 that the first iteration does not need to match the back reference. This can be
1458 done using alternation, as in the example above, or by a quantifier with a
1459 minimum of zero.
1460 <a name="bigassertions"></a></P>
1461 <br><a name="SEC17" href="#TOC1">ASSERTIONS</a><br>
1462 <P>
1463 An assertion is a test on the characters following or preceding the current
1464 matching point that does not actually consume any characters. The simple
1465 assertions coded as \b, \B, \A, \G, \Z, \z, ^ and $ are described
1466 <a href="#smallassertions">above.</a>
1467 </P>
1468 <P>
1469 More complicated assertions are coded as subpatterns. There are two kinds:
1470 those that look ahead of the current position in the subject string, and those
1471 that look behind it. An assertion subpattern is matched in the normal way,
1472 except that it does not cause the current matching position to be changed.
1473 </P>
1474 <P>
1475 Assertion subpatterns are not capturing subpatterns, and may not be repeated,
1476 because it makes no sense to assert the same thing several times. If any kind
1477 of assertion contains capturing subpatterns within it, these are counted for
1478 the purposes of numbering the capturing subpatterns in the whole pattern.
1479 However, substring capturing is carried out only for positive assertions,
1480 because it does not make sense for negative assertions.
1481 </P>
1482 <br><b>
1483 Lookahead assertions
1484 </b><br>
1485 <P>
1486 Lookahead assertions start with (?= for positive assertions and (?! for
1487 negative assertions. For example,
1488 <pre>
1489 \w+(?=;)
1490 </pre>
1491 matches a word followed by a semicolon, but does not include the semicolon in
1492 the match, and
1493 <pre>
1494 foo(?!bar)
1495 </pre>
1496 matches any occurrence of "foo" that is not followed by "bar". Note that the
1497 apparently similar pattern
1498 <pre>
1499 (?!foo)bar
1500 </pre>
1501 does not find an occurrence of "bar" that is preceded by something other than
1502 "foo"; it finds any occurrence of "bar" whatsoever, because the assertion
1503 (?!foo) is always true when the next three characters are "bar". A
1504 lookbehind assertion is needed to achieve the other effect.
1505 </P>
1506 <P>
1507 If you want to force a matching failure at some point in a pattern, the most
1508 convenient way to do it is with (?!) because an empty string always matches, so
1509 an assertion that requires there not to be an empty string must always fail.
1510 <a name="lookbehind"></a></P>
1511 <br><b>
1512 Lookbehind assertions
1513 </b><br>
1514 <P>
1515 Lookbehind assertions start with (?&#60;= for positive assertions and (?&#60;! for
1516 negative assertions. For example,
1517 <pre>
1518 (?&#60;!foo)bar
1519 </pre>
1520 does find an occurrence of "bar" that is not preceded by "foo". The contents of
1521 a lookbehind assertion are restricted such that all the strings it matches must
1522 have a fixed length. However, if there are several top-level alternatives, they
1523 do not all have to have the same fixed length. Thus
1524 <pre>
1525 (?&#60;=bullock|donkey)
1526 </pre>
1527 is permitted, but
1528 <pre>
1529 (?&#60;!dogs?|cats?)
1530 </pre>
1531 causes an error at compile time. Branches that match different length strings
1532 are permitted only at the top level of a lookbehind assertion. This is an
1533 extension compared with Perl (at least for 5.8), which requires all branches to
1534 match the same length of string. An assertion such as
1535 <pre>
1536 (?&#60;=ab(c|de))
1537 </pre>
1538 is not permitted, because its single top-level branch can match two different
1539 lengths, but it is acceptable if rewritten to use two top-level branches:
1540 <pre>
1541 (?&#60;=abc|abde)
1542 </pre>
1543 In some cases, the Perl 5.10 escape sequence \K
1544 <a href="#resetmatchstart">(see above)</a>
1545 can be used instead of a lookbehind assertion; this is not restricted to a
1546 fixed-length.
1547 </P>
1548 <P>
1549 The implementation of lookbehind assertions is, for each alternative, to
1550 temporarily move the current position back by the fixed length and then try to
1551 match. If there are insufficient characters before the current position, the
1552 assertion fails.
1553 </P>
1554 <P>
1555 PCRE does not allow the \C escape (which matches a single byte in UTF-8 mode)
1556 to appear in lookbehind assertions, because it makes it impossible to calculate
1557 the length of the lookbehind. The \X and \R escapes, which can match
1558 different numbers of bytes, are also not permitted.
1559 </P>
1560 <P>
1561 Possessive quantifiers can be used in conjunction with lookbehind assertions to
1562 specify efficient matching at the end of the subject string. Consider a simple
1563 pattern such as
1564 <pre>
1565 abcd$
1566 </pre>
1567 when applied to a long string that does not match. Because matching proceeds
1568 from left to right, PCRE will look for each "a" in the subject and then see if
1569 what follows matches the rest of the pattern. If the pattern is specified as
1570 <pre>
1571 ^.*abcd$
1572 </pre>
1573 the initial .* matches the entire string at first, but when this fails (because
1574 there is no following "a"), it backtracks to match all but the last character,
1575 then all but the last two characters, and so on. Once again the search for "a"
1576 covers the entire string, from right to left, so we are no better off. However,
1577 if the pattern is written as
1578 <pre>
1579 ^.*+(?&#60;=abcd)
1580 </pre>
1581 there can be no backtracking for the .*+ item; it can match only the entire
1582 string. The subsequent lookbehind assertion does a single test on the last four
1583 characters. If it fails, the match fails immediately. For long strings, this
1584 approach makes a significant difference to the processing time.
1585 </P>
1586 <br><b>
1587 Using multiple assertions
1588 </b><br>
1589 <P>
1590 Several assertions (of any sort) may occur in succession. For example,
1591 <pre>
1592 (?&#60;=\d{3})(?&#60;!999)foo
1593 </pre>
1594 matches "foo" preceded by three digits that are not "999". Notice that each of
1595 the assertions is applied independently at the same point in the subject
1596 string. First there is a check that the previous three characters are all
1597 digits, and then there is a check that the same three characters are not "999".
1598 This pattern does <i>not</i> match "foo" preceded by six characters, the first
1599 of which are digits and the last three of which are not "999". For example, it
1600 doesn't match "123abcfoo". A pattern to do that is
1601 <pre>
1602 (?&#60;=\d{3}...)(?&#60;!999)foo
1603 </pre>
1604 This time the first assertion looks at the preceding six characters, checking
1605 that the first three are digits, and then the second assertion checks that the
1606 preceding three characters are not "999".
1607 </P>
1608 <P>
1609 Assertions can be nested in any combination. For example,
1610 <pre>
1611 (?&#60;=(?&#60;!foo)bar)baz
1612 </pre>
1613 matches an occurrence of "baz" that is preceded by "bar" which in turn is not
1614 preceded by "foo", while
1615 <pre>
1616 (?&#60;=\d{3}(?!999)...)foo
1617 </pre>
1618 is another pattern that matches "foo" preceded by three digits and any three
1619 characters that are not "999".
1620 <a name="conditions"></a></P>
1621 <br><a name="SEC18" href="#TOC1">CONDITIONAL SUBPATTERNS</a><br>
1622 <P>
1623 It is possible to cause the matching process to obey a subpattern
1624 conditionally or to choose between two alternative subpatterns, depending on
1625 the result of an assertion, or whether a previous capturing subpattern matched
1626 or not. The two possible forms of conditional subpattern are
1627 <pre>
1628 (?(condition)yes-pattern)
1629 (?(condition)yes-pattern|no-pattern)
1630 </pre>
1631 If the condition is satisfied, the yes-pattern is used; otherwise the
1632 no-pattern (if present) is used. If there are more than two alternatives in the
1633 subpattern, a compile-time error occurs.
1634 </P>
1635 <P>
1636 There are four kinds of condition: references to subpatterns, references to
1637 recursion, a pseudo-condition called DEFINE, and assertions.
1638 </P>
1639 <br><b>
1640 Checking for a used subpattern by number
1641 </b><br>
1642 <P>
1643 If the text between the parentheses consists of a sequence of digits, the
1644 condition is true if the capturing subpattern of that number has previously
1645 matched. An alternative notation is to precede the digits with a plus or minus
1646 sign. In this case, the subpattern number is relative rather than absolute.
1647 The most recently opened parentheses can be referenced by (?(-1), the next most
1648 recent by (?(-2), and so on. In looping constructs it can also make sense to
1649 refer to subsequent groups with constructs such as (?(+2).
1650 </P>
1651 <P>
1652 Consider the following pattern, which contains non-significant white space to
1653 make it more readable (assume the PCRE_EXTENDED option) and to divide it into
1654 three parts for ease of discussion:
1655 <pre>
1656 ( \( )? [^()]+ (?(1) \) )
1657 </pre>
1658 The first part matches an optional opening parenthesis, and if that
1659 character is present, sets it as the first captured substring. The second part
1660 matches one or more characters that are not parentheses. The third part is a
1661 conditional subpattern that tests whether the first set of parentheses matched
1662 or not. If they did, that is, if subject started with an opening parenthesis,
1663 the condition is true, and so the yes-pattern is executed and a closing
1664 parenthesis is required. Otherwise, since no-pattern is not present, the
1665 subpattern matches nothing. In other words, this pattern matches a sequence of
1666 non-parentheses, optionally enclosed in parentheses.
1667 </P>
1668 <P>
1669 If you were embedding this pattern in a larger one, you could use a relative
1670 reference:
1671 <pre>
1672 ...other stuff... ( \( )? [^()]+ (?(-1) \) ) ...
1673 </pre>
1674 This makes the fragment independent of the parentheses in the larger pattern.
1675 </P>
1676 <br><b>
1677 Checking for a used subpattern by name
1678 </b><br>
1679 <P>
1680 Perl uses the syntax (?(&#60;name&#62;)...) or (?('name')...) to test for a used
1681 subpattern by name. For compatibility with earlier versions of PCRE, which had
1682 this facility before Perl, the syntax (?(name)...) is also recognized. However,
1683 there is a possible ambiguity with this syntax, because subpattern names may
1684 consist entirely of digits. PCRE looks first for a named subpattern; if it
1685 cannot find one and the name consists entirely of digits, PCRE looks for a
1686 subpattern of that number, which must be greater than zero. Using subpattern
1687 names that consist entirely of digits is not recommended.
1688 </P>
1689 <P>
1690 Rewriting the above example to use a named subpattern gives this:
1691 <pre>
1692 (?&#60;OPEN&#62; \( )? [^()]+ (?(&#60;OPEN&#62;) \) )
1693
1694 </PRE>
1695 </P>
1696 <br><b>
1697 Checking for pattern recursion
1698 </b><br>
1699 <P>
1700 If the condition is the string (R), and there is no subpattern with the name R,
1701 the condition is true if a recursive call to the whole pattern or any
1702 subpattern has been made. If digits or a name preceded by ampersand follow the
1703 letter R, for example:
1704 <pre>
1705 (?(R3)...) or (?(R&name)...)
1706 </pre>
1707 the condition is true if the most recent recursion is into the subpattern whose
1708 number or name is given. This condition does not check the entire recursion
1709 stack.
1710 </P>
1711 <P>
1712 At "top level", all these recursion test conditions are false. Recursive
1713 patterns are described below.
1714 </P>
1715 <br><b>
1716 Defining subpatterns for use by reference only
1717 </b><br>
1718 <P>
1719 If the condition is the string (DEFINE), and there is no subpattern with the
1720 name DEFINE, the condition is always false. In this case, there may be only one
1721 alternative in the subpattern. It is always skipped if control reaches this
1722 point in the pattern; the idea of DEFINE is that it can be used to define
1723 "subroutines" that can be referenced from elsewhere. (The use of "subroutines"
1724 is described below.) For example, a pattern to match an IPv4 address could be
1725 written like this (ignore whitespace and line breaks):
1726 <pre>
1727 (?(DEFINE) (?&#60;byte&#62; 2[0-4]\d | 25[0-5] | 1\d\d | [1-9]?\d) )
1728 \b (?&byte) (\.(?&byte)){3} \b
1729 </pre>
1730 The first part of the pattern is a DEFINE group inside which a another group
1731 named "byte" is defined. This matches an individual component of an IPv4
1732 address (a number less than 256). When matching takes place, this part of the
1733 pattern is skipped because DEFINE acts like a false condition.
1734 </P>
1735 <P>
1736 The rest of the pattern uses references to the named group to match the four
1737 dot-separated components of an IPv4 address, insisting on a word boundary at
1738 each end.
1739 </P>
1740 <br><b>
1741 Assertion conditions
1742 </b><br>
1743 <P>
1744 If the condition is not in any of the above formats, it must be an assertion.
1745 This may be a positive or negative lookahead or lookbehind assertion. Consider
1746 this pattern, again containing non-significant white space, and with the two
1747 alternatives on the second line:
1748 <pre>
1749 (?(?=[^a-z]*[a-z])
1750 \d{2}-[a-z]{3}-\d{2} | \d{2}-\d{2}-\d{2} )
1751 </pre>
1752 The condition is a positive lookahead assertion that matches an optional
1753 sequence of non-letters followed by a letter. In other words, it tests for the
1754 presence of at least one letter in the subject. If a letter is found, the
1755 subject is matched against the first alternative; otherwise it is matched
1756 against the second. This pattern matches strings in one of the two forms
1757 dd-aaa-dd or dd-dd-dd, where aaa are letters and dd are digits.
1758 <a name="comments"></a></P>
1759 <br><a name="SEC19" href="#TOC1">COMMENTS</a><br>
1760 <P>
1761 The sequence (?# marks the start of a comment that continues up to the next
1762 closing parenthesis. Nested parentheses are not permitted. The characters
1763 that make up a comment play no part in the pattern matching at all.
1764 </P>
1765 <P>
1766 If the PCRE_EXTENDED option is set, an unescaped # character outside a
1767 character class introduces a comment that continues to immediately after the
1768 next newline in the pattern.
1769 <a name="recursion"></a></P>
1770 <br><a name="SEC20" href="#TOC1">RECURSIVE PATTERNS</a><br>
1771 <P>
1772 Consider the problem of matching a string in parentheses, allowing for
1773 unlimited nested parentheses. Without the use of recursion, the best that can
1774 be done is to use a pattern that matches up to some fixed depth of nesting. It
1775 is not possible to handle an arbitrary nesting depth.
1776 </P>
1777 <P>
1778 For some time, Perl has provided a facility that allows regular expressions to
1779 recurse (amongst other things). It does this by interpolating Perl code in the
1780 expression at run time, and the code can refer to the expression itself. A Perl
1781 pattern using code interpolation to solve the parentheses problem can be
1782 created like this:
1783 <pre>
1784 $re = qr{\( (?: (?&#62;[^()]+) | (?p{$re}) )* \)}x;
1785 </pre>
1786 The (?p{...}) item interpolates Perl code at run time, and in this case refers
1787 recursively to the pattern in which it appears.
1788 </P>
1789 <P>
1790 Obviously, PCRE cannot support the interpolation of Perl code. Instead, it
1791 supports special syntax for recursion of the entire pattern, and also for
1792 individual subpattern recursion. After its introduction in PCRE and Python,
1793 this kind of recursion was introduced into Perl at release 5.10.
1794 </P>
1795 <P>
1796 A special item that consists of (? followed by a number greater than zero and a
1797 closing parenthesis is a recursive call of the subpattern of the given number,
1798 provided that it occurs inside that subpattern. (If not, it is a "subroutine"
1799 call, which is described in the next section.) The special item (?R) or (?0) is
1800 a recursive call of the entire regular expression.
1801 </P>
1802 <P>
1803 In PCRE (like Python, but unlike Perl), a recursive subpattern call is always
1804 treated as an atomic group. That is, once it has matched some of the subject
1805 string, it is never re-entered, even if it contains untried alternatives and
1806 there is a subsequent matching failure.
1807 </P>
1808 <P>
1809 This PCRE pattern solves the nested parentheses problem (assume the
1810 PCRE_EXTENDED option is set so that white space is ignored):
1811 <pre>
1812 \( ( (?&#62;[^()]+) | (?R) )* \)
1813 </pre>
1814 First it matches an opening parenthesis. Then it matches any number of
1815 substrings which can either be a sequence of non-parentheses, or a recursive
1816 match of the pattern itself (that is, a correctly parenthesized substring).
1817 Finally there is a closing parenthesis.
1818 </P>
1819 <P>
1820 If this were part of a larger pattern, you would not want to recurse the entire
1821 pattern, so instead you could use this:
1822 <pre>
1823 ( \( ( (?&#62;[^()]+) | (?1) )* \) )
1824 </pre>
1825 We have put the pattern into parentheses, and caused the recursion to refer to
1826 them instead of the whole pattern.
1827 </P>
1828 <P>
1829 In a larger pattern, keeping track of parenthesis numbers can be tricky. This
1830 is made easier by the use of relative references. (A Perl 5.10 feature.)
1831 Instead of (?1) in the pattern above you can write (?-2) to refer to the second
1832 most recently opened parentheses preceding the recursion. In other words, a
1833 negative number counts capturing parentheses leftwards from the point at which
1834 it is encountered.
1835 </P>
1836 <P>
1837 It is also possible to refer to subsequently opened parentheses, by writing
1838 references such as (?+2). However, these cannot be recursive because the
1839 reference is not inside the parentheses that are referenced. They are always
1840 "subroutine" calls, as described in the next section.
1841 </P>
1842 <P>
1843 An alternative approach is to use named parentheses instead. The Perl syntax
1844 for this is (?&name); PCRE's earlier syntax (?P&#62;name) is also supported. We
1845 could rewrite the above example as follows:
1846 <pre>
1847 (?&#60;pn&#62; \( ( (?&#62;[^()]+) | (?&pn) )* \) )
1848 </pre>
1849 If there is more than one subpattern with the same name, the earliest one is
1850 used.
1851 </P>
1852 <P>
1853 This particular example pattern that we have been looking at contains nested
1854 unlimited repeats, and so the use of atomic grouping for matching strings of
1855 non-parentheses is important when applying the pattern to strings that do not
1856 match. For example, when this pattern is applied to
1857 <pre>
1858 (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()
1859 </pre>
1860 it yields "no match" quickly. However, if atomic grouping is not used,
1861 the match runs for a very long time indeed because there are so many different
1862 ways the + and * repeats can carve up the subject, and all have to be tested
1863 before failure can be reported.
1864 </P>
1865 <P>
1866 At the end of a match, the values set for any capturing subpatterns are those
1867 from the outermost level of the recursion at which the subpattern value is set.
1868 If you want to obtain intermediate values, a callout function can be used (see
1869 below and the
1870 <a href="pcrecallout.html"><b>pcrecallout</b></a>
1871 documentation). If the pattern above is matched against
1872 <pre>
1873 (ab(cd)ef)
1874 </pre>
1875 the value for the capturing parentheses is "ef", which is the last value taken
1876 on at the top level. If additional parentheses are added, giving
1877 <pre>
1878 \( ( ( (?&#62;[^()]+) | (?R) )* ) \)
1879 ^ ^
1880 ^ ^
1881 </pre>
1882 the string they capture is "ab(cd)ef", the contents of the top level
1883 parentheses. If there are more than 15 capturing parentheses in a pattern, PCRE
1884 has to obtain extra memory to store data during a recursion, which it does by
1885 using <b>pcre_malloc</b>, freeing it via <b>pcre_free</b> afterwards. If no
1886 memory can be obtained, the match fails with the PCRE_ERROR_NOMEMORY error.
1887 </P>
1888 <P>
1889 Do not confuse the (?R) item with the condition (R), which tests for recursion.
1890 Consider this pattern, which matches text in angle brackets, allowing for
1891 arbitrary nesting. Only digits are allowed in nested brackets (that is, when
1892 recursing), whereas any characters are permitted at the outer level.
1893 <pre>
1894 &#60; (?: (?(R) \d++ | [^&#60;&#62;]*+) | (?R)) * &#62;
1895 </pre>
1896 In this pattern, (?(R) is the start of a conditional subpattern, with two
1897 different alternatives for the recursive and non-recursive cases. The (?R) item
1898 is the actual recursive call.
1899 <a name="subpatternsassubroutines"></a></P>
1900 <br><a name="SEC21" href="#TOC1">SUBPATTERNS AS SUBROUTINES</a><br>
1901 <P>
1902 If the syntax for a recursive subpattern reference (either by number or by
1903 name) is used outside the parentheses to which it refers, it operates like a
1904 subroutine in a programming language. The "called" subpattern may be defined
1905 before or after the reference. A numbered reference can be absolute or
1906 relative, as in these examples:
1907 <pre>
1908 (...(absolute)...)...(?2)...
1909 (...(relative)...)...(?-1)...
1910 (...(?+1)...(relative)...
1911 </pre>
1912 An earlier example pointed out that the pattern
1913 <pre>
1914 (sens|respons)e and \1ibility
1915 </pre>
1916 matches "sense and sensibility" and "response and responsibility", but not
1917 "sense and responsibility". If instead the pattern
1918 <pre>
1919 (sens|respons)e and (?1)ibility
1920 </pre>
1921 is used, it does match "sense and responsibility" as well as the other two
1922 strings. Another example is given in the discussion of DEFINE above.
1923 </P>
1924 <P>
1925 Like recursive subpatterns, a "subroutine" call is always treated as an atomic
1926 group. That is, once it has matched some of the subject string, it is never
1927 re-entered, even if it contains untried alternatives and there is a subsequent
1928 matching failure.
1929 </P>
1930 <P>
1931 When a subpattern is used as a subroutine, processing options such as
1932 case-independence are fixed when the subpattern is defined. They cannot be
1933 changed for different calls. For example, consider this pattern:
1934 <pre>
1935 (abc)(?i:(?-1))
1936 </pre>
1937 It matches "abcabc". It does not match "abcABC" because the change of
1938 processing option does not affect the called subpattern.
1939 </P>
1940 <br><a name="SEC22" href="#TOC1">CALLOUTS</a><br>
1941 <P>
1942 Perl has a feature whereby using the sequence (?{...}) causes arbitrary Perl
1943 code to be obeyed in the middle of matching a regular expression. This makes it
1944 possible, amongst other things, to extract different substrings that match the
1945 same pair of parentheses when there is a repetition.
1946 </P>
1947 <P>
1948 PCRE provides a similar feature, but of course it cannot obey arbitrary Perl
1949 code. The feature is called "callout". The caller of PCRE provides an external
1950 function by putting its entry point in the global variable <i>pcre_callout</i>.
1951 By default, this variable contains NULL, which disables all calling out.
1952 </P>
1953 <P>
1954 Within a regular expression, (?C) indicates the points at which the external
1955 function is to be called. If you want to identify different callout points, you
1956 can put a number less than 256 after the letter C. The default value is zero.
1957 For example, this pattern has two callout points:
1958 <pre>
1959 (?C1)abc(?C2)def
1960 </pre>
1961 If the PCRE_AUTO_CALLOUT flag is passed to <b>pcre_compile()</b>, callouts are
1962 automatically installed before each item in the pattern. They are all numbered
1963 255.
1964 </P>
1965 <P>
1966 During matching, when PCRE reaches a callout point (and <i>pcre_callout</i> is
1967 set), the external function is called. It is provided with the number of the
1968 callout, the position in the pattern, and, optionally, one item of data
1969 originally supplied by the caller of <b>pcre_exec()</b>. The callout function
1970 may cause matching to proceed, to backtrack, or to fail altogether. A complete
1971 description of the interface to the callout function is given in the
1972 <a href="pcrecallout.html"><b>pcrecallout</b></a>
1973 documentation.
1974 </P>
1975 <br><a name="SEC23" href="#TOC1">SEE ALSO</a><br>
1976 <P>
1977 <b>pcreapi</b>(3), <b>pcrecallout</b>(3), <b>pcrematching</b>(3), <b>pcre</b>(3).
1978 </P>
1979 <br><a name="SEC24" href="#TOC1">AUTHOR</a><br>
1980 <P>
1981 Philip Hazel
1982 <br>
1983 University Computing Service
1984 <br>
1985 Cambridge CB2 3QH, England.
1986 <br>
1987 </P>
1988 <br><a name="SEC25" href="#TOC1">REVISION</a><br>
1989 <P>
1990 Last updated: 13 June 2007
1991 <br>
1992 Copyright &copy; 1997-2007 University of Cambridge.
1993 <br>
1994 <p>
1995 Return to the <a href="index.html">PCRE index page</a>.
1996 </p>

Properties

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

  ViewVC Help
Powered by ViewVC 1.1.5