/[pcre]/code/trunk/doc/pcre.3
ViewVC logotype

Contents of /code/trunk/doc/pcre.3

Parent Directory Parent Directory | Revision Log Revision Log


Revision 41 - (hide annotations) (download)
Sat Feb 24 21:39:17 2007 UTC (6 years, 2 months ago) by nigel
File size: 69815 byte(s)
Load pcre-2.08a into code/trunk.

1 nigel 41 .TH PCRE 3
2     .SH NAME
3     pcre - Perl-compatible regular expressions.
4     .SH SYNOPSIS
5     .B #include <pcre.h>
6     .PP
7     .SM
8     .br
9     .B pcre *pcre_compile(const char *\fIpattern\fR, int \fIoptions\fR,
10     .ti +5n
11     .B const char **\fIerrptr\fR, int *\fIerroffset\fR,
12     .ti +5n
13     .B const unsigned char *\fItableptr\fR);
14     .PP
15     .br
16     .B pcre_extra *pcre_study(const pcre *\fIcode\fR, int \fIoptions\fR,
17     .ti +5n
18     .B const char **\fIerrptr\fR);
19     .PP
20     .br
21     .B int pcre_exec(const pcre *\fIcode\fR, "const pcre_extra *\fIextra\fR,"
22     .ti +5n
23     .B "const char *\fIsubject\fR," int \fIlength\fR, int \fIstartoffset\fR,
24     .ti +5n
25     .B int \fIoptions\fR, int *\fIovector\fR, int \fIovecsize\fR);
26     .PP
27     .br
28     .B int pcre_copy_substring(const char *\fIsubject\fR, int *\fIovector\fR,
29     .ti +5n
30     .B int \fIstringcount\fR, int \fIstringnumber\fR, char *\fIbuffer\fR,
31     .ti +5n
32     .B int \fIbuffersize\fR);
33     .PP
34     .br
35     .B int pcre_get_substring(const char *\fIsubject\fR, int *\fIovector\fR,
36     .ti +5n
37     .B int \fIstringcount\fR, int \fIstringnumber\fR,
38     .ti +5n
39     .B const char **\fIstringptr\fR);
40     .PP
41     .br
42     .B int pcre_get_substring_list(const char *\fIsubject\fR,
43     .ti +5n
44     .B int *\fIovector\fR, int \fIstringcount\fR, "const char ***\fIlistptr\fR);"
45     .PP
46     .br
47     .B const unsigned char *pcre_maketables(void);
48     .PP
49     .br
50     .B int pcre_info(const pcre *\fIcode\fR, int *\fIoptptr\fR, int
51     .B *\fIfirstcharptr\fR);
52     .PP
53     .br
54     .B char *pcre_version(void);
55     .PP
56     .br
57     .B void *(*pcre_malloc)(size_t);
58     .PP
59     .br
60     .B void (*pcre_free)(void *);
61    
62    
63    
64     .SH DESCRIPTION
65     The PCRE library is a set of functions that implement regular expression
66     pattern matching using the same syntax and semantics as Perl 5, with just a few
67     differences (see below). The current implementation corresponds to Perl 5.005.
68    
69     PCRE has its own native API, which is described in this document. There is also
70     a set of wrapper functions that correspond to the POSIX API. These are
71     described in the \fBpcreposix\fR documentation.
72    
73     The native API function prototypes are defined in the header file \fBpcre.h\fR,
74     and on Unix systems the library itself is called \fBlibpcre.a\fR, so can be
75     accessed by adding \fB-lpcre\fR to the command for linking an application which
76     calls it.
77    
78     The functions \fBpcre_compile()\fR, \fBpcre_study()\fR, and \fBpcre_exec()\fR
79     are used for compiling and matching regular expressions, while
80     \fBpcre_copy_substring()\fR, \fBpcre_get_substring()\fR, and
81     \fBpcre_get_substring_list()\fR are convenience functions for extracting
82     captured substrings from a matched subject string. The function
83     \fBpcre_maketables()\fR is used (optionally) to build a set of character tables
84     in the current locale for passing to \fBpcre_compile()\fR.
85    
86     The function \fBpcre_info()\fR is used to find out information about a compiled
87     pattern, while the function \fBpcre_version()\fR returns a pointer to a string
88     containing the version of PCRE and its date of release.
89    
90     The global variables \fBpcre_malloc\fR and \fBpcre_free\fR initially contain
91     the entry points of the standard \fBmalloc()\fR and \fBfree()\fR functions
92     respectively. PCRE calls the memory management functions via these variables,
93     so a calling program can replace them if it wishes to intercept the calls. This
94     should be done before calling any PCRE functions.
95    
96    
97     .SH MULTI-THREADING
98     The PCRE functions can be used in multi-threading applications, with the
99     proviso that the memory management functions pointed to by \fBpcre_malloc\fR
100     and \fBpcre_free\fR are shared by all threads.
101    
102     The compiled form of a regular expression is not altered during matching, so
103     the same compiled pattern can safely be used by several threads at once.
104    
105    
106     .SH COMPILING A PATTERN
107     The function \fBpcre_compile()\fR is called to compile a pattern into an
108     internal form. The pattern is a C string terminated by a binary zero, and
109     is passed in the argument \fIpattern\fR. A pointer to a single block of memory
110     that is obtained via \fBpcre_malloc\fR is returned. This contains the
111     compiled code and related data. The \fBpcre\fR type is defined for this for
112     convenience, but in fact \fBpcre\fR is just a typedef for \fBvoid\fR, since the
113     contents of the block are not externally defined. It is up to the caller to
114     free the memory when it is no longer required.
115     .PP
116     The size of a compiled pattern is roughly proportional to the length of the
117     pattern string, except that each character class (other than those containing
118     just a single character, negated or not) requires 33 bytes, and repeat
119     quantifiers with a minimum greater than one or a bounded maximum cause the
120     relevant portions of the compiled pattern to be replicated.
121     .PP
122     The \fIoptions\fR argument contains independent bits that affect the
123     compilation. It should be zero if no options are required. Some of the options,
124     in particular, those that are compatible with Perl, can also be set and unset
125     from within the pattern (see the detailed description of regular expressions
126     below). For these options, the contents of the \fIoptions\fR argument specifies
127     their initial settings at the start of compilation and execution. The
128     PCRE_ANCHORED option can be set at the time of matching as well as at compile
129     time.
130     .PP
131     If \fIerrptr\fR is NULL, \fBpcre_compile()\fR returns NULL immediately.
132     Otherwise, if compilation of a pattern fails, \fBpcre_compile()\fR returns
133     NULL, and sets the variable pointed to by \fIerrptr\fR to point to a textual
134     error message. The offset from the start of the pattern to the character where
135     the error was discovered is placed in the variable pointed to by
136     \fIerroffset\fR, which must not be NULL. If it is, an immediate error is given.
137     .PP
138     If the final argument, \fItableptr\fR, is NULL, PCRE uses a default set of
139     character tables which are built when it is compiled, using the default C
140     locale. Otherwise, \fItableptr\fR must be the result of a call to
141     \fBpcre_maketables()\fR. See the section on locale support below.
142     .PP
143     The following option bits are defined in the header file:
144    
145     PCRE_ANCHORED
146    
147     If this bit is set, the pattern is forced to be "anchored", that is, it is
148     constrained to match only at the start of the string which is being searched
149     (the "subject string"). This effect can also be achieved by appropriate
150     constructs in the pattern itself, which is the only way to do it in Perl.
151    
152     PCRE_CASELESS
153    
154     If this bit is set, letters in the pattern match both upper and lower case
155     letters. It is equivalent to Perl's /i option.
156    
157     PCRE_DOLLAR_ENDONLY
158    
159     If this bit is set, a dollar metacharacter in the pattern matches only at the
160     end of the subject string. Without this option, a dollar also matches
161     immediately before the final character if it is a newline (but not before any
162     other newlines). The PCRE_DOLLAR_ENDONLY option is ignored if PCRE_MULTILINE is
163     set. There is no equivalent to this option in Perl.
164    
165     PCRE_DOTALL
166    
167     If this bit is set, a dot metacharater in the pattern matches all characters,
168     including newlines. Without it, newlines are excluded. This option is
169     equivalent to Perl's /s option. A negative class such as [^a] always matches a
170     newline character, independent of the setting of this option.
171    
172     PCRE_EXTENDED
173    
174     If this bit is set, whitespace data characters in the pattern are totally
175     ignored except when escaped or inside a character class, and characters between
176     an unescaped # outside a character class and the next newline character,
177     inclusive, are also ignored. This is equivalent to Perl's /x option, and makes
178     it possible to include comments inside complicated patterns. Note, however,
179     that this applies only to data characters. Whitespace characters may never
180     appear within special character sequences in a pattern, for example within the
181     sequence (?( which introduces a conditional subpattern.
182    
183     PCRE_EXTRA
184    
185     This option turns on additional functionality of PCRE that is incompatible with
186     Perl. Any backslash in a pattern that is followed by a letter that has no
187     special meaning causes an error, thus reserving these combinations for future
188     expansion. By default, as in Perl, a backslash followed by a letter with no
189     special meaning is treated as a literal. There are at present no other features
190     controlled by this option.
191    
192     PCRE_MULTILINE
193    
194     By default, PCRE treats the subject string as consisting of a single "line" of
195     characters (even if it actually contains several newlines). The "start of line"
196     metacharacter (^) matches only at the start of the string, while the "end of
197     line" metacharacter ($) matches only at the end of the string, or before a
198     terminating newline (unless PCRE_DOLLAR_ENDONLY is set). This is the same as
199     Perl.
200    
201     When PCRE_MULTILINE it is set, the "start of line" and "end of line" constructs
202     match immediately following or immediately before any newline in the subject
203     string, respectively, as well as at the very start and end. This is equivalent
204     to Perl's /m option. If there are no "\\n" characters in a subject string, or
205     no occurrences of ^ or $ in a pattern, setting PCRE_MULTILINE has no
206     effect.
207    
208     PCRE_UNGREEDY
209    
210     This option inverts the "greediness" of the quantifiers so that they are not
211     greedy by default, but become greedy if followed by "?". It is not compatible
212     with Perl. It can also be set by a (?U) option setting within the pattern.
213    
214    
215     .SH STUDYING A PATTERN
216     When a pattern is going to be used several times, it is worth spending more
217     time analyzing it in order to speed up the time taken for matching. The
218     function \fBpcre_study()\fR takes a pointer to a compiled pattern as its first
219     argument, and returns a pointer to a \fBpcre_extra\fR block (another \fBvoid\fR
220     typedef) containing additional information about the pattern; this can be
221     passed to \fBpcre_exec()\fR. If no additional information is available, NULL
222     is returned.
223    
224     The second argument contains option bits. At present, no options are defined
225     for \fBpcre_study()\fR, and this argument should always be zero.
226    
227     The third argument for \fBpcre_study()\fR is a pointer to an error message. If
228     studying succeeds (even if no data is returned), the variable it points to is
229     set to NULL. Otherwise it points to a textual error message.
230    
231     At present, studying a pattern is useful only for non-anchored patterns that do
232     not have a single fixed starting character. A bitmap of possible starting
233     characters is created.
234    
235    
236     .SH LOCALE SUPPORT
237     PCRE handles caseless matching, and determines whether characters are letters,
238     digits, or whatever, by reference to a set of tables. The library contains a
239     default set of tables which is created in the default C locale when PCRE is
240     compiled. This is used when the final argument of \fBpcre_compile()\fR is NULL,
241     and is sufficient for many applications.
242    
243     An alternative set of tables can, however, be supplied. Such tables are built
244     by calling the \fBpcre_maketables()\fR function, which has no arguments, in the
245     relevant locale. The result can then be passed to \fBpcre_compile()\fR as often
246     as necessary. For example, to build and use tables that are appropriate for the
247     French locale (where accented characters with codes greater than 128 are
248     treated as letters), the following code could be used:
249    
250     setlocale(LC_CTYPE, "fr");
251     tables = pcre_maketables();
252     re = pcre_compile(..., tables);
253    
254     The tables are built in memory that is obtained via \fBpcre_malloc\fR. The
255     pointer that is passed to \fBpcre_compile\fR is saved with the compiled
256     pattern, and the same tables are used via this pointer by \fBpcre_study()\fR
257     and \fBpcre_exec()\fR. Thus for any single pattern, compilation, studying and
258     matching all happen in the same locale, but different patterns can be compiled
259     in different locales. It is the caller's responsibility to ensure that the
260     memory containing the tables remains available for as long as it is needed.
261    
262    
263     .SH INFORMATION ABOUT A PATTERN
264     The \fBpcre_info()\fR function returns information about a compiled pattern.
265     Its yield is the number of capturing subpatterns, or one of the following
266     negative numbers:
267    
268     PCRE_ERROR_NULL the argument \fIcode\fR was NULL
269     PCRE_ERROR_BADMAGIC the "magic number" was not found
270    
271     If the \fIoptptr\fR argument is not NULL, a copy of the options with which the
272     pattern was compiled is placed in the integer it points to. These option bits
273     are those specified in the call to \fBpcre_compile()\fR, modified by any
274     top-level option settings within the pattern itself, and with the PCRE_ANCHORED
275     bit set if the form of the pattern implies that it can match only at the start
276     of a subject string.
277    
278     If the pattern is not anchored and the \fIfirstcharptr\fR argument is not NULL,
279     it is used to pass back information about the first character of any matched
280     string. If there is a fixed first character, e.g. from a pattern such as
281     (cat|cow|coyote), then it is returned in the integer pointed to by
282     \fIfirstcharptr\fR. Otherwise, if either
283    
284     (a) the pattern was compiled with the PCRE_MULTILINE option, and every branch
285     starts with "^", or
286    
287     (b) every branch of the pattern starts with ".*" and PCRE_DOTALL is not set
288     (if it were set, the pattern would be anchored),
289    
290     then -1 is returned, indicating that the pattern matches only at the
291     start of a subject string or after any "\\n" within the string. Otherwise -2 is
292     returned.
293    
294    
295     .SH MATCHING A PATTERN
296     The function \fBpcre_exec()\fR is called to match a subject string against a
297     pre-compiled pattern, which is passed in the \fIcode\fR argument. If the
298     pattern has been studied, the result of the study should be passed in the
299     \fIextra\fR argument. Otherwise this must be NULL.
300    
301     The PCRE_ANCHORED option can be passed in the \fIoptions\fR argument, whose
302     unused bits must be zero. However, if a pattern was compiled with
303     PCRE_ANCHORED, or turned out to be anchored by virtue of its contents, it
304     cannot be made unachored at matching time.
305    
306     There are also three further options that can be set only at matching time:
307    
308     PCRE_NOTBOL
309    
310     The first character of the string is not the beginning of a line, so the
311     circumflex metacharacter should not match before it. Setting this without
312     PCRE_MULTILINE (at compile time) causes circumflex never to match.
313    
314     PCRE_NOTEOL
315    
316     The end of the string is not the end of a line, so the dollar metacharacter
317     should not match it nor (except in multiline mode) a newline immediately before
318     it. Setting this without PCRE_MULTILINE (at compile time) causes dollar never
319     to match.
320    
321     PCRE_NOTEMPTY
322    
323     An empty string is not considered to be a valid match if this option is set. If
324     there are alternatives in the pattern, they are tried. If all the alternatives
325     match the empty string, the entire match fails. For example, if the pattern
326    
327     a?b?
328    
329     is applied to a string not beginning with "a" or "b", it matches the empty
330     string at the start of the subject. With PCRE_NOTEMPTY set, this match is not
331     valid, so PCRE searches further into the string for occurrences of "a" or "b".
332    
333     Perl has no direct equivalent of PCRE_NOTEMPTY, but it does make a special case
334     of a pattern match of the empty string within its \fBsplit()\fR function, and
335     when using the /g modifier. It is possible to emulate Perl's behaviour after
336     matching a null string by first trying the match again at the same offset with
337     PCRE_NOTEMPTY set, and then if that fails by advancing the starting offset (see
338     below) and trying an ordinary match again.
339    
340     The subject string is passed as a pointer in \fIsubject\fR, a length in
341     \fIlength\fR, and a starting offset in \fIstartoffset\fR. Unlike the pattern
342     string, it may contain binary zero characters. When the starting offset is
343     zero, the search for a match starts at the beginning of the subject, and this
344     is by far the most common case.
345    
346     A non-zero starting offset is useful when searching for another match in the
347     same subject by calling \fBpcre_exec()\fR again after a previous success.
348     Setting \fIstartoffset\fR differs from just passing over a shortened string and
349     setting PCRE_NOTBOL in the case of a pattern that begins with any kind of
350     lookbehind. For example, consider the pattern
351    
352     \\Biss\\B
353    
354     which finds occurrences of "iss" in the middle of words. (\\B matches only if
355     the current position in the subject is not a word boundary.) When applied to
356     the string "Mississipi" the first call to \fBpcre_exec()\fR finds the first
357     occurrence. If \fBpcre_exec()\fR is called again with just the remainder of the
358     subject, namely "issipi", it does not match, because \\B is always false at the
359     start of the subject, which is deemed to be a word boundary. However, if
360     \fBpcre_exec()\fR is passed the entire string again, but with \fIstartoffset\fR
361     set to 4, it finds the second occurrence of "iss" because it is able to look
362     behind the starting point to discover that it is preceded by a letter.
363    
364     If a non-zero starting offset is passed when the pattern is anchored, one
365     attempt to match at the given offset is tried. This can only succeed if the
366     pattern does not require the match to be at the start of the subject.
367    
368     In general, a pattern matches a certain portion of the subject, and in
369     addition, further substrings from the subject may be picked out by parts of the
370     pattern. Following the usage in Jeffrey Friedl's book, this is called
371     "capturing" in what follows, and the phrase "capturing subpattern" is used for
372     a fragment of a pattern that picks out a substring. PCRE supports several other
373     kinds of parenthesized subpattern that do not cause substrings to be captured.
374    
375     Captured substrings are returned to the caller via a vector of integer offsets
376     whose address is passed in \fIovector\fR. The number of elements in the vector
377     is passed in \fIovecsize\fR. The first two-thirds of the vector is used to pass
378     back captured substrings, each substring using a pair of integers. The
379     remaining third of the vector is used as workspace by \fBpcre_exec()\fR while
380     matching capturing subpatterns, and is not available for passing back
381     information. The length passed in \fIovecsize\fR should always be a multiple of
382     three. If it is not, it is rounded down.
383    
384     When a match has been successful, information about captured substrings is
385     returned in pairs of integers, starting at the beginning of \fIovector\fR, and
386     continuing up to two-thirds of its length at the most. The first element of a
387     pair is set to the offset of the first character in a substring, and the second
388     is set to the offset of the first character after the end of a substring. The
389     first pair, \fIovector[0]\fR and \fIovector[1]\fR, identify the portion of the
390     subject string matched by the entire pattern. The next pair is used for the
391     first capturing subpattern, and so on. The value returned by \fBpcre_exec()\fR
392     is the number of pairs that have been set. If there are no capturing
393     subpatterns, the return value from a successful match is 1, indicating that
394     just the first pair of offsets has been set.
395    
396     Some convenience functions are provided for extracting the captured substrings
397     as separate strings. These are described in the following section.
398    
399     It is possible for an capturing subpattern number \fIn+1\fR to match some
400     part of the subject when subpattern \fIn\fR has not been used at all. For
401     example, if the string "abc" is matched against the pattern (a|(z))(bc)
402     subpatterns 1 and 3 are matched, but 2 is not. When this happens, both offset
403     values corresponding to the unused subpattern are set to -1.
404    
405     If a capturing subpattern is matched repeatedly, it is the last portion of the
406     string that it matched that gets returned.
407    
408     If the vector is too small to hold all the captured substrings, it is used as
409     far as possible (up to two-thirds of its length), and the function returns a
410     value of zero. In particular, if the substring offsets are not of interest,
411     \fBpcre_exec()\fR may be called with \fIovector\fR passed as NULL and
412     \fIovecsize\fR as zero. However, if the pattern contains back references and
413     the \fIovector\fR isn't big enough to remember the related substrings, PCRE has
414     to get additional memory for use during matching. Thus it is usually advisable
415     to supply an \fIovector\fR.
416    
417     Note that \fBpcre_info()\fR can be used to find out how many capturing
418     subpatterns there are in a compiled pattern. The smallest size for
419     \fIovector\fR that will allow for \fIn\fR captured substrings in addition to
420     the offsets of the substring matched by the whole pattern is (\fIn\fR+1)*3.
421    
422     If \fBpcre_exec()\fR fails, it returns a negative number. The following are
423     defined in the header file:
424    
425     PCRE_ERROR_NOMATCH (-1)
426    
427     The subject string did not match the pattern.
428    
429     PCRE_ERROR_NULL (-2)
430    
431     Either \fIcode\fR or \fIsubject\fR was passed as NULL, or \fIovector\fR was
432     NULL and \fIovecsize\fR was not zero.
433    
434     PCRE_ERROR_BADOPTION (-3)
435    
436     An unrecognized bit was set in the \fIoptions\fR argument.
437    
438     PCRE_ERROR_BADMAGIC (-4)
439    
440     PCRE stores a 4-byte "magic number" at the start of the compiled code, to catch
441     the case when it is passed a junk pointer. This is the error it gives when the
442     magic number isn't present.
443    
444     PCRE_ERROR_UNKNOWN_NODE (-5)
445    
446     While running the pattern match, an unknown item was encountered in the
447     compiled pattern. This error could be caused by a bug in PCRE or by overwriting
448     of the compiled pattern.
449    
450     PCRE_ERROR_NOMEMORY (-6)
451    
452     If a pattern contains back references, but the \fIovector\fR that is passed to
453     \fBpcre_exec()\fR is not big enough to remember the referenced substrings, PCRE
454     gets a block of memory at the start of matching to use for this purpose. If the
455     call via \fBpcre_malloc()\fR fails, this error is given. The memory is freed at
456     the end of matching.
457    
458    
459     .SH EXTRACTING CAPTURED SUBSTRINGS
460     Captured substrings can be accessed directly by using the offsets returned by
461     \fBpcre_exec()\fR in \fIovector\fR. For convenience, the functions
462     \fBpcre_copy_substring()\fR, \fBpcre_get_substring()\fR, and
463     \fBpcre_get_substring_list()\fR are provided for extracting captured substrings
464     as new, separate, zero-terminated strings. A substring that contains a binary
465     zero is correctly extracted and has a further zero added on the end, but the
466     result does not, of course, function as a C string.
467    
468     The first three arguments are the same for all three functions: \fIsubject\fR
469     is the subject string which has just been successfully matched, \fIovector\fR
470     is a pointer to the vector of integer offsets that was passed to
471     \fBpcre_exec()\fR, and \fIstringcount\fR is the number of substrings that
472     were captured by the match, including the substring that matched the entire
473     regular expression. This is the value returned by \fBpcre_exec\fR if it
474     is greater than zero. If \fBpcre_exec()\fR returned zero, indicating that it
475     ran out of space in \fIovector\fR, then the value passed as
476     \fIstringcount\fR should be the size of the vector divided by three.
477    
478     The functions \fBpcre_copy_substring()\fR and \fBpcre_get_substring()\fR
479     extract a single substring, whose number is given as \fIstringnumber\fR. A
480     value of zero extracts the substring that matched the entire pattern, while
481     higher values extract the captured substrings. For \fBpcre_copy_substring()\fR,
482     the string is placed in \fIbuffer\fR, whose length is given by
483     \fIbuffersize\fR, while for \fBpcre_get_substring()\fR a new block of store is
484     obtained via \fBpcre_malloc\fR, and its address is returned via
485     \fIstringptr\fR. The yield of the function is the length of the string, not
486     including the terminating zero, or one of
487    
488     PCRE_ERROR_NOMEMORY (-6)
489    
490     The buffer was too small for \fBpcre_copy_substring()\fR, or the attempt to get
491     memory failed for \fBpcre_get_substring()\fR.
492    
493     PCRE_ERROR_NOSUBSTRING (-7)
494    
495     There is no substring whose number is \fIstringnumber\fR.
496    
497     The \fBpcre_get_substring_list()\fR function extracts all available substrings
498     and builds a list of pointers to them. All this is done in a single block of
499     memory which is obtained via \fBpcre_malloc\fR. The address of the memory block
500     is returned via \fIlistptr\fR, which is also the start of the list of string
501     pointers. The end of the list is marked by a NULL pointer. The yield of the
502     function is zero if all went well, or
503    
504     PCRE_ERROR_NOMEMORY (-6)
505    
506     if the attempt to get the memory block failed.
507    
508     When any of these functions encounter a substring that is unset, which can
509     happen when capturing subpattern number \fIn+1\fR matches some part of the
510     subject, but subpattern \fIn\fR has not been used at all, they return an empty
511     string. This can be distinguished from a genuine zero-length substring by
512     inspecting the appropriate offset in \fIovector\fR, which is negative for unset
513     substrings.
514    
515    
516    
517     .SH LIMITATIONS
518     There are some size limitations in PCRE but it is hoped that they will never in
519     practice be relevant.
520     The maximum length of a compiled pattern is 65539 (sic) bytes.
521     All values in repeating quantifiers must be less than 65536.
522     The maximum number of capturing subpatterns is 99.
523     The maximum number of all parenthesized subpatterns, including capturing
524     subpatterns, assertions, and other types of subpattern, is 200.
525    
526     The maximum length of a subject string is the largest positive number that an
527     integer variable can hold. However, PCRE uses recursion to handle subpatterns
528     and indefinite repetition. This means that the available stack space may limit
529     the size of a subject string that can be processed by certain patterns.
530    
531    
532     .SH DIFFERENCES FROM PERL
533     The differences described here are with respect to Perl 5.005.
534    
535     1. By default, a whitespace character is any character that the C library
536     function \fBisspace()\fR recognizes, though it is possible to compile PCRE with
537     alternative character type tables. Normally \fBisspace()\fR matches space,
538     formfeed, newline, carriage return, horizontal tab, and vertical tab. Perl 5
539     no longer includes vertical tab in its set of whitespace characters. The \\v
540     escape that was in the Perl documentation for a long time was never in fact
541     recognized. However, the character itself was treated as whitespace at least
542     up to 5.002. In 5.004 and 5.005 it does not match \\s.
543    
544     2. PCRE does not allow repeat quantifiers on lookahead assertions. Perl permits
545     them, but they do not mean what you might think. For example, (?!a){3} does
546     not assert that the next three characters are not "a". It just asserts that the
547     next character is not "a" three times.
548    
549     3. Capturing subpatterns that occur inside negative lookahead assertions are
550     counted, but their entries in the offsets vector are never set. Perl sets its
551     numerical variables from any such patterns that are matched before the
552     assertion fails to match something (thereby succeeding), but only if the
553     negative lookahead assertion contains just one branch.
554    
555     4. Though binary zero characters are supported in the subject string, they are
556     not allowed in a pattern string because it is passed as a normal C string,
557     terminated by zero. The escape sequence "\\0" can be used in the pattern to
558     represent a binary zero.
559    
560     5. The following Perl escape sequences are not supported: \\l, \\u, \\L, \\U,
561     \\E, \\Q. In fact these are implemented by Perl's general string-handling and
562     are not part of its pattern matching engine.
563    
564     6. The Perl \\G assertion is not supported as it is not relevant to single
565     pattern matches.
566    
567     7. Fairly obviously, PCRE does not support the (?{code}) construction.
568    
569     8. There are at the time of writing some oddities in Perl 5.005_02 concerned
570     with the settings of captured strings when part of a pattern is repeated. For
571     example, matching "aba" against the pattern /^(a(b)?)+$/ sets $2 to the value
572     "b", but matching "aabbaa" against /^(aa(bb)?)+$/ leaves $2 unset. However, if
573     the pattern is changed to /^(aa(b(b))?)+$/ then $2 (and $3) get set.
574    
575     In Perl 5.004 $2 is set in both cases, and that is also true of PCRE. If in the
576     future Perl changes to a consistent state that is different, PCRE may change to
577     follow.
578    
579     9. Another as yet unresolved discrepancy is that in Perl 5.005_02 the pattern
580     /^(a)?(?(1)a|b)+$/ matches the string "a", whereas in PCRE it does not.
581     However, in both Perl and PCRE /^(a)?a/ matched against "a" leaves $1 unset.
582    
583     10. PCRE provides some extensions to the Perl regular expression facilities:
584    
585     (a) Although lookbehind assertions must match fixed length strings, each
586     alternative branch of a lookbehind assertion can match a different length of
587     string. Perl 5.005 requires them all to have the same length.
588    
589     (b) If PCRE_DOLLAR_ENDONLY is set and PCRE_MULTILINE is not set, the $ meta-
590     character matches only at the very end of the string.
591    
592     (c) If PCRE_EXTRA is set, a backslash followed by a letter with no special
593     meaning is faulted.
594    
595     (d) If PCRE_UNGREEDY is set, the greediness of the repetition quantifiers is
596     inverted, that is, by default they are not greedy, but if followed by a
597     question mark they are.
598    
599     (e) PCRE_ANCHORED can be used to force a pattern to be tried only at the start
600     of the subject.
601    
602     (f) The PCRE_NOTBOL, PCRE_NOTEOL, and PCRE_NOTEMPTY options for
603     \fBpcre_exec()\fR have no Perl equivalents.
604    
605    
606     .SH REGULAR EXPRESSION DETAILS
607     The syntax and semantics of the regular expressions supported by PCRE are
608     described below. Regular expressions are also described in the Perl
609     documentation and in a number of other books, some of which have copious
610     examples. Jeffrey Friedl's "Mastering Regular Expressions", published by
611     O'Reilly (ISBN 1-56592-257-3), covers them in great detail. The description
612     here is intended as reference documentation.
613    
614     A regular expression is a pattern that is matched against a subject string from
615     left to right. Most characters stand for themselves in a pattern, and match the
616     corresponding characters in the subject. As a trivial example, the pattern
617    
618     The quick brown fox
619    
620     matches a portion of a subject string that is identical to itself. The power of
621     regular expressions comes from the ability to include alternatives and
622     repetitions in the pattern. These are encoded in the pattern by the use of
623     \fImeta-characters\fR, which do not stand for themselves but instead are
624     interpreted in some special way.
625    
626     There are two different sets of meta-characters: those that are recognized
627     anywhere in the pattern except within square brackets, and those that are
628     recognized in square brackets. Outside square brackets, the meta-characters are
629     as follows:
630    
631     \\ general escape character with several uses
632     ^ assert start of subject (or line, in multiline mode)
633     $ assert end of subject (or line, in multiline mode)
634     . match any character except newline (by default)
635     [ start character class definition
636     | start of alternative branch
637     ( start subpattern
638     ) end subpattern
639     ? extends the meaning of (
640     also 0 or 1 quantifier
641     also quantifier minimizer
642     * 0 or more quantifier
643     + 1 or more quantifier
644     { start min/max quantifier
645    
646     Part of a pattern that is in square brackets is called a "character class". In
647     a character class the only meta-characters are:
648    
649     \\ general escape character
650     ^ negate the class, but only if the first character
651     - indicates character range
652     ] terminates the character class
653    
654     The following sections describe the use of each of the meta-characters.
655    
656    
657     .SH BACKSLASH
658     The backslash character has several uses. Firstly, if it is followed by a
659     non-alphameric character, it takes away any special meaning that character may
660     have. This use of backslash as an escape character applies both inside and
661     outside character classes.
662    
663     For example, if you want to match a "*" character, you write "\\*" in the
664     pattern. This applies whether or not the following character would otherwise be
665     interpreted as a meta-character, so it is always safe to precede a
666     non-alphameric with "\\" to specify that it stands for itself. In particular,
667     if you want to match a backslash, you write "\\\\".
668    
669     If a pattern is compiled with the PCRE_EXTENDED option, whitespace in the
670     pattern (other than in a character class) and characters between a "#" outside
671     a character class and the next newline character are ignored. An escaping
672     backslash can be used to include a whitespace or "#" character as part of the
673     pattern.
674    
675     A second use of backslash provides a way of encoding non-printing characters
676     in patterns in a visible manner. There is no restriction on the appearance of
677     non-printing characters, apart from the binary zero that terminates a pattern,
678     but when a pattern is being prepared by text editing, it is usually easier to
679     use one of the following escape sequences than the binary character it
680     represents:
681    
682     \\a alarm, that is, the BEL character (hex 07)
683     \\cx "control-x", where x is any character
684     \\e escape (hex 1B)
685     \\f formfeed (hex 0C)
686     \\n newline (hex 0A)
687     \\r carriage return (hex 0D)
688     \\t tab (hex 09)
689     \\xhh character with hex code hh
690     \\ddd character with octal code ddd, or backreference
691    
692     The precise effect of "\\cx" is as follows: if "x" is a lower case letter, it
693     is converted to upper case. Then bit 6 of the character (hex 40) is inverted.
694     Thus "\\cz" becomes hex 1A, but "\\c{" becomes hex 3B, while "\\c;" becomes hex
695     7B.
696    
697     After "\\x", up to two hexadecimal digits are read (letters can be in upper or
698     lower case).
699    
700     After "\\0" up to two further octal digits are read. In both cases, if there
701     are fewer than two digits, just those that are present are used. Thus the
702     sequence "\\0\\x\\07" specifies two binary zeros followed by a BEL character.
703     Make sure you supply two digits after the initial zero if the character that
704     follows is itself an octal digit.
705    
706     The handling of a backslash followed by a digit other than 0 is complicated.
707     Outside a character class, PCRE reads it and any following digits as a decimal
708     number. If the number is less than 10, or if there have been at least that many
709     previous capturing left parentheses in the expression, the entire sequence is
710     taken as a \fIback reference\fR. A description of how this works is given
711     later, following the discussion of parenthesized subpatterns.
712    
713     Inside a character class, or if the decimal number is greater than 9 and there
714     have not been that many capturing subpatterns, PCRE re-reads up to three octal
715     digits following the backslash, and generates a single byte from the least
716     significant 8 bits of the value. Any subsequent digits stand for themselves.
717     For example:
718    
719     \\040 is another way of writing a space
720     \\40 is the same, provided there are fewer than 40
721     previous capturing subpatterns
722     \\7 is always a back reference
723     \\11 might be a back reference, or another way of
724     writing a tab
725     \\011 is always a tab
726     \\0113 is a tab followed by the character "3"
727     \\113 is the character with octal code 113 (since there
728     can be no more than 99 back references)
729     \\377 is a byte consisting entirely of 1 bits
730     \\81 is either a back reference, or a binary zero
731     followed by the two characters "8" and "1"
732    
733     Note that octal values of 100 or greater must not be introduced by a leading
734     zero, because no more than three octal digits are ever read.
735    
736     All the sequences that define a single byte value can be used both inside and
737     outside character classes. In addition, inside a character class, the sequence
738     "\\b" is interpreted as the backspace character (hex 08). Outside a character
739     class it has a different meaning (see below).
740    
741     The third use of backslash is for specifying generic character types:
742    
743     \\d any decimal digit
744     \\D any character that is not a decimal digit
745     \\s any whitespace character
746     \\S any character that is not a whitespace character
747     \\w any "word" character
748     \\W any "non-word" character
749    
750     Each pair of escape sequences partitions the complete set of characters into
751     two disjoint sets. Any given character matches one, and only one, of each pair.
752    
753     A "word" character is any letter or digit or the underscore character, that is,
754     any character which can be part of a Perl "word". The definition of letters and
755     digits is controlled by PCRE's character tables, and may vary if locale-
756     specific matching is taking place (see "Locale support" above). For example, in
757     the "fr" (French) locale, some character codes greater than 128 are used for
758     accented letters, and these are matched by \\w.
759    
760     These character type sequences can appear both inside and outside character
761     classes. They each match one character of the appropriate type. If the current
762     matching point is at the end of the subject string, all of them fail, since
763     there is no character to match.
764    
765     The fourth use of backslash is for certain simple assertions. An assertion
766     specifies a condition that has to be met at a particular point in a match,
767     without consuming any characters from the subject string. The use of
768     subpatterns for more complicated assertions is described below. The backslashed
769     assertions are
770    
771     \\b word boundary
772     \\B not a word boundary
773     \\A start of subject (independent of multiline mode)
774     \\Z end of subject or newline at end (independent of multiline mode)
775     \\z end of subject (independent of multiline mode)
776    
777     These assertions may not appear in character classes (but note that "\\b" has a
778     different meaning, namely the backspace character, inside a character class).
779    
780     A word boundary is a position in the subject string where the current character
781     and the previous character do not both match \\w or \\W (i.e. one matches
782     \\w and the other matches \\W), or the start or end of the string if the
783     first or last character matches \\w, respectively.
784    
785     The \\A, \\Z, and \\z assertions differ from the traditional circumflex and
786     dollar (described below) in that they only ever match at the very start and end
787     of the subject string, whatever options are set. They are not affected by the
788     PCRE_NOTBOL or PCRE_NOTEOL options. If the \fIstartoffset\fR argument of
789     \fBpcre_exec()\fR is non-zero, \\A can never match. The difference between \\Z
790     and \\z is that \\Z matches before a newline that is the last character of the
791     string as well as at the end of the string, whereas \\z matches only at the
792     end.
793    
794    
795     .SH CIRCUMFLEX AND DOLLAR
796     Outside a character class, in the default matching mode, the circumflex
797     character is an assertion which is true only if the current matching point is
798     at the start of the subject string. If the \fIstartoffset\fR argument of
799     \fBpcre_exec()\fR is non-zero, circumflex can never match. Inside a character
800     class, circumflex has an entirely different meaning (see below).
801    
802     Circumflex need not be the first character of the pattern if a number of
803     alternatives are involved, but it should be the first thing in each alternative
804     in which it appears if the pattern is ever to match that branch. If all
805     possible alternatives start with a circumflex, that is, if the pattern is
806     constrained to match only at the start of the subject, it is said to be an
807     "anchored" pattern. (There are also other constructs that can cause a pattern
808     to be anchored.)
809    
810     A dollar character is an assertion which is true only if the current matching
811     point is at the end of the subject string, or immediately before a newline
812     character that is the last character in the string (by default). Dollar need
813     not be the last character of the pattern if a number of alternatives are
814     involved, but it should be the last item in any branch in which it appears.
815     Dollar has no special meaning in a character class.
816    
817     The meaning of dollar can be changed so that it matches only at the very end of
818     the string, by setting the PCRE_DOLLAR_ENDONLY option at compile or matching
819     time. This does not affect the \\Z assertion.
820    
821     The meanings of the circumflex and dollar characters are changed if the
822     PCRE_MULTILINE option is set. When this is the case, they match immediately
823     after and immediately before an internal "\\n" character, respectively, in
824     addition to matching at the start and end of the subject string. For example,
825     the pattern /^abc$/ matches the subject string "def\\nabc" in multiline mode,
826     but not otherwise. Consequently, patterns that are anchored in single line mode
827     because all branches start with "^" are not anchored in multiline mode, and a
828     match for circumflex is possible when the \fIstartoffset\fR argument of
829     \fBpcre_exec()\fR is non-zero. The PCRE_DOLLAR_ENDONLY option is ignored if
830     PCRE_MULTILINE is set.
831    
832     Note that the sequences \\A, \\Z, and \\z can be used to match the start and
833     end of the subject in both modes, and if all branches of a pattern start with
834     \\A is it always anchored, whether PCRE_MULTILINE is set or not.
835    
836    
837     .SH FULL STOP (PERIOD, DOT)
838     Outside a character class, a dot in the pattern matches any one character in
839     the subject, including a non-printing character, but not (by default) newline.
840     If the PCRE_DOTALL option is set, then dots match newlines as well. The
841     handling of dot is entirely independent of the handling of circumflex and
842     dollar, the only relationship being that they both involve newline characters.
843     Dot has no special meaning in a character class.
844    
845    
846     .SH SQUARE BRACKETS
847     An opening square bracket introduces a character class, terminated by a closing
848     square bracket. A closing square bracket on its own is not special. If a
849     closing square bracket is required as a member of the class, it should be the
850     first data character in the class (after an initial circumflex, if present) or
851     escaped with a backslash.
852    
853     A character class matches a single character in the subject; the character must
854     be in the set of characters defined by the class, unless the first character in
855     the class is a circumflex, in which case the subject character must not be in
856     the set defined by the class. If a circumflex is actually required as a member
857     of the class, ensure it is not the first character, or escape it with a
858     backslash.
859    
860     For example, the character class [aeiou] matches any lower case vowel, while
861     [^aeiou] matches any character that is not a lower case vowel. Note that a
862     circumflex is just a convenient notation for specifying the characters which
863     are in the class by enumerating those that are not. It is not an assertion: it
864     still consumes a character from the subject string, and fails if the current
865     pointer is at the end of the string.
866    
867     When caseless matching is set, any letters in a class represent both their
868     upper case and lower case versions, so for example, a caseless [aeiou] matches
869     "A" as well as "a", and a caseless [^aeiou] does not match "A", whereas a
870     caseful version would.
871    
872     The newline character is never treated in any special way in character classes,
873     whatever the setting of the PCRE_DOTALL or PCRE_MULTILINE options is. A class
874     such as [^a] will always match a newline.
875    
876     The minus (hyphen) character can be used to specify a range of characters in a
877     character class. For example, [d-m] matches any letter between d and m,
878     inclusive. If a minus character is required in a class, it must be escaped with
879     a backslash or appear in a position where it cannot be interpreted as
880     indicating a range, typically as the first or last character in the class.
881    
882     It is not possible to have the literal character "]" as the end character of a
883     range. A pattern such as [W-]46] is interpreted as a class of two characters
884     ("W" and "-") followed by a literal string "46]", so it would match "W46]" or
885     "-46]". However, if the "]" is escaped with a backslash it is interpreted as
886     the end of range, so [W-\\]46] is interpreted as a single class containing a
887     range followed by two separate characters. The octal or hexadecimal
888     representation of "]" can also be used to end a range.
889    
890     Ranges operate in ASCII collating sequence. They can also be used for
891     characters specified numerically, for example [\\000-\\037]. If a range that
892     includes letters is used when caseless matching is set, it matches the letters
893     in either case. For example, [W-c] is equivalent to [][\\^_`wxyzabc], matched
894     caselessly, and if character tables for the "fr" locale are in use,
895     [\\xc8-\\xcb] matches accented E characters in both cases.
896    
897     The character types \\d, \\D, \\s, \\S, \\w, and \\W may also appear in a
898     character class, and add the characters that they match to the class. For
899     example, [\\dABCDEF] matches any hexadecimal digit. A circumflex can
900     conveniently be used with the upper case character types to specify a more
901     restricted set of characters than the matching lower case type. For example,
902     the class [^\\W_] matches any letter or digit, but not underscore.
903    
904     All non-alphameric characters other than \\, -, ^ (at the start) and the
905     terminating ] are non-special in character classes, but it does no harm if they
906     are escaped.
907    
908    
909     .SH VERTICAL BAR
910     Vertical bar characters are used to separate alternative patterns. For example,
911     the pattern
912    
913     gilbert|sullivan
914    
915     matches either "gilbert" or "sullivan". Any number of alternatives may appear,
916     and an empty alternative is permitted (matching the empty string).
917     The matching process tries each alternative in turn, from left to right,
918     and the first one that succeeds is used. If the alternatives are within a
919     subpattern (defined below), "succeeds" means matching the rest of the main
920     pattern as well as the alternative in the subpattern.
921    
922    
923     .SH INTERNAL OPTION SETTING
924     The settings of PCRE_CASELESS, PCRE_MULTILINE, PCRE_DOTALL, and PCRE_EXTENDED
925     can be changed from within the pattern by a sequence of Perl option letters
926     enclosed between "(?" and ")". The option letters are
927    
928     i for PCRE_CASELESS
929     m for PCRE_MULTILINE
930     s for PCRE_DOTALL
931     x for PCRE_EXTENDED
932    
933     For example, (?im) sets caseless, multiline matching. It is also possible to
934     unset these options by preceding the letter with a hyphen, and a combined
935     setting and unsetting such as (?im-sx), which sets PCRE_CASELESS and
936     PCRE_MULTILINE while unsetting PCRE_DOTALL and PCRE_EXTENDED, is also
937     permitted. If a letter appears both before and after the hyphen, the option is
938     unset.
939    
940     The scope of these option changes depends on where in the pattern the setting
941     occurs. For settings that are outside any subpattern (defined below), the
942     effect is the same as if the options were set or unset at the start of
943     matching. The following patterns all behave in exactly the same way:
944    
945     (?i)abc
946     a(?i)bc
947     ab(?i)c
948     abc(?i)
949    
950     which in turn is the same as compiling the pattern abc with PCRE_CASELESS set.
951     In other words, such "top level" settings apply to the whole pattern (unless
952     there are other changes inside subpatterns). If there is more than one setting
953     of the same option at top level, the rightmost setting is used.
954    
955     If an option change occurs inside a subpattern, the effect is different. This
956     is a change of behaviour in Perl 5.005. An option change inside a subpattern
957     affects only that part of the subpattern that follows it, so
958    
959     (a(?i)b)c
960    
961     matches abc and aBc and no other strings (assuming PCRE_CASELESS is not used).
962     By this means, options can be made to have different settings in different
963     parts of the pattern. Any changes made in one alternative do carry on
964     into subsequent branches within the same subpattern. For example,
965    
966     (a(?i)b|c)
967    
968     matches "ab", "aB", "c", and "C", even though when matching "C" the first
969     branch is abandoned before the option setting. This is because the effects of
970     option settings happen at compile time. There would be some very weird
971     behaviour otherwise.
972    
973     The PCRE-specific options PCRE_UNGREEDY and PCRE_EXTRA can be changed in the
974     same way as the Perl-compatible options by using the characters U and X
975     respectively. The (?X) flag setting is special in that it must always occur
976     earlier in the pattern than any of the additional features it turns on, even
977     when it is at top level. It is best put at the start.
978    
979    
980     .SH SUBPATTERNS
981     Subpatterns are delimited by parentheses (round brackets), which can be nested.
982     Marking part of a pattern as a subpattern does two things:
983    
984     1. It localizes a set of alternatives. For example, the pattern
985    
986     cat(aract|erpillar|)
987    
988     matches one of the words "cat", "cataract", or "caterpillar". Without the
989     parentheses, it would match "cataract", "erpillar" or the empty string.
990    
991     2. It sets up the subpattern as a capturing subpattern (as defined above).
992     When the whole pattern matches, that portion of the subject string that matched
993     the subpattern is passed back to the caller via the \fIovector\fR argument of
994     \fBpcre_exec()\fR. Opening parentheses are counted from left to right (starting
995     from 1) to obtain the numbers of the capturing subpatterns.
996    
997     For example, if the string "the red king" is matched against the pattern
998    
999     the ((red|white) (king|queen))
1000    
1001     the captured substrings are "red king", "red", and "king", and are numbered 1,
1002     2, and 3.
1003    
1004     The fact that plain parentheses fulfil two functions is not always helpful.
1005     There are often times when a grouping subpattern is required without a
1006     capturing requirement. If an opening parenthesis is followed by "?:", the
1007     subpattern does not do any capturing, and is not counted when computing the
1008     number of any subsequent capturing subpatterns. For example, if the string "the
1009     white queen" is matched against the pattern
1010    
1011     the ((?:red|white) (king|queen))
1012    
1013     the captured substrings are "white queen" and "queen", and are numbered 1 and
1014     2. The maximum number of captured substrings is 99, and the maximum number of
1015     all subpatterns, both capturing and non-capturing, is 200.
1016    
1017     As a convenient shorthand, if any option settings are required at the start of
1018     a non-capturing subpattern, the option letters may appear between the "?" and
1019     the ":". Thus the two patterns
1020    
1021     (?i:saturday|sunday)
1022     (?:(?i)saturday|sunday)
1023    
1024     match exactly the same set of strings. Because alternative branches are tried
1025     from left to right, and options are not reset until the end of the subpattern
1026     is reached, an option setting in one branch does affect subsequent branches, so
1027     the above patterns match "SUNDAY" as well as "Saturday".
1028    
1029    
1030     .SH REPETITION
1031     Repetition is specified by quantifiers, which can follow any of the following
1032     items:
1033    
1034     a single character, possibly escaped
1035     the . metacharacter
1036     a character class
1037     a back reference (see next section)
1038     a parenthesized subpattern (unless it is an assertion - see below)
1039    
1040     The general repetition quantifier specifies a minimum and maximum number of
1041     permitted matches, by giving the two numbers in curly brackets (braces),
1042     separated by a comma. The numbers must be less than 65536, and the first must
1043     be less than or equal to the second. For example:
1044    
1045     z{2,4}
1046    
1047     matches "zz", "zzz", or "zzzz". A closing brace on its own is not a special
1048     character. If the second number is omitted, but the comma is present, there is
1049     no upper limit; if the second number and the comma are both omitted, the
1050     quantifier specifies an exact number of required matches. Thus
1051    
1052     [aeiou]{3,}
1053    
1054     matches at least 3 successive vowels, but may match many more, while
1055    
1056     \\d{8}
1057    
1058     matches exactly 8 digits. An opening curly bracket that appears in a position
1059     where a quantifier is not allowed, or one that does not match the syntax of a
1060     quantifier, is taken as a literal character. For example, {,6} is not a
1061     quantifier, but a literal string of four characters.
1062    
1063     The quantifier {0} is permitted, causing the expression to behave as if the
1064     previous item and the quantifier were not present.
1065    
1066     For convenience (and historical compatibility) the three most common
1067     quantifiers have single-character abbreviations:
1068    
1069     * is equivalent to {0,}
1070     + is equivalent to {1,}
1071     ? is equivalent to {0,1}
1072    
1073     It is possible to construct infinite loops by following a subpattern that can
1074     match no characters with a quantifier that has no upper limit, for example:
1075    
1076     (a?)*
1077    
1078     Earlier versions of Perl and PCRE used to give an error at compile time for
1079     such patterns. However, because there are cases where this can be useful, such
1080     patterns are now accepted, but if any repetition of the subpattern does in fact
1081     match no characters, the loop is forcibly broken.
1082    
1083     By default, the quantifiers are "greedy", that is, they match as much as
1084     possible (up to the maximum number of permitted times), without causing the
1085     rest of the pattern to fail. The classic example of where this gives problems
1086     is in trying to match comments in C programs. These appear between the
1087     sequences /* and */ and within the sequence, individual * and / characters may
1088     appear. An attempt to match C comments by applying the pattern
1089    
1090     /\\*.*\\*/
1091    
1092     to the string
1093    
1094     /* first command */ not comment /* second comment */
1095    
1096     fails, because it matches the entire string due to the greediness of the .*
1097     item.
1098    
1099     However, if a quantifier is followed by a question mark, then it ceases to be
1100     greedy, and instead matches the minimum number of times possible, so the
1101     pattern
1102    
1103     /\\*.*?\\*/
1104    
1105     does the right thing with the C comments. The meaning of the various
1106     quantifiers is not otherwise changed, just the preferred number of matches.
1107     Do not confuse this use of question mark with its use as a quantifier in its
1108     own right. Because it has two uses, it can sometimes appear doubled, as in
1109    
1110     \\d??\\d
1111    
1112     which matches one digit by preference, but can match two if that is the only
1113     way the rest of the pattern matches.
1114    
1115     If the PCRE_UNGREEDY option is set (an option which is not available in Perl)
1116     then the quantifiers are not greedy by default, but individual ones can be made
1117     greedy by following them with a question mark. In other words, it inverts the
1118     default behaviour.
1119    
1120     When a parenthesized subpattern is quantified with a minimum repeat count that
1121     is greater than 1 or with a limited maximum, more store is required for the
1122     compiled pattern, in proportion to the size of the minimum or maximum.
1123    
1124     If a pattern starts with .* or .{0,} and the PCRE_DOTALL option (equivalent
1125     to Perl's /s) is set, thus allowing the . to match newlines, then the pattern
1126     is implicitly anchored, because whatever follows will be tried against every
1127     character position in the subject string, so there is no point in retrying the
1128     overall match at any position after the first. PCRE treats such a pattern as
1129     though it were preceded by \\A. In cases where it is known that the subject
1130     string contains no newlines, it is worth setting PCRE_DOTALL when the pattern
1131     begins with .* in order to obtain this optimization, or alternatively using ^
1132     to indicate anchoring explicitly.
1133    
1134     When a capturing subpattern is repeated, the value captured is the substring
1135     that matched the final iteration. For example, after
1136    
1137     (tweedle[dume]{3}\\s*)+
1138    
1139     has matched "tweedledum tweedledee" the value of the captured substring is
1140     "tweedledee". However, if there are nested capturing subpatterns, the
1141     corresponding captured values may have been set in previous iterations. For
1142     example, after
1143    
1144     /(a|(b))+/
1145    
1146     matches "aba" the value of the second captured substring is "b".
1147    
1148    
1149     .SH BACK REFERENCES
1150     Outside a character class, a backslash followed by a digit greater than 0 (and
1151     possibly further digits) is a back reference to a capturing subpattern earlier
1152     (i.e. to its left) in the pattern, provided there have been that many previous
1153     capturing left parentheses.
1154    
1155     However, if the decimal number following the backslash is less than 10, it is
1156     always taken as a back reference, and causes an error only if there are not
1157     that many capturing left parentheses in the entire pattern. In other words, the
1158     parentheses that are referenced need not be to the left of the reference for
1159     numbers less than 10. See the section entitled "Backslash" above for further
1160     details of the handling of digits following a backslash.
1161    
1162     A back reference matches whatever actually matched the capturing subpattern in
1163     the current subject string, rather than anything matching the subpattern
1164     itself. So the pattern
1165    
1166     (sens|respons)e and \\1ibility
1167    
1168     matches "sense and sensibility" and "response and responsibility", but not
1169     "sense and responsibility". If caseful matching is in force at the time of the
1170     back reference, then the case of letters is relevant. For example,
1171    
1172     ((?i)rah)\\s+\\1
1173    
1174     matches "rah rah" and "RAH RAH", but not "RAH rah", even though the original
1175     capturing subpattern is matched caselessly.
1176    
1177     There may be more than one back reference to the same subpattern. If a
1178     subpattern has not actually been used in a particular match, then any back
1179     references to it always fail. For example, the pattern
1180    
1181     (a|(bc))\\2
1182    
1183     always fails if it starts to match "a" rather than "bc". Because there may be
1184     up to 99 back references, all digits following the backslash are taken
1185     as part of a potential back reference number. If the pattern continues with a
1186     digit character, then some delimiter must be used to terminate the back
1187     reference. If the PCRE_EXTENDED option is set, this can be whitespace.
1188     Otherwise an empty comment can be used.
1189    
1190     A back reference that occurs inside the parentheses to which it refers fails
1191     when the subpattern is first used, so, for example, (a\\1) never matches.
1192     However, such references can be useful inside repeated subpatterns. For
1193     example, the pattern
1194    
1195     (a|b\\1)+
1196    
1197     matches any number of "a"s and also "aba", "ababaa" etc. At each iteration of
1198     the subpattern, the back reference matches the character string corresponding
1199     to the previous iteration. In order for this to work, the pattern must be such
1200     that the first iteration does not need to match the back reference. This can be
1201     done using alternation, as in the example above, or by a quantifier with a
1202     minimum of zero.
1203    
1204    
1205     .SH ASSERTIONS
1206     An assertion is a test on the characters following or preceding the current
1207     matching point that does not actually consume any characters. The simple
1208     assertions coded as \\b, \\B, \\A, \\Z, \\z, ^ and $ are described above. More
1209     complicated assertions are coded as subpatterns. There are two kinds: those
1210     that look ahead of the current position in the subject string, and those that
1211     look behind it.
1212    
1213     An assertion subpattern is matched in the normal way, except that it does not
1214     cause the current matching position to be changed. Lookahead assertions start
1215     with (?= for positive assertions and (?! for negative assertions. For example,
1216    
1217     \\w+(?=;)
1218    
1219     matches a word followed by a semicolon, but does not include the semicolon in
1220     the match, and
1221    
1222     foo(?!bar)
1223    
1224     matches any occurrence of "foo" that is not followed by "bar". Note that the
1225     apparently similar pattern
1226    
1227     (?!foo)bar
1228    
1229     does not find an occurrence of "bar" that is preceded by something other than
1230     "foo"; it finds any occurrence of "bar" whatsoever, because the assertion
1231     (?!foo) is always true when the next three characters are "bar". A
1232     lookbehind assertion is needed to achieve this effect.
1233    
1234     Lookbehind assertions start with (?<= for positive assertions and (?<! for
1235     negative assertions. For example,
1236    
1237     (?<!foo)bar
1238    
1239     does find an occurrence of "bar" that is not preceded by "foo". The contents of
1240     a lookbehind assertion are restricted such that all the strings it matches must
1241     have a fixed length. However, if there are several alternatives, they do not
1242     all have to have the same fixed length. Thus
1243    
1244     (?<=bullock|donkey)
1245    
1246     is permitted, but
1247    
1248     (?<!dogs?|cats?)
1249    
1250     causes an error at compile time. Branches that match different length strings
1251     are permitted only at the top level of a lookbehind assertion. This is an
1252     extension compared with Perl 5.005, which requires all branches to match the
1253     same length of string. An assertion such as
1254    
1255     (?<=ab(c|de))
1256    
1257     is not permitted, because its single top-level branch can match two different
1258     lengths, but it is acceptable if rewritten to use two top-level branches:
1259    
1260     (?<=abc|abde)
1261    
1262     The implementation of lookbehind assertions is, for each alternative, to
1263     temporarily move the current position back by the fixed width and then try to
1264     match. If there are insufficient characters before the current position, the
1265     match is deemed to fail. Lookbehinds in conjunction with once-only subpatterns
1266     can be particularly useful for matching at the ends of strings; an example is
1267     given at the end of the section on once-only subpatterns.
1268    
1269     Several assertions (of any sort) may occur in succession. For example,
1270    
1271     (?<=\\d{3})(?<!999)foo
1272    
1273     matches "foo" preceded by three digits that are not "999". Notice that each of
1274     the assertions is applied independently at the same point in the subject
1275     string. First there is a check that the previous three characters are all
1276     digits, then there is a check that the same three characters are not "999".
1277     This pattern does \fInot\fR match "foo" preceded by six characters, the first
1278     of which are digits and the last three of which are not "999". For example, it
1279     doesn't match "123abcfoo". A pattern to do that is
1280    
1281     (?<=\\d{3}...)(?<!999)foo
1282    
1283     This time the first assertion looks at the preceding six characters, checking
1284     that the first three are digits, and then the second assertion checks that the
1285     preceding three characters are not "999".
1286    
1287     Assertions can be nested in any combination. For example,
1288    
1289     (?<=(?<!foo)bar)baz
1290    
1291     matches an occurrence of "baz" that is preceded by "bar" which in turn is not
1292     preceded by "foo", while
1293    
1294     (?<=\\d{3}(?!999)...)foo
1295    
1296     is another pattern which matches "foo" preceded by three digits and any three
1297     characters that are not "999".
1298    
1299     Assertion subpatterns are not capturing subpatterns, and may not be repeated,
1300     because it makes no sense to assert the same thing several times. If any kind
1301     of assertion contains capturing subpatterns within it, these are counted for
1302     the purposes of numbering the capturing subpatterns in the whole pattern.
1303     However, substring capturing is carried out only for positive assertions,
1304     because it does not make sense for negative assertions.
1305    
1306     Assertions count towards the maximum of 200 parenthesized subpatterns.
1307    
1308    
1309     .SH ONCE-ONLY SUBPATTERNS
1310     With both maximizing and minimizing repetition, failure of what follows
1311     normally causes the repeated item to be re-evaluated to see if a different
1312     number of repeats allows the rest of the pattern to match. Sometimes it is
1313     useful to prevent this, either to change the nature of the match, or to cause
1314     it fail earlier than it otherwise might, when the author of the pattern knows
1315     there is no point in carrying on.
1316    
1317     Consider, for example, the pattern \\d+foo when applied to the subject line
1318    
1319     123456bar
1320    
1321     After matching all 6 digits and then failing to match "foo", the normal
1322     action of the matcher is to try again with only 5 digits matching the \\d+
1323     item, and then with 4, and so on, before ultimately failing. Once-only
1324     subpatterns provide the means for specifying that once a portion of the pattern
1325     has matched, it is not to be re-evaluated in this way, so the matcher would
1326     give up immediately on failing to match "foo" the first time. The notation is
1327     another kind of special parenthesis, starting with (?> as in this example:
1328    
1329     (?>\\d+)bar
1330    
1331     This kind of parenthesis "locks up" the part of the pattern it contains once
1332     it has matched, and a failure further into the pattern is prevented from
1333     backtracking into it. Backtracking past it to previous items, however, works as
1334     normal.
1335    
1336     An alternative description is that a subpattern of this type matches the string
1337     of characters that an identical standalone pattern would match, if anchored at
1338     the current point in the subject string.
1339    
1340     Once-only subpatterns are not capturing subpatterns. Simple cases such as the
1341     above example can be thought of as a maximizing repeat that must swallow
1342     everything it can. So, while both \\d+ and \\d+? are prepared to adjust the
1343     number of digits they match in order to make the rest of the pattern match,
1344     (?>\\d+) can only match an entire sequence of digits.
1345    
1346     This construction can of course contain arbitrarily complicated subpatterns,
1347     and it can be nested.
1348    
1349     Once-only subpatterns can be used in conjunction with lookbehind assertions to
1350     specify efficient matching at the end of the subject string. Consider a simple
1351     pattern such as
1352    
1353     abcd$
1354    
1355     when applied to a long string which does not match it. Because matching
1356     proceeds from left to right, PCRE will look for each "a" in the subject and
1357     then see if what follows matches the rest of the pattern. If the pattern is
1358     specified as
1359    
1360     ^.*abcd$
1361    
1362     then the initial .* matches the entire string at first, but when this fails, it
1363     backtracks to match all but the last character, then all but the last two
1364     characters, and so on. Once again the search for "a" covers the entire string,
1365     from right to left, so we are no better off. However, if the pattern is written
1366     as
1367    
1368     ^(?>.*)(?<=abcd)
1369    
1370     then there can be no backtracking for the .* item; it can match only the entire
1371     string. The subsequent lookbehind assertion does a single test on the last four
1372     characters. If it fails, the match fails immediately. For long strings, this
1373     approach makes a significant difference to the processing time.
1374    
1375    
1376     .SH CONDITIONAL SUBPATTERNS
1377     It is possible to cause the matching process to obey a subpattern
1378     conditionally or to choose between two alternative subpatterns, depending on
1379     the result of an assertion, or whether a previous capturing subpattern matched
1380     or not. The two possible forms of conditional subpattern are
1381    
1382     (?(condition)yes-pattern)
1383     (?(condition)yes-pattern|no-pattern)
1384    
1385     If the condition is satisfied, the yes-pattern is used; otherwise the
1386     no-pattern (if present) is used. If there are more than two alternatives in the
1387     subpattern, a compile-time error occurs.
1388    
1389     There are two kinds of condition. If the text between the parentheses consists
1390     of a sequence of digits, then the condition is satisfied if the capturing
1391     subpattern of that number has previously matched. Consider the following
1392     pattern, which contains non-significant white space to make it more readable
1393     (assume the PCRE_EXTENDED option) and to divide it into three parts for ease
1394     of discussion:
1395    
1396     ( \\( )? [^()]+ (?(1) \\) )
1397    
1398     The first part matches an optional opening parenthesis, and if that
1399     character is present, sets it as the first captured substring. The second part
1400     matches one or more characters that are not parentheses. The third part is a
1401     conditional subpattern that tests whether the first set of parentheses matched
1402     or not. If they did, that is, if subject started with an opening parenthesis,
1403     the condition is true, and so the yes-pattern is executed and a closing
1404     parenthesis is required. Otherwise, since no-pattern is not present, the
1405     subpattern matches nothing. In other words, this pattern matches a sequence of
1406     non-parentheses, optionally enclosed in parentheses.
1407    
1408     If the condition is not a sequence of digits, it must be an assertion. This may
1409     be a positive or negative lookahead or lookbehind assertion. Consider this
1410     pattern, again containing non-significant white space, and with the two
1411     alternatives on the second line:
1412    
1413     (?(?=[^a-z]*[a-z])
1414     \\d{2}-[a-z]{3}-\\d{2} | \\d{2}-\\d{2}-\\d{2} )
1415    
1416     The condition is a positive lookahead assertion that matches an optional
1417     sequence of non-letters followed by a letter. In other words, it tests for the
1418     presence of at least one letter in the subject. If a letter is found, the
1419     subject is matched against the first alternative; otherwise it is matched
1420     against the second. This pattern matches strings in one of the two forms
1421     dd-aaa-dd or dd-dd-dd, where aaa are letters and dd are digits.
1422    
1423    
1424     .SH COMMENTS
1425     The sequence (?# marks the start of a comment which continues up to the next
1426     closing parenthesis. Nested parentheses are not permitted. The characters
1427     that make up a comment play no part in the pattern matching at all.
1428    
1429     If the PCRE_EXTENDED option is set, an unescaped # character outside a
1430     character class introduces a comment that continues up to the next newline
1431     character in the pattern.
1432    
1433    
1434     .SH PERFORMANCE
1435     Certain items that may appear in patterns are more efficient than others. It is
1436     more efficient to use a character class like [aeiou] than a set of alternatives
1437     such as (a|e|i|o|u). In general, the simplest construction that provides the
1438     required behaviour is usually the most efficient. Jeffrey Friedl's book
1439     contains a lot of discussion about optimizing regular expressions for efficient
1440     performance.
1441    
1442     When a pattern begins with .* and the PCRE_DOTALL option is set, the pattern is
1443     implicitly anchored by PCRE, since it can match only at the start of a subject
1444     string. However, if PCRE_DOTALL is not set, PCRE cannot make this optimization,
1445     because the . metacharacter does not then match a newline, and if the subject
1446     string contains newlines, the pattern may match from the character immediately
1447     following one of them instead of from the very start. For example, the pattern
1448    
1449     (.*) second
1450    
1451     matches the subject "first\\nand second" (where \\n stands for a newline
1452     character) with the first captured substring being "and". In order to do this,
1453     PCRE has to retry the match starting after every newline in the subject.
1454    
1455     If you are using such a pattern with subject strings that do not contain
1456     newlines, the best performance is obtained by setting PCRE_DOTALL, or starting
1457     the pattern with ^.* to indicate explicit anchoring. That saves PCRE from
1458     having to scan along the subject looking for a newline to restart at.
1459    
1460     Beware of patterns that contain nested indefinite repeats. These can take a
1461     long time to run when applied to a string that does not match. Consider the
1462     pattern fragment
1463    
1464     (a+)*
1465    
1466     This can match "aaaa" in 33 different ways, and this number increases very
1467     rapidly as the string gets longer. (The * repeat can match 0, 1, 2, 3, or 4
1468     times, and for each of those cases other than 0, the + repeats can match
1469     different numbers of times.) When the remainder of the pattern is such that the
1470     entire match is going to fail, PCRE has in principle to try every possible
1471     variation, and this can take an extremely long time.
1472    
1473     An optimization catches some of the more simple cases such as
1474    
1475     (a+)*b
1476    
1477     where a literal character follows. Before embarking on the standard matching
1478     procedure, PCRE checks that there is a "b" later in the subject string, and if
1479     there is not, it fails the match immediately. However, when there is no
1480     following literal this optimization cannot be used. You can see the difference
1481     by comparing the behaviour of
1482    
1483     (a+)*\\d
1484    
1485     with the pattern above. The former gives a failure almost instantly when
1486     applied to a whole line of "a" characters, whereas the latter takes an
1487     appreciable time with strings longer than about 20 characters.
1488    
1489     .SH AUTHOR
1490     Philip Hazel <ph10@cam.ac.uk>
1491     .br
1492     University Computing Service,
1493     .br
1494     New Museums Site,
1495     .br
1496     Cambridge CB2 3QG, England.
1497     .br
1498     Phone: +44 1223 334714
1499    
1500     Last updated: 29 July 1999
1501     .br
1502     Copyright (c) 1997-1999 University of Cambridge.

webmaster@exim.org
ViewVC Help
Powered by ViewVC 1.1.12