ViewVC logotype

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

Parent Directory Parent Directory | Revision Log Revision Log

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


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

  ViewVC Help
Powered by ViewVC 1.1.5