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

Contents of /code/trunk/pcre.3

Parent Directory Parent Directory | Revision Log Revision Log


Revision 39 - (show annotations) (download)
Sat Feb 24 21:39:13 2007 UTC (7 years, 1 month ago) by nigel
File size: 69617 byte(s)
Load pcre-2.08 into code/trunk.

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

webmaster@exim.org
ViewVC Help
Powered by ViewVC 1.1.12