ViewVC logotype

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

Parent Directory Parent Directory | Revision Log Revision Log

Revision 172 - (hide annotations) (download) (as text)
Tue Jun 5 10:40:13 2007 UTC (7 years, 10 months ago) by ph10
File MIME type: text/html
File size: 80828 byte(s)
Drastically reduce workspace used for alternatives in groups; also some 
trailing space removals for a test release.

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


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

ViewVC Help
Powered by ViewVC 1.1.12