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

Contents of /code/trunk/pcre.3

Parent Directory Parent Directory | Revision Log Revision Log


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

  ViewVC Help
Powered by ViewVC 1.1.5