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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 53 - (show annotations) (download)
Sat Feb 24 21:39:42 2007 UTC (7 years, 9 months ago) by nigel
File size: 89461 byte(s)
Load pcre-3.5 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 void pcre_free_substring(const char *\fIstringptr\fR);
48 .PP
49 .br
50 .B void pcre_free_substring_list(const char **\fIstringptr\fR);
51 .PP
52 .br
53 .B const unsigned char *pcre_maketables(void);
54 .PP
55 .br
56 .B int pcre_fullinfo(const pcre *\fIcode\fR, "const pcre_extra *\fIextra\fR,"
57 .ti +5n
58 .B int \fIwhat\fR, void *\fIwhere\fR);
59 .PP
60 .br
61 .B int pcre_info(const pcre *\fIcode\fR, int *\fIoptptr\fR, int
62 .B *\fIfirstcharptr\fR);
63 .PP
64 .br
65 .B char *pcre_version(void);
66 .PP
67 .br
68 .B void *(*pcre_malloc)(size_t);
69 .PP
70 .br
71 .B void (*pcre_free)(void *);
72
73
74
75 .SH DESCRIPTION
76 The PCRE library is a set of functions that implement regular expression
77 pattern matching using the same syntax and semantics as Perl 5, with just a few
78 differences (see below). The current implementation corresponds to Perl 5.005,
79 with some additional features from later versions. This includes some
80 experimental, incomplete support for UTF-8 encoded strings. Details of exactly
81 what is and what is not supported are given below.
82
83 PCRE has its own native API, which is described in this document. There is also
84 a set of wrapper functions that correspond to the POSIX regular expression API.
85 These are described in the \fBpcreposix\fR documentation.
86
87 The native API function prototypes are defined in the header file \fBpcre.h\fR,
88 and on Unix systems the library itself is called \fBlibpcre.a\fR, so can be
89 accessed by adding \fB-lpcre\fR to the command for linking an application which
90 calls it. The header file defines the macros PCRE_MAJOR and PCRE_MINOR to
91 contain the major and minor release numbers for the library. Applications can
92 use these to include support for different releases.
93
94 The functions \fBpcre_compile()\fR, \fBpcre_study()\fR, and \fBpcre_exec()\fR
95 are used for compiling and matching regular expressions. A sample program that
96 demonstrates the simplest way of using them is given in the file
97 \fIpcredemo.c\fR. The last section of this man page describes how to run it.
98
99 The functions \fBpcre_copy_substring()\fR, \fBpcre_get_substring()\fR, and
100 \fBpcre_get_substring_list()\fR are convenience functions for extracting
101 captured substrings from a matched subject string; \fBpcre_free_substring()\fR
102 and \fBpcre_free_substring_list()\fR are also provided, to free the memory used
103 for extracted strings.
104
105 The function \fBpcre_maketables()\fR is used (optionally) to build a set of
106 character tables in the current locale for passing to \fBpcre_compile()\fR.
107
108 The function \fBpcre_fullinfo()\fR is used to find out information about a
109 compiled pattern; \fBpcre_info()\fR is an obsolete version which returns only
110 some of the available information, but is retained for backwards compatibility.
111 The function \fBpcre_version()\fR returns a pointer to a string containing the
112 version of PCRE and its date of release.
113
114 The global variables \fBpcre_malloc\fR and \fBpcre_free\fR initially contain
115 the entry points of the standard \fBmalloc()\fR and \fBfree()\fR functions
116 respectively. PCRE calls the memory management functions via these variables,
117 so a calling program can replace them if it wishes to intercept the calls. This
118 should be done before calling any PCRE functions.
119
120
121 .SH MULTI-THREADING
122 The PCRE functions can be used in multi-threading applications, with the
123 proviso that the memory management functions pointed to by \fBpcre_malloc\fR
124 and \fBpcre_free\fR are shared by all threads.
125
126 The compiled form of a regular expression is not altered during matching, so
127 the same compiled pattern can safely be used by several threads at once.
128
129
130 .SH COMPILING A PATTERN
131 The function \fBpcre_compile()\fR is called to compile a pattern into an
132 internal form. The pattern is a C string terminated by a binary zero, and
133 is passed in the argument \fIpattern\fR. A pointer to a single block of memory
134 that is obtained via \fBpcre_malloc\fR is returned. This contains the compiled
135 code and related data. The \fBpcre\fR type is defined for the returned block;
136 this is a typedef for a structure whose contents are not externally defined. It
137 is up to the caller to free the memory when it is no longer required.
138
139 Although the compiled code of a PCRE regex is relocatable, that is, it does not
140 depend on memory location, the complete \fBpcre\fR data block is not
141 fully relocatable, because it contains a copy of the \fItableptr\fR argument,
142 which is an address (see below).
143
144 The size of a compiled pattern is roughly proportional to the length of the
145 pattern string, except that each character class (other than those containing
146 just a single character, negated or not) requires 33 bytes, and repeat
147 quantifiers with a minimum greater than one or a bounded maximum cause the
148 relevant portions of the compiled pattern to be replicated.
149
150 The \fIoptions\fR argument contains independent bits that affect the
151 compilation. It should be zero if no options are required. Some of the options,
152 in particular, those that are compatible with Perl, can also be set and unset
153 from within the pattern (see the detailed description of regular expressions
154 below). For these options, the contents of the \fIoptions\fR argument specifies
155 their initial settings at the start of compilation and execution. The
156 PCRE_ANCHORED option can be set at the time of matching as well as at compile
157 time.
158
159 If \fIerrptr\fR is NULL, \fBpcre_compile()\fR returns NULL immediately.
160 Otherwise, if compilation of a pattern fails, \fBpcre_compile()\fR returns
161 NULL, and sets the variable pointed to by \fIerrptr\fR to point to a textual
162 error message. The offset from the start of the pattern to the character where
163 the error was discovered is placed in the variable pointed to by
164 \fIerroffset\fR, which must not be NULL. If it is, an immediate error is given.
165
166 If the final argument, \fItableptr\fR, is NULL, PCRE uses a default set of
167 character tables which are built when it is compiled, using the default C
168 locale. Otherwise, \fItableptr\fR must be the result of a call to
169 \fBpcre_maketables()\fR. See the section on locale support below.
170
171 This code fragment shows a typical straightforward call to \fBpcre_compile()\fR:
172
173 pcre *re;
174 const char *error;
175 int erroffset;
176 re = pcre_compile(
177 "^A.*Z", /* the pattern */
178 0, /* default options */
179 &error, /* for error message */
180 &erroffset, /* for error offset */
181 NULL); /* use default character tables */
182
183 The following option bits are defined in the header file:
184
185 PCRE_ANCHORED
186
187 If this bit is set, the pattern is forced to be "anchored", that is, it is
188 constrained to match only at the start of the string which is being searched
189 (the "subject string"). This effect can also be achieved by appropriate
190 constructs in the pattern itself, which is the only way to do it in Perl.
191
192 PCRE_CASELESS
193
194 If this bit is set, letters in the pattern match both upper and lower case
195 letters. It is equivalent to Perl's /i option.
196
197 PCRE_DOLLAR_ENDONLY
198
199 If this bit is set, a dollar metacharacter in the pattern matches only at the
200 end of the subject string. Without this option, a dollar also matches
201 immediately before the final character if it is a newline (but not before any
202 other newlines). The PCRE_DOLLAR_ENDONLY option is ignored if PCRE_MULTILINE is
203 set. There is no equivalent to this option in Perl.
204
205 PCRE_DOTALL
206
207 If this bit is set, a dot metacharater in the pattern matches all characters,
208 including newlines. Without it, newlines are excluded. This option is
209 equivalent to Perl's /s option. A negative class such as [^a] always matches a
210 newline character, independent of the setting of this option.
211
212 PCRE_EXTENDED
213
214 If this bit is set, whitespace data characters in the pattern are totally
215 ignored except when escaped or inside a character class, and characters between
216 an unescaped # outside a character class and the next newline character,
217 inclusive, are also ignored. This is equivalent to Perl's /x option, and makes
218 it possible to include comments inside complicated patterns. Note, however,
219 that this applies only to data characters. Whitespace characters may never
220 appear within special character sequences in a pattern, for example within the
221 sequence (?( which introduces a conditional subpattern.
222
223 PCRE_EXTRA
224
225 This option was invented in order to turn on additional functionality of PCRE
226 that is incompatible with Perl, but it is currently of very little use. When
227 set, any backslash in a pattern that is followed by a letter that has no
228 special meaning causes an error, thus reserving these combinations for future
229 expansion. By default, as in Perl, a backslash followed by a letter with no
230 special meaning is treated as a literal. There are at present no other features
231 controlled by this option. It can also be set by a (?X) option setting within a
232 pattern.
233
234 PCRE_MULTILINE
235
236 By default, PCRE treats the subject string as consisting of a single "line" of
237 characters (even if it actually contains several newlines). The "start of line"
238 metacharacter (^) matches only at the start of the string, while the "end of
239 line" metacharacter ($) matches only at the end of the string, or before a
240 terminating newline (unless PCRE_DOLLAR_ENDONLY is set). This is the same as
241 Perl.
242
243 When PCRE_MULTILINE it is set, the "start of line" and "end of line" constructs
244 match immediately following or immediately before any newline in the subject
245 string, respectively, as well as at the very start and end. This is equivalent
246 to Perl's /m option. If there are no "\\n" characters in a subject string, or
247 no occurrences of ^ or $ in a pattern, setting PCRE_MULTILINE has no
248 effect.
249
250 PCRE_UNGREEDY
251
252 This option inverts the "greediness" of the quantifiers so that they are not
253 greedy by default, but become greedy if followed by "?". It is not compatible
254 with Perl. It can also be set by a (?U) option setting within the pattern.
255
256 PCRE_UTF8
257
258 This option causes PCRE to regard both the pattern and the subject as strings
259 of UTF-8 characters instead of just byte strings. However, it is available only
260 if PCRE has been built to include UTF-8 support. If not, the use of this option
261 provokes an error. Support for UTF-8 is new, experimental, and incomplete.
262 Details of exactly what it entails are given below.
263
264
265 .SH STUDYING A PATTERN
266 When a pattern is going to be used several times, it is worth spending more
267 time analyzing it in order to speed up the time taken for matching. The
268 function \fBpcre_study()\fR takes a pointer to a compiled pattern as its first
269 argument, and returns a pointer to a \fBpcre_extra\fR block (another typedef
270 for a structure with hidden contents) containing additional information about
271 the pattern; this can be passed to \fBpcre_exec()\fR. If no additional
272 information is available, NULL is returned.
273
274 The second argument contains option bits. At present, no options are defined
275 for \fBpcre_study()\fR, and this argument should always be zero.
276
277 The third argument for \fBpcre_study()\fR is a pointer to an error message. If
278 studying succeeds (even if no data is returned), the variable it points to is
279 set to NULL. Otherwise it points to a textual error message.
280
281 This is a typical call to \fBpcre_study\fR():
282
283 pcre_extra *pe;
284 pe = pcre_study(
285 re, /* result of pcre_compile() */
286 0, /* no options exist */
287 &error); /* set to NULL or points to a message */
288
289 At present, studying a pattern is useful only for non-anchored patterns that do
290 not have a single fixed starting character. A bitmap of possible starting
291 characters is created.
292
293
294 .SH LOCALE SUPPORT
295 PCRE handles caseless matching, and determines whether characters are letters,
296 digits, or whatever, by reference to a set of tables. The library contains a
297 default set of tables which is created in the default C locale when PCRE is
298 compiled. This is used when the final argument of \fBpcre_compile()\fR is NULL,
299 and is sufficient for many applications.
300
301 An alternative set of tables can, however, be supplied. Such tables are built
302 by calling the \fBpcre_maketables()\fR function, which has no arguments, in the
303 relevant locale. The result can then be passed to \fBpcre_compile()\fR as often
304 as necessary. For example, to build and use tables that are appropriate for the
305 French locale (where accented characters with codes greater than 128 are
306 treated as letters), the following code could be used:
307
308 setlocale(LC_CTYPE, "fr");
309 tables = pcre_maketables();
310 re = pcre_compile(..., tables);
311
312 The tables are built in memory that is obtained via \fBpcre_malloc\fR. The
313 pointer that is passed to \fBpcre_compile\fR is saved with the compiled
314 pattern, and the same tables are used via this pointer by \fBpcre_study()\fR
315 and \fBpcre_exec()\fR. Thus for any single pattern, compilation, studying and
316 matching all happen in the same locale, but different patterns can be compiled
317 in different locales. It is the caller's responsibility to ensure that the
318 memory containing the tables remains available for as long as it is needed.
319
320
321 .SH INFORMATION ABOUT A PATTERN
322 The \fBpcre_fullinfo()\fR function returns information about a compiled
323 pattern. It replaces the obsolete \fBpcre_info()\fR function, which is
324 nevertheless retained for backwards compability (and is documented below).
325
326 The first argument for \fBpcre_fullinfo()\fR is a pointer to the compiled
327 pattern. The second argument is the result of \fBpcre_study()\fR, or NULL if
328 the pattern was not studied. The third argument specifies which piece of
329 information is required, while the fourth argument is a pointer to a variable
330 to receive the data. The yield of the function is zero for success, or one of
331 the following negative numbers:
332
333 PCRE_ERROR_NULL the argument \fIcode\fR was NULL
334 the argument \fIwhere\fR was NULL
335 PCRE_ERROR_BADMAGIC the "magic number" was not found
336 PCRE_ERROR_BADOPTION the value of \fIwhat\fR was invalid
337
338 Here is a typical call of \fBpcre_fullinfo()\fR, to obtain the length of the
339 compiled pattern:
340
341 int rc;
342 unsigned long int length;
343 rc = pcre_fullinfo(
344 re, /* result of pcre_compile() */
345 pe, /* result of pcre_study(), or NULL */
346 PCRE_INFO_SIZE, /* what is required */
347 &length); /* where to put the data */
348
349 The possible values for the third argument are defined in \fBpcre.h\fR, and are
350 as follows:
351
352 PCRE_INFO_OPTIONS
353
354 Return a copy of the options with which the pattern was compiled. The fourth
355 argument should point to an \fBunsigned long int\fR variable. These option bits
356 are those specified in the call to \fBpcre_compile()\fR, modified by any
357 top-level option settings within the pattern itself, and with the PCRE_ANCHORED
358 bit forcibly set if the form of the pattern implies that it can match only at
359 the start of a subject string.
360
361 PCRE_INFO_SIZE
362
363 Return the size of the compiled pattern, that is, the value that was passed as
364 the argument to \fBpcre_malloc()\fR when PCRE was getting memory in which to
365 place the compiled data. The fourth argument should point to a \fBsize_t\fR
366 variable.
367
368 PCRE_INFO_CAPTURECOUNT
369
370 Return the number of capturing subpatterns in the pattern. The fourth argument
371 should point to an \fbint\fR variable.
372
373 PCRE_INFO_BACKREFMAX
374
375 Return the number of the highest back reference in the pattern. The fourth
376 argument should point to an \fBint\fR variable. Zero is returned if there are
377 no back references.
378
379 PCRE_INFO_FIRSTCHAR
380
381 Return information about the first character of any matched string, for a
382 non-anchored pattern. If there is a fixed first character, e.g. from a pattern
383 such as (cat|cow|coyote), it is returned in the integer pointed to by
384 \fIwhere\fR. Otherwise, if either
385
386 (a) the pattern was compiled with the PCRE_MULTILINE option, and every branch
387 starts with "^", or
388
389 (b) every branch of the pattern starts with ".*" and PCRE_DOTALL is not set
390 (if it were set, the pattern would be anchored),
391
392 -1 is returned, indicating that the pattern matches only at the start of a
393 subject string or after any "\\n" within the string. Otherwise -2 is returned.
394 For anchored patterns, -2 is returned.
395
396 PCRE_INFO_FIRSTTABLE
397
398 If the pattern was studied, and this resulted in the construction of a 256-bit
399 table indicating a fixed set of characters for the first character in any
400 matching string, a pointer to the table is returned. Otherwise NULL is
401 returned. The fourth argument should point to an \fBunsigned char *\fR
402 variable.
403
404 PCRE_INFO_LASTLITERAL
405
406 For a non-anchored pattern, return the value of the rightmost literal character
407 which must exist in any matched string, other than at its start. The fourth
408 argument should point to an \fBint\fR variable. If there is no such character,
409 or if the pattern is anchored, -1 is returned. For example, for the pattern
410 /a\\d+z\\d+/ the returned value is 'z'.
411
412 The \fBpcre_info()\fR function is now obsolete because its interface is too
413 restrictive to return all the available data about a compiled pattern. New
414 programs should use \fBpcre_fullinfo()\fR instead. The yield of
415 \fBpcre_info()\fR is the number of capturing subpatterns, or one of the
416 following negative numbers:
417
418 PCRE_ERROR_NULL the argument \fIcode\fR was NULL
419 PCRE_ERROR_BADMAGIC the "magic number" was not found
420
421 If the \fIoptptr\fR argument is not NULL, a copy of the options with which the
422 pattern was compiled is placed in the integer it points to (see
423 PCRE_INFO_OPTIONS above).
424
425 If the pattern is not anchored and the \fIfirstcharptr\fR argument is not NULL,
426 it is used to pass back information about the first character of any matched
427 string (see PCRE_INFO_FIRSTCHAR above).
428
429
430 .SH MATCHING A PATTERN
431 The function \fBpcre_exec()\fR is called to match a subject string against a
432 pre-compiled pattern, which is passed in the \fIcode\fR argument. If the
433 pattern has been studied, the result of the study should be passed in the
434 \fIextra\fR argument. Otherwise this must be NULL.
435
436 Here is an example of a simple call to \fBpcre_exec()\fR:
437
438 int rc;
439 int ovector[30];
440 rc = pcre_exec(
441 re, /* result of pcre_compile() */
442 NULL, /* we didn't study the pattern */
443 "some string", /* the subject string */
444 11, /* the length of the subject string */
445 0, /* start at offset 0 in the subject */
446 0, /* default options */
447 ovector, /* vector for substring information */
448 30); /* number of elements in the vector */
449
450 The PCRE_ANCHORED option can be passed in the \fIoptions\fR argument, whose
451 unused bits must be zero. However, if a pattern was compiled with
452 PCRE_ANCHORED, or turned out to be anchored by virtue of its contents, it
453 cannot be made unachored at matching time.
454
455 There are also three further options that can be set only at matching time:
456
457 PCRE_NOTBOL
458
459 The first character of the string is not the beginning of a line, so the
460 circumflex metacharacter should not match before it. Setting this without
461 PCRE_MULTILINE (at compile time) causes circumflex never to match.
462
463 PCRE_NOTEOL
464
465 The end of the string is not the end of a line, so the dollar metacharacter
466 should not match it nor (except in multiline mode) a newline immediately before
467 it. Setting this without PCRE_MULTILINE (at compile time) causes dollar never
468 to match.
469
470 PCRE_NOTEMPTY
471
472 An empty string is not considered to be a valid match if this option is set. If
473 there are alternatives in the pattern, they are tried. If all the alternatives
474 match the empty string, the entire match fails. For example, if the pattern
475
476 a?b?
477
478 is applied to a string not beginning with "a" or "b", it matches the empty
479 string at the start of the subject. With PCRE_NOTEMPTY set, this match is not
480 valid, so PCRE searches further into the string for occurrences of "a" or "b".
481
482 Perl has no direct equivalent of PCRE_NOTEMPTY, but it does make a special case
483 of a pattern match of the empty string within its \fBsplit()\fR function, and
484 when using the /g modifier. It is possible to emulate Perl's behaviour after
485 matching a null string by first trying the match again at the same offset with
486 PCRE_NOTEMPTY set, and then if that fails by advancing the starting offset (see
487 below) and trying an ordinary match again.
488
489 The subject string is passed as a pointer in \fIsubject\fR, a length in
490 \fIlength\fR, and a starting offset in \fIstartoffset\fR. Unlike the pattern
491 string, the subject may contain binary zero characters. When the starting
492 offset is zero, the search for a match starts at the beginning of the subject,
493 and this is by far the most common case.
494
495 A non-zero starting offset is useful when searching for another match in the
496 same subject by calling \fBpcre_exec()\fR again after a previous success.
497 Setting \fIstartoffset\fR differs from just passing over a shortened string and
498 setting PCRE_NOTBOL in the case of a pattern that begins with any kind of
499 lookbehind. For example, consider the pattern
500
501 \\Biss\\B
502
503 which finds occurrences of "iss" in the middle of words. (\\B matches only if
504 the current position in the subject is not a word boundary.) When applied to
505 the string "Mississipi" the first call to \fBpcre_exec()\fR finds the first
506 occurrence. If \fBpcre_exec()\fR is called again with just the remainder of the
507 subject, namely "issipi", it does not match, because \\B is always false at the
508 start of the subject, which is deemed to be a word boundary. However, if
509 \fBpcre_exec()\fR is passed the entire string again, but with \fIstartoffset\fR
510 set to 4, it finds the second occurrence of "iss" because it is able to look
511 behind the starting point to discover that it is preceded by a letter.
512
513 If a non-zero starting offset is passed when the pattern is anchored, one
514 attempt to match at the given offset is tried. This can only succeed if the
515 pattern does not require the match to be at the start of the subject.
516
517 In general, a pattern matches a certain portion of the subject, and in
518 addition, further substrings from the subject may be picked out by parts of the
519 pattern. Following the usage in Jeffrey Friedl's book, this is called
520 "capturing" in what follows, and the phrase "capturing subpattern" is used for
521 a fragment of a pattern that picks out a substring. PCRE supports several other
522 kinds of parenthesized subpattern that do not cause substrings to be captured.
523
524 Captured substrings are returned to the caller via a vector of integer offsets
525 whose address is passed in \fIovector\fR. The number of elements in the vector
526 is passed in \fIovecsize\fR. The first two-thirds of the vector is used to pass
527 back captured substrings, each substring using a pair of integers. The
528 remaining third of the vector is used as workspace by \fBpcre_exec()\fR while
529 matching capturing subpatterns, and is not available for passing back
530 information. The length passed in \fIovecsize\fR should always be a multiple of
531 three. If it is not, it is rounded down.
532
533 When a match has been successful, information about captured substrings is
534 returned in pairs of integers, starting at the beginning of \fIovector\fR, and
535 continuing up to two-thirds of its length at the most. The first element of a
536 pair is set to the offset of the first character in a substring, and the second
537 is set to the offset of the first character after the end of a substring. The
538 first pair, \fIovector[0]\fR and \fIovector[1]\fR, identify the portion of the
539 subject string matched by the entire pattern. The next pair is used for the
540 first capturing subpattern, and so on. The value returned by \fBpcre_exec()\fR
541 is the number of pairs that have been set. If there are no capturing
542 subpatterns, the return value from a successful match is 1, indicating that
543 just the first pair of offsets has been set.
544
545 Some convenience functions are provided for extracting the captured substrings
546 as separate strings. These are described in the following section.
547
548 It is possible for an capturing subpattern number \fIn+1\fR to match some
549 part of the subject when subpattern \fIn\fR has not been used at all. For
550 example, if the string "abc" is matched against the pattern (a|(z))(bc)
551 subpatterns 1 and 3 are matched, but 2 is not. When this happens, both offset
552 values corresponding to the unused subpattern are set to -1.
553
554 If a capturing subpattern is matched repeatedly, it is the last portion of the
555 string that it matched that gets returned.
556
557 If the vector is too small to hold all the captured substrings, it is used as
558 far as possible (up to two-thirds of its length), and the function returns a
559 value of zero. In particular, if the substring offsets are not of interest,
560 \fBpcre_exec()\fR may be called with \fIovector\fR passed as NULL and
561 \fIovecsize\fR as zero. However, if the pattern contains back references and
562 the \fIovector\fR isn't big enough to remember the related substrings, PCRE has
563 to get additional memory for use during matching. Thus it is usually advisable
564 to supply an \fIovector\fR.
565
566 Note that \fBpcre_info()\fR can be used to find out how many capturing
567 subpatterns there are in a compiled pattern. The smallest size for
568 \fIovector\fR that will allow for \fIn\fR captured substrings in addition to
569 the offsets of the substring matched by the whole pattern is (\fIn\fR+1)*3.
570
571 If \fBpcre_exec()\fR fails, it returns a negative number. The following are
572 defined in the header file:
573
574 PCRE_ERROR_NOMATCH (-1)
575
576 The subject string did not match the pattern.
577
578 PCRE_ERROR_NULL (-2)
579
580 Either \fIcode\fR or \fIsubject\fR was passed as NULL, or \fIovector\fR was
581 NULL and \fIovecsize\fR was not zero.
582
583 PCRE_ERROR_BADOPTION (-3)
584
585 An unrecognized bit was set in the \fIoptions\fR argument.
586
587 PCRE_ERROR_BADMAGIC (-4)
588
589 PCRE stores a 4-byte "magic number" at the start of the compiled code, to catch
590 the case when it is passed a junk pointer. This is the error it gives when the
591 magic number isn't present.
592
593 PCRE_ERROR_UNKNOWN_NODE (-5)
594
595 While running the pattern match, an unknown item was encountered in the
596 compiled pattern. This error could be caused by a bug in PCRE or by overwriting
597 of the compiled pattern.
598
599 PCRE_ERROR_NOMEMORY (-6)
600
601 If a pattern contains back references, but the \fIovector\fR that is passed to
602 \fBpcre_exec()\fR is not big enough to remember the referenced substrings, PCRE
603 gets a block of memory at the start of matching to use for this purpose. If the
604 call via \fBpcre_malloc()\fR fails, this error is given. The memory is freed at
605 the end of matching.
606
607
608 .SH EXTRACTING CAPTURED SUBSTRINGS
609 Captured substrings can be accessed directly by using the offsets returned by
610 \fBpcre_exec()\fR in \fIovector\fR. For convenience, the functions
611 \fBpcre_copy_substring()\fR, \fBpcre_get_substring()\fR, and
612 \fBpcre_get_substring_list()\fR are provided for extracting captured substrings
613 as new, separate, zero-terminated strings. A substring that contains a binary
614 zero is correctly extracted and has a further zero added on the end, but the
615 result does not, of course, function as a C string.
616
617 The first three arguments are the same for all three functions: \fIsubject\fR
618 is the subject string which has just been successfully matched, \fIovector\fR
619 is a pointer to the vector of integer offsets that was passed to
620 \fBpcre_exec()\fR, and \fIstringcount\fR is the number of substrings that
621 were captured by the match, including the substring that matched the entire
622 regular expression. This is the value returned by \fBpcre_exec\fR if it
623 is greater than zero. If \fBpcre_exec()\fR returned zero, indicating that it
624 ran out of space in \fIovector\fR, the value passed as \fIstringcount\fR should
625 be the size of the vector divided by three.
626
627 The functions \fBpcre_copy_substring()\fR and \fBpcre_get_substring()\fR
628 extract a single substring, whose number is given as \fIstringnumber\fR. A
629 value of zero extracts the substring that matched the entire pattern, while
630 higher values extract the captured substrings. For \fBpcre_copy_substring()\fR,
631 the string is placed in \fIbuffer\fR, whose length is given by
632 \fIbuffersize\fR, while for \fBpcre_get_substring()\fR a new block of memory is
633 obtained via \fBpcre_malloc\fR, and its address is returned via
634 \fIstringptr\fR. The yield of the function is the length of the string, not
635 including the terminating zero, or one of
636
637 PCRE_ERROR_NOMEMORY (-6)
638
639 The buffer was too small for \fBpcre_copy_substring()\fR, or the attempt to get
640 memory failed for \fBpcre_get_substring()\fR.
641
642 PCRE_ERROR_NOSUBSTRING (-7)
643
644 There is no substring whose number is \fIstringnumber\fR.
645
646 The \fBpcre_get_substring_list()\fR function extracts all available substrings
647 and builds a list of pointers to them. All this is done in a single block of
648 memory which is obtained via \fBpcre_malloc\fR. The address of the memory block
649 is returned via \fIlistptr\fR, which is also the start of the list of string
650 pointers. The end of the list is marked by a NULL pointer. The yield of the
651 function is zero if all went well, or
652
653 PCRE_ERROR_NOMEMORY (-6)
654
655 if the attempt to get the memory block failed.
656
657 When any of these functions encounter a substring that is unset, which can
658 happen when capturing subpattern number \fIn+1\fR matches some part of the
659 subject, but subpattern \fIn\fR has not been used at all, they return an empty
660 string. This can be distinguished from a genuine zero-length substring by
661 inspecting the appropriate offset in \fIovector\fR, which is negative for unset
662 substrings.
663
664 The two convenience functions \fBpcre_free_substring()\fR and
665 \fBpcre_free_substring_list()\fR can be used to free the memory returned by
666 a previous call of \fBpcre_get_substring()\fR or
667 \fBpcre_get_substring_list()\fR, respectively. They do nothing more than call
668 the function pointed to by \fBpcre_free\fR, which of course could be called
669 directly from a C program. However, PCRE is used in some situations where it is
670 linked via a special interface to another programming language which cannot use
671 \fBpcre_free\fR directly; it is for these cases that the functions are
672 provided.
673
674
675 .SH LIMITATIONS
676 There are some size limitations in PCRE but it is hoped that they will never in
677 practice be relevant.
678 The maximum length of a compiled pattern is 65539 (sic) bytes.
679 All values in repeating quantifiers must be less than 65536.
680 There maximum number of capturing subpatterns is 65535.
681 There is no limit to the number of non-capturing subpatterns, but the maximum
682 depth of nesting of all kinds of parenthesized subpattern, including capturing
683 subpatterns, assertions, and other types of subpattern, is 200.
684
685 The maximum length of a subject string is the largest positive number that an
686 integer variable can hold. However, PCRE uses recursion to handle subpatterns
687 and indefinite repetition. This means that the available stack space may limit
688 the size of a subject string that can be processed by certain patterns.
689
690
691 .SH DIFFERENCES FROM PERL
692 The differences described here are with respect to Perl 5.005.
693
694 1. By default, a whitespace character is any character that the C library
695 function \fBisspace()\fR recognizes, though it is possible to compile PCRE with
696 alternative character type tables. Normally \fBisspace()\fR matches space,
697 formfeed, newline, carriage return, horizontal tab, and vertical tab. Perl 5
698 no longer includes vertical tab in its set of whitespace characters. The \\v
699 escape that was in the Perl documentation for a long time was never in fact
700 recognized. However, the character itself was treated as whitespace at least
701 up to 5.002. In 5.004 and 5.005 it does not match \\s.
702
703 2. PCRE does not allow repeat quantifiers on lookahead assertions. Perl permits
704 them, but they do not mean what you might think. For example, (?!a){3} does
705 not assert that the next three characters are not "a". It just asserts that the
706 next character is not "a" three times.
707
708 3. Capturing subpatterns that occur inside negative lookahead assertions are
709 counted, but their entries in the offsets vector are never set. Perl sets its
710 numerical variables from any such patterns that are matched before the
711 assertion fails to match something (thereby succeeding), but only if the
712 negative lookahead assertion contains just one branch.
713
714 4. Though binary zero characters are supported in the subject string, they are
715 not allowed in a pattern string because it is passed as a normal C string,
716 terminated by zero. The escape sequence "\\0" can be used in the pattern to
717 represent a binary zero.
718
719 5. The following Perl escape sequences are not supported: \\l, \\u, \\L, \\U,
720 \\E, \\Q. In fact these are implemented by Perl's general string-handling and
721 are not part of its pattern matching engine.
722
723 6. The Perl \\G assertion is not supported as it is not relevant to single
724 pattern matches.
725
726 7. Fairly obviously, PCRE does not support the (?{code}) and (?p{code})
727 constructions. However, there is some experimental support for recursive
728 patterns using the non-Perl item (?R).
729
730 8. There are at the time of writing some oddities in Perl 5.005_02 concerned
731 with the settings of captured strings when part of a pattern is repeated. For
732 example, matching "aba" against the pattern /^(a(b)?)+$/ sets $2 to the value
733 "b", but matching "aabbaa" against /^(aa(bb)?)+$/ leaves $2 unset. However, if
734 the pattern is changed to /^(aa(b(b))?)+$/ then $2 (and $3) are set.
735
736 In Perl 5.004 $2 is set in both cases, and that is also true of PCRE. If in the
737 future Perl changes to a consistent state that is different, PCRE may change to
738 follow.
739
740 9. Another as yet unresolved discrepancy is that in Perl 5.005_02 the pattern
741 /^(a)?(?(1)a|b)+$/ matches the string "a", whereas in PCRE it does not.
742 However, in both Perl and PCRE /^(a)?a/ matched against "a" leaves $1 unset.
743
744 10. PCRE provides some extensions to the Perl regular expression facilities:
745
746 (a) Although lookbehind assertions must match fixed length strings, each
747 alternative branch of a lookbehind assertion can match a different length of
748 string. Perl 5.005 requires them all to have the same length.
749
750 (b) If PCRE_DOLLAR_ENDONLY is set and PCRE_MULTILINE is not set, the $ meta-
751 character matches only at the very end of the string.
752
753 (c) If PCRE_EXTRA is set, a backslash followed by a letter with no special
754 meaning is faulted.
755
756 (d) If PCRE_UNGREEDY is set, the greediness of the repetition quantifiers is
757 inverted, that is, by default they are not greedy, but if followed by a
758 question mark they are.
759
760 (e) PCRE_ANCHORED can be used to force a pattern to be tried only at the start
761 of the subject.
762
763 (f) The PCRE_NOTBOL, PCRE_NOTEOL, and PCRE_NOTEMPTY options for
764 \fBpcre_exec()\fR have no Perl equivalents.
765
766 (g) The (?R) construct allows for recursive pattern matching (Perl 5.6 can do
767 this using the (?p{code}) construct, which PCRE cannot of course support.)
768
769
770 .SH REGULAR EXPRESSION DETAILS
771 The syntax and semantics of the regular expressions supported by PCRE are
772 described below. Regular expressions are also described in the Perl
773 documentation and in a number of other books, some of which have copious
774 examples. Jeffrey Friedl's "Mastering Regular Expressions", published by
775 O'Reilly (ISBN 1-56592-257), covers them in great detail.
776
777 The description here is intended as reference documentation. The basic
778 operation of PCRE is on strings of bytes. However, there is the beginnings of
779 some support for UTF-8 character strings. To use this support you must
780 configure PCRE to include it, and then call \fBpcre_compile()\fR with the
781 PCRE_UTF8 option. How this affects the pattern matching is described in the
782 final section of this document.
783
784 A regular expression is a pattern that is matched against a subject string from
785 left to right. Most characters stand for themselves in a pattern, and match the
786 corresponding characters in the subject. As a trivial example, the pattern
787
788 The quick brown fox
789
790 matches a portion of a subject string that is identical to itself. The power of
791 regular expressions comes from the ability to include alternatives and
792 repetitions in the pattern. These are encoded in the pattern by the use of
793 \fImeta-characters\fR, which do not stand for themselves but instead are
794 interpreted in some special way.
795
796 There are two different sets of meta-characters: those that are recognized
797 anywhere in the pattern except within square brackets, and those that are
798 recognized in square brackets. Outside square brackets, the meta-characters are
799 as follows:
800
801 \\ general escape character with several uses
802 ^ assert start of subject (or line, in multiline mode)
803 $ assert end of subject (or line, in multiline mode)
804 . match any character except newline (by default)
805 [ start character class definition
806 | start of alternative branch
807 ( start subpattern
808 ) end subpattern
809 ? extends the meaning of (
810 also 0 or 1 quantifier
811 also quantifier minimizer
812 * 0 or more quantifier
813 + 1 or more quantifier
814 { start min/max quantifier
815
816 Part of a pattern that is in square brackets is called a "character class". In
817 a character class the only meta-characters are:
818
819 \\ general escape character
820 ^ negate the class, but only if the first character
821 - indicates character range
822 ] terminates the character class
823
824 The following sections describe the use of each of the meta-characters.
825
826
827 .SH BACKSLASH
828 The backslash character has several uses. Firstly, if it is followed by a
829 non-alphameric character, it takes away any special meaning that character may
830 have. This use of backslash as an escape character applies both inside and
831 outside character classes.
832
833 For example, if you want to match a "*" character, you write "\\*" in the
834 pattern. This applies whether or not the following character would otherwise be
835 interpreted as a meta-character, so it is always safe to precede a
836 non-alphameric with "\\" to specify that it stands for itself. In particular,
837 if you want to match a backslash, you write "\\\\".
838
839 If a pattern is compiled with the PCRE_EXTENDED option, whitespace in the
840 pattern (other than in a character class) and characters between a "#" outside
841 a character class and the next newline character are ignored. An escaping
842 backslash can be used to include a whitespace or "#" character as part of the
843 pattern.
844
845 A second use of backslash provides a way of encoding non-printing characters
846 in patterns in a visible manner. There is no restriction on the appearance of
847 non-printing characters, apart from the binary zero that terminates a pattern,
848 but when a pattern is being prepared by text editing, it is usually easier to
849 use one of the following escape sequences than the binary character it
850 represents:
851
852 \\a alarm, that is, the BEL character (hex 07)
853 \\cx "control-x", where x is any character
854 \\e escape (hex 1B)
855 \\f formfeed (hex 0C)
856 \\n newline (hex 0A)
857 \\r carriage return (hex 0D)
858 \\t tab (hex 09)
859 \\xhh character with hex code hh
860 \\ddd character with octal code ddd, or backreference
861
862 The precise effect of "\\cx" is as follows: if "x" is a lower case letter, it
863 is converted to upper case. Then bit 6 of the character (hex 40) is inverted.
864 Thus "\\cz" becomes hex 1A, but "\\c{" becomes hex 3B, while "\\c;" becomes hex
865 7B.
866
867 After "\\x", up to two hexadecimal digits are read (letters can be in upper or
868 lower case).
869
870 After "\\0" up to two further octal digits are read. In both cases, if there
871 are fewer than two digits, just those that are present are used. Thus the
872 sequence "\\0\\x\\07" specifies two binary zeros followed by a BEL character.
873 Make sure you supply two digits after the initial zero if the character that
874 follows is itself an octal digit.
875
876 The handling of a backslash followed by a digit other than 0 is complicated.
877 Outside a character class, PCRE reads it and any following digits as a decimal
878 number. If the number is less than 10, or if there have been at least that many
879 previous capturing left parentheses in the expression, the entire sequence is
880 taken as a \fIback reference\fR. A description of how this works is given
881 later, following the discussion of parenthesized subpatterns.
882
883 Inside a character class, or if the decimal number is greater than 9 and there
884 have not been that many capturing subpatterns, PCRE re-reads up to three octal
885 digits following the backslash, and generates a single byte from the least
886 significant 8 bits of the value. Any subsequent digits stand for themselves.
887 For example:
888
889 \\040 is another way of writing a space
890 \\40 is the same, provided there are fewer than 40
891 previous capturing subpatterns
892 \\7 is always a back reference
893 \\11 might be a back reference, or another way of
894 writing a tab
895 \\011 is always a tab
896 \\0113 is a tab followed by the character "3"
897 \\113 is the character with octal code 113 (since there
898 can be no more than 99 back references)
899 \\377 is a byte consisting entirely of 1 bits
900 \\81 is either a back reference, or a binary zero
901 followed by the two characters "8" and "1"
902
903 Note that octal values of 100 or greater must not be introduced by a leading
904 zero, because no more than three octal digits are ever read.
905
906 All the sequences that define a single byte value can be used both inside and
907 outside character classes. In addition, inside a character class, the sequence
908 "\\b" is interpreted as the backspace character (hex 08). Outside a character
909 class it has a different meaning (see below).
910
911 The third use of backslash is for specifying generic character types:
912
913 \\d any decimal digit
914 \\D any character that is not a decimal digit
915 \\s any whitespace character
916 \\S any character that is not a whitespace character
917 \\w any "word" character
918 \\W any "non-word" character
919
920 Each pair of escape sequences partitions the complete set of characters into
921 two disjoint sets. Any given character matches one, and only one, of each pair.
922
923 A "word" character is any letter or digit or the underscore character, that is,
924 any character which can be part of a Perl "word". The definition of letters and
925 digits is controlled by PCRE's character tables, and may vary if locale-
926 specific matching is taking place (see "Locale support" above). For example, in
927 the "fr" (French) locale, some character codes greater than 128 are used for
928 accented letters, and these are matched by \\w.
929
930 These character type sequences can appear both inside and outside character
931 classes. They each match one character of the appropriate type. If the current
932 matching point is at the end of the subject string, all of them fail, since
933 there is no character to match.
934
935 The fourth use of backslash is for certain simple assertions. An assertion
936 specifies a condition that has to be met at a particular point in a match,
937 without consuming any characters from the subject string. The use of
938 subpatterns for more complicated assertions is described below. The backslashed
939 assertions are
940
941 \\b word boundary
942 \\B not a word boundary
943 \\A start of subject (independent of multiline mode)
944 \\Z end of subject or newline at end (independent of multiline mode)
945 \\z end of subject (independent of multiline mode)
946
947 These assertions may not appear in character classes (but note that "\\b" has a
948 different meaning, namely the backspace character, inside a character class).
949
950 A word boundary is a position in the subject string where the current character
951 and the previous character do not both match \\w or \\W (i.e. one matches
952 \\w and the other matches \\W), or the start or end of the string if the
953 first or last character matches \\w, respectively.
954
955 The \\A, \\Z, and \\z assertions differ from the traditional circumflex and
956 dollar (described below) in that they only ever match at the very start and end
957 of the subject string, whatever options are set. They are not affected by the
958 PCRE_NOTBOL or PCRE_NOTEOL options. If the \fIstartoffset\fR argument of
959 \fBpcre_exec()\fR is non-zero, \\A can never match. The difference between \\Z
960 and \\z is that \\Z matches before a newline that is the last character of the
961 string as well as at the end of the string, whereas \\z matches only at the
962 end.
963
964
965 .SH CIRCUMFLEX AND DOLLAR
966 Outside a character class, in the default matching mode, the circumflex
967 character is an assertion which is true only if the current matching point is
968 at the start of the subject string. If the \fIstartoffset\fR argument of
969 \fBpcre_exec()\fR is non-zero, circumflex can never match. Inside a character
970 class, circumflex has an entirely different meaning (see below).
971
972 Circumflex need not be the first character of the pattern if a number of
973 alternatives are involved, but it should be the first thing in each alternative
974 in which it appears if the pattern is ever to match that branch. If all
975 possible alternatives start with a circumflex, that is, if the pattern is
976 constrained to match only at the start of the subject, it is said to be an
977 "anchored" pattern. (There are also other constructs that can cause a pattern
978 to be anchored.)
979
980 A dollar character is an assertion which is true only if the current matching
981 point is at the end of the subject string, or immediately before a newline
982 character that is the last character in the string (by default). Dollar need
983 not be the last character of the pattern if a number of alternatives are
984 involved, but it should be the last item in any branch in which it appears.
985 Dollar has no special meaning in a character class.
986
987 The meaning of dollar can be changed so that it matches only at the very end of
988 the string, by setting the PCRE_DOLLAR_ENDONLY option at compile or matching
989 time. This does not affect the \\Z assertion.
990
991 The meanings of the circumflex and dollar characters are changed if the
992 PCRE_MULTILINE option is set. When this is the case, they match immediately
993 after and immediately before an internal "\\n" character, respectively, in
994 addition to matching at the start and end of the subject string. For example,
995 the pattern /^abc$/ matches the subject string "def\\nabc" in multiline mode,
996 but not otherwise. Consequently, patterns that are anchored in single line mode
997 because all branches start with "^" are not anchored in multiline mode, and a
998 match for circumflex is possible when the \fIstartoffset\fR argument of
999 \fBpcre_exec()\fR is non-zero. The PCRE_DOLLAR_ENDONLY option is ignored if
1000 PCRE_MULTILINE is set.
1001
1002 Note that the sequences \\A, \\Z, and \\z can be used to match the start and
1003 end of the subject in both modes, and if all branches of a pattern start with
1004 \\A it is always anchored, whether PCRE_MULTILINE is set or not.
1005
1006
1007 .SH FULL STOP (PERIOD, DOT)
1008 Outside a character class, a dot in the pattern matches any one character in
1009 the subject, including a non-printing character, but not (by default) newline.
1010 If the PCRE_DOTALL option is set, dots match newlines as well. The handling of
1011 dot is entirely independent of the handling of circumflex and dollar, the only
1012 relationship being that they both involve newline characters. Dot has no
1013 special meaning in a character class.
1014
1015
1016 .SH SQUARE BRACKETS
1017 An opening square bracket introduces a character class, terminated by a closing
1018 square bracket. A closing square bracket on its own is not special. If a
1019 closing square bracket is required as a member of the class, it should be the
1020 first data character in the class (after an initial circumflex, if present) or
1021 escaped with a backslash.
1022
1023 A character class matches a single character in the subject; the character must
1024 be in the set of characters defined by the class, unless the first character in
1025 the class is a circumflex, in which case the subject character must not be in
1026 the set defined by the class. If a circumflex is actually required as a member
1027 of the class, ensure it is not the first character, or escape it with a
1028 backslash.
1029
1030 For example, the character class [aeiou] matches any lower case vowel, while
1031 [^aeiou] matches any character that is not a lower case vowel. Note that a
1032 circumflex is just a convenient notation for specifying the characters which
1033 are in the class by enumerating those that are not. It is not an assertion: it
1034 still consumes a character from the subject string, and fails if the current
1035 pointer is at the end of the string.
1036
1037 When caseless matching is set, any letters in a class represent both their
1038 upper case and lower case versions, so for example, a caseless [aeiou] matches
1039 "A" as well as "a", and a caseless [^aeiou] does not match "A", whereas a
1040 caseful version would.
1041
1042 The newline character is never treated in any special way in character classes,
1043 whatever the setting of the PCRE_DOTALL or PCRE_MULTILINE options is. A class
1044 such as [^a] will always match a newline.
1045
1046 The minus (hyphen) character can be used to specify a range of characters in a
1047 character class. For example, [d-m] matches any letter between d and m,
1048 inclusive. If a minus character is required in a class, it must be escaped with
1049 a backslash or appear in a position where it cannot be interpreted as
1050 indicating a range, typically as the first or last character in the class.
1051
1052 It is not possible to have the literal character "]" as the end character of a
1053 range. A pattern such as [W-]46] is interpreted as a class of two characters
1054 ("W" and "-") followed by a literal string "46]", so it would match "W46]" or
1055 "-46]". However, if the "]" is escaped with a backslash it is interpreted as
1056 the end of range, so [W-\\]46] is interpreted as a single class containing a
1057 range followed by two separate characters. The octal or hexadecimal
1058 representation of "]" can also be used to end a range.
1059
1060 Ranges operate in ASCII collating sequence. They can also be used for
1061 characters specified numerically, for example [\\000-\\037]. If a range that
1062 includes letters is used when caseless matching is set, it matches the letters
1063 in either case. For example, [W-c] is equivalent to [][\\^_`wxyzabc], matched
1064 caselessly, and if character tables for the "fr" locale are in use,
1065 [\\xc8-\\xcb] matches accented E characters in both cases.
1066
1067 The character types \\d, \\D, \\s, \\S, \\w, and \\W may also appear in a
1068 character class, and add the characters that they match to the class. For
1069 example, [\\dABCDEF] matches any hexadecimal digit. A circumflex can
1070 conveniently be used with the upper case character types to specify a more
1071 restricted set of characters than the matching lower case type. For example,
1072 the class [^\\W_] matches any letter or digit, but not underscore.
1073
1074 All non-alphameric characters other than \\, -, ^ (at the start) and the
1075 terminating ] are non-special in character classes, but it does no harm if they
1076 are escaped.
1077
1078
1079 .SH POSIX CHARACTER CLASSES
1080 Perl 5.6 (not yet released at the time of writing) is going to support the
1081 POSIX notation for character classes, which uses names enclosed by [: and :]
1082 within the enclosing square brackets. PCRE supports this notation. For example,
1083
1084 [01[:alpha:]%]
1085
1086 matches "0", "1", any alphabetic character, or "%". The supported class names
1087 are
1088
1089 alnum letters and digits
1090 alpha letters
1091 ascii character codes 0 - 127
1092 cntrl control characters
1093 digit decimal digits (same as \\d)
1094 graph printing characters, excluding space
1095 lower lower case letters
1096 print printing characters, including space
1097 punct printing characters, excluding letters and digits
1098 space white space (same as \\s)
1099 upper upper case letters
1100 word "word" characters (same as \\w)
1101 xdigit hexadecimal digits
1102
1103 The names "ascii" and "word" are Perl extensions. Another Perl extension is
1104 negation, which is indicated by a ^ character after the colon. For example,
1105
1106 [12[:^digit:]]
1107
1108 matches "1", "2", or any non-digit. PCRE (and Perl) also recognize the POSIX
1109 syntax [.ch.] and [=ch=] where "ch" is a "collating element", but these are not
1110 supported, and an error is given if they are encountered.
1111
1112
1113 .SH VERTICAL BAR
1114 Vertical bar characters are used to separate alternative patterns. For example,
1115 the pattern
1116
1117 gilbert|sullivan
1118
1119 matches either "gilbert" or "sullivan". Any number of alternatives may appear,
1120 and an empty alternative is permitted (matching the empty string).
1121 The matching process tries each alternative in turn, from left to right,
1122 and the first one that succeeds is used. If the alternatives are within a
1123 subpattern (defined below), "succeeds" means matching the rest of the main
1124 pattern as well as the alternative in the subpattern.
1125
1126
1127 .SH INTERNAL OPTION SETTING
1128 The settings of PCRE_CASELESS, PCRE_MULTILINE, PCRE_DOTALL, and PCRE_EXTENDED
1129 can be changed from within the pattern by a sequence of Perl option letters
1130 enclosed between "(?" and ")". The option letters are
1131
1132 i for PCRE_CASELESS
1133 m for PCRE_MULTILINE
1134 s for PCRE_DOTALL
1135 x for PCRE_EXTENDED
1136
1137 For example, (?im) sets caseless, multiline matching. It is also possible to
1138 unset these options by preceding the letter with a hyphen, and a combined
1139 setting and unsetting such as (?im-sx), which sets PCRE_CASELESS and
1140 PCRE_MULTILINE while unsetting PCRE_DOTALL and PCRE_EXTENDED, is also
1141 permitted. If a letter appears both before and after the hyphen, the option is
1142 unset.
1143
1144 The scope of these option changes depends on where in the pattern the setting
1145 occurs. For settings that are outside any subpattern (defined below), the
1146 effect is the same as if the options were set or unset at the start of
1147 matching. The following patterns all behave in exactly the same way:
1148
1149 (?i)abc
1150 a(?i)bc
1151 ab(?i)c
1152 abc(?i)
1153
1154 which in turn is the same as compiling the pattern abc with PCRE_CASELESS set.
1155 In other words, such "top level" settings apply to the whole pattern (unless
1156 there are other changes inside subpatterns). If there is more than one setting
1157 of the same option at top level, the rightmost setting is used.
1158
1159 If an option change occurs inside a subpattern, the effect is different. This
1160 is a change of behaviour in Perl 5.005. An option change inside a subpattern
1161 affects only that part of the subpattern that follows it, so
1162
1163 (a(?i)b)c
1164
1165 matches abc and aBc and no other strings (assuming PCRE_CASELESS is not used).
1166 By this means, options can be made to have different settings in different
1167 parts of the pattern. Any changes made in one alternative do carry on
1168 into subsequent branches within the same subpattern. For example,
1169
1170 (a(?i)b|c)
1171
1172 matches "ab", "aB", "c", and "C", even though when matching "C" the first
1173 branch is abandoned before the option setting. This is because the effects of
1174 option settings happen at compile time. There would be some very weird
1175 behaviour otherwise.
1176
1177 The PCRE-specific options PCRE_UNGREEDY and PCRE_EXTRA can be changed in the
1178 same way as the Perl-compatible options by using the characters U and X
1179 respectively. The (?X) flag setting is special in that it must always occur
1180 earlier in the pattern than any of the additional features it turns on, even
1181 when it is at top level. It is best put at the start.
1182
1183
1184 .SH SUBPATTERNS
1185 Subpatterns are delimited by parentheses (round brackets), which can be nested.
1186 Marking part of a pattern as a subpattern does two things:
1187
1188 1. It localizes a set of alternatives. For example, the pattern
1189
1190 cat(aract|erpillar|)
1191
1192 matches one of the words "cat", "cataract", or "caterpillar". Without the
1193 parentheses, it would match "cataract", "erpillar" or the empty string.
1194
1195 2. It sets up the subpattern as a capturing subpattern (as defined above).
1196 When the whole pattern matches, that portion of the subject string that matched
1197 the subpattern is passed back to the caller via the \fIovector\fR argument of
1198 \fBpcre_exec()\fR. Opening parentheses are counted from left to right (starting
1199 from 1) to obtain the numbers of the capturing subpatterns.
1200
1201 For example, if the string "the red king" is matched against the pattern
1202
1203 the ((red|white) (king|queen))
1204
1205 the captured substrings are "red king", "red", and "king", and are numbered 1,
1206 2, and 3, respectively.
1207
1208 The fact that plain parentheses fulfil two functions is not always helpful.
1209 There are often times when a grouping subpattern is required without a
1210 capturing requirement. If an opening parenthesis is followed by "?:", the
1211 subpattern does not do any capturing, and is not counted when computing the
1212 number of any subsequent capturing subpatterns. For example, if the string "the
1213 white queen" is matched against the pattern
1214
1215 the ((?:red|white) (king|queen))
1216
1217 the captured substrings are "white queen" and "queen", and are numbered 1 and
1218 2. The maximum number of captured substrings is 99, and the maximum number of
1219 all subpatterns, both capturing and non-capturing, is 200.
1220
1221 As a convenient shorthand, if any option settings are required at the start of
1222 a non-capturing subpattern, the option letters may appear between the "?" and
1223 the ":". Thus the two patterns
1224
1225 (?i:saturday|sunday)
1226 (?:(?i)saturday|sunday)
1227
1228 match exactly the same set of strings. Because alternative branches are tried
1229 from left to right, and options are not reset until the end of the subpattern
1230 is reached, an option setting in one branch does affect subsequent branches, so
1231 the above patterns match "SUNDAY" as well as "Saturday".
1232
1233
1234 .SH REPETITION
1235 Repetition is specified by quantifiers, which can follow any of the following
1236 items:
1237
1238 a single character, possibly escaped
1239 the . metacharacter
1240 a character class
1241 a back reference (see next section)
1242 a parenthesized subpattern (unless it is an assertion - see below)
1243
1244 The general repetition quantifier specifies a minimum and maximum number of
1245 permitted matches, by giving the two numbers in curly brackets (braces),
1246 separated by a comma. The numbers must be less than 65536, and the first must
1247 be less than or equal to the second. For example:
1248
1249 z{2,4}
1250
1251 matches "zz", "zzz", or "zzzz". A closing brace on its own is not a special
1252 character. If the second number is omitted, but the comma is present, there is
1253 no upper limit; if the second number and the comma are both omitted, the
1254 quantifier specifies an exact number of required matches. Thus
1255
1256 [aeiou]{3,}
1257
1258 matches at least 3 successive vowels, but may match many more, while
1259
1260 \\d{8}
1261
1262 matches exactly 8 digits. An opening curly bracket that appears in a position
1263 where a quantifier is not allowed, or one that does not match the syntax of a
1264 quantifier, is taken as a literal character. For example, {,6} is not a
1265 quantifier, but a literal string of four characters.
1266
1267 The quantifier {0} is permitted, causing the expression to behave as if the
1268 previous item and the quantifier were not present.
1269
1270 For convenience (and historical compatibility) the three most common
1271 quantifiers have single-character abbreviations:
1272
1273 * is equivalent to {0,}
1274 + is equivalent to {1,}
1275 ? is equivalent to {0,1}
1276
1277 It is possible to construct infinite loops by following a subpattern that can
1278 match no characters with a quantifier that has no upper limit, for example:
1279
1280 (a?)*
1281
1282 Earlier versions of Perl and PCRE used to give an error at compile time for
1283 such patterns. However, because there are cases where this can be useful, such
1284 patterns are now accepted, but if any repetition of the subpattern does in fact
1285 match no characters, the loop is forcibly broken.
1286
1287 By default, the quantifiers are "greedy", that is, they match as much as
1288 possible (up to the maximum number of permitted times), without causing the
1289 rest of the pattern to fail. The classic example of where this gives problems
1290 is in trying to match comments in C programs. These appear between the
1291 sequences /* and */ and within the sequence, individual * and / characters may
1292 appear. An attempt to match C comments by applying the pattern
1293
1294 /\\*.*\\*/
1295
1296 to the string
1297
1298 /* first command */ not comment /* second comment */
1299
1300 fails, because it matches the entire string owing to the greediness of the .*
1301 item.
1302
1303 However, if a quantifier is followed by a question mark, it ceases to be
1304 greedy, and instead matches the minimum number of times possible, so the
1305 pattern
1306
1307 /\\*.*?\\*/
1308
1309 does the right thing with the C comments. The meaning of the various
1310 quantifiers is not otherwise changed, just the preferred number of matches.
1311 Do not confuse this use of question mark with its use as a quantifier in its
1312 own right. Because it has two uses, it can sometimes appear doubled, as in
1313
1314 \\d??\\d
1315
1316 which matches one digit by preference, but can match two if that is the only
1317 way the rest of the pattern matches.
1318
1319 If the PCRE_UNGREEDY option is set (an option which is not available in Perl),
1320 the quantifiers are not greedy by default, but individual ones can be made
1321 greedy by following them with a question mark. In other words, it inverts the
1322 default behaviour.
1323
1324 When a parenthesized subpattern is quantified with a minimum repeat count that
1325 is greater than 1 or with a limited maximum, more store is required for the
1326 compiled pattern, in proportion to the size of the minimum or maximum.
1327
1328 If a pattern starts with .* or .{0,} and the PCRE_DOTALL option (equivalent
1329 to Perl's /s) is set, thus allowing the . to match newlines, the pattern is
1330 implicitly anchored, because whatever follows will be tried against every
1331 character position in the subject string, so there is no point in retrying the
1332 overall match at any position after the first. PCRE treats such a pattern as
1333 though it were preceded by \\A. In cases where it is known that the subject
1334 string contains no newlines, it is worth setting PCRE_DOTALL when the pattern
1335 begins with .* in order to obtain this optimization, or alternatively using ^
1336 to indicate anchoring explicitly.
1337
1338 When a capturing subpattern is repeated, the value captured is the substring
1339 that matched the final iteration. For example, after
1340
1341 (tweedle[dume]{3}\\s*)+
1342
1343 has matched "tweedledum tweedledee" the value of the captured substring is
1344 "tweedledee". However, if there are nested capturing subpatterns, the
1345 corresponding captured values may have been set in previous iterations. For
1346 example, after
1347
1348 /(a|(b))+/
1349
1350 matches "aba" the value of the second captured substring is "b".
1351
1352
1353 .SH BACK REFERENCES
1354 Outside a character class, a backslash followed by a digit greater than 0 (and
1355 possibly further digits) is a back reference to a capturing subpattern earlier
1356 (i.e. to its left) in the pattern, provided there have been that many previous
1357 capturing left parentheses.
1358
1359 However, if the decimal number following the backslash is less than 10, it is
1360 always taken as a back reference, and causes an error only if there are not
1361 that many capturing left parentheses in the entire pattern. In other words, the
1362 parentheses that are referenced need not be to the left of the reference for
1363 numbers less than 10. See the section entitled "Backslash" above for further
1364 details of the handling of digits following a backslash.
1365
1366 A back reference matches whatever actually matched the capturing subpattern in
1367 the current subject string, rather than anything matching the subpattern
1368 itself. So the pattern
1369
1370 (sens|respons)e and \\1ibility
1371
1372 matches "sense and sensibility" and "response and responsibility", but not
1373 "sense and responsibility". If caseful matching is in force at the time of the
1374 back reference, the case of letters is relevant. For example,
1375
1376 ((?i)rah)\\s+\\1
1377
1378 matches "rah rah" and "RAH RAH", but not "RAH rah", even though the original
1379 capturing subpattern is matched caselessly.
1380
1381 There may be more than one back reference to the same subpattern. If a
1382 subpattern has not actually been used in a particular match, any back
1383 references to it always fail. For example, the pattern
1384
1385 (a|(bc))\\2
1386
1387 always fails if it starts to match "a" rather than "bc". Because there may be
1388 up to 99 back references, all digits following the backslash are taken
1389 as part of a potential back reference number. If the pattern continues with a
1390 digit character, some delimiter must be used to terminate the back reference.
1391 If the PCRE_EXTENDED option is set, this can be whitespace. Otherwise an empty
1392 comment can be used.
1393
1394 A back reference that occurs inside the parentheses to which it refers fails
1395 when the subpattern is first used, so, for example, (a\\1) never matches.
1396 However, such references can be useful inside repeated subpatterns. For
1397 example, the pattern
1398
1399 (a|b\\1)+
1400
1401 matches any number of "a"s and also "aba", "ababbaa" etc. At each iteration of
1402 the subpattern, the back reference matches the character string corresponding
1403 to the previous iteration. In order for this to work, the pattern must be such
1404 that the first iteration does not need to match the back reference. This can be
1405 done using alternation, as in the example above, or by a quantifier with a
1406 minimum of zero.
1407
1408
1409 .SH ASSERTIONS
1410 An assertion is a test on the characters following or preceding the current
1411 matching point that does not actually consume any characters. The simple
1412 assertions coded as \\b, \\B, \\A, \\Z, \\z, ^ and $ are described above. More
1413 complicated assertions are coded as subpatterns. There are two kinds: those
1414 that look ahead of the current position in the subject string, and those that
1415 look behind it.
1416
1417 An assertion subpattern is matched in the normal way, except that it does not
1418 cause the current matching position to be changed. Lookahead assertions start
1419 with (?= for positive assertions and (?! for negative assertions. For example,
1420
1421 \\w+(?=;)
1422
1423 matches a word followed by a semicolon, but does not include the semicolon in
1424 the match, and
1425
1426 foo(?!bar)
1427
1428 matches any occurrence of "foo" that is not followed by "bar". Note that the
1429 apparently similar pattern
1430
1431 (?!foo)bar
1432
1433 does not find an occurrence of "bar" that is preceded by something other than
1434 "foo"; it finds any occurrence of "bar" whatsoever, because the assertion
1435 (?!foo) is always true when the next three characters are "bar". A
1436 lookbehind assertion is needed to achieve this effect.
1437
1438 Lookbehind assertions start with (?<= for positive assertions and (?<! for
1439 negative assertions. For example,
1440
1441 (?<!foo)bar
1442
1443 does find an occurrence of "bar" that is not preceded by "foo". The contents of
1444 a lookbehind assertion are restricted such that all the strings it matches must
1445 have a fixed length. However, if there are several alternatives, they do not
1446 all have to have the same fixed length. Thus
1447
1448 (?<=bullock|donkey)
1449
1450 is permitted, but
1451
1452 (?<!dogs?|cats?)
1453
1454 causes an error at compile time. Branches that match different length strings
1455 are permitted only at the top level of a lookbehind assertion. This is an
1456 extension compared with Perl 5.005, which requires all branches to match the
1457 same length of string. An assertion such as
1458
1459 (?<=ab(c|de))
1460
1461 is not permitted, because its single top-level branch can match two different
1462 lengths, but it is acceptable if rewritten to use two top-level branches:
1463
1464 (?<=abc|abde)
1465
1466 The implementation of lookbehind assertions is, for each alternative, to
1467 temporarily move the current position back by the fixed width and then try to
1468 match. If there are insufficient characters before the current position, the
1469 match is deemed to fail. Lookbehinds in conjunction with once-only subpatterns
1470 can be particularly useful for matching at the ends of strings; an example is
1471 given at the end of the section on once-only subpatterns.
1472
1473 Several assertions (of any sort) may occur in succession. For example,
1474
1475 (?<=\\d{3})(?<!999)foo
1476
1477 matches "foo" preceded by three digits that are not "999". Notice that each of
1478 the assertions is applied independently at the same point in the subject
1479 string. First there is a check that the previous three characters are all
1480 digits, and then there is a check that the same three characters are not "999".
1481 This pattern does \fInot\fR match "foo" preceded by six characters, the first
1482 of which are digits and the last three of which are not "999". For example, it
1483 doesn't match "123abcfoo". A pattern to do that is
1484
1485 (?<=\\d{3}...)(?<!999)foo
1486
1487 This time the first assertion looks at the preceding six characters, checking
1488 that the first three are digits, and then the second assertion checks that the
1489 preceding three characters are not "999".
1490
1491 Assertions can be nested in any combination. For example,
1492
1493 (?<=(?<!foo)bar)baz
1494
1495 matches an occurrence of "baz" that is preceded by "bar" which in turn is not
1496 preceded by "foo", while
1497
1498 (?<=\\d{3}(?!999)...)foo
1499
1500 is another pattern which matches "foo" preceded by three digits and any three
1501 characters that are not "999".
1502
1503 Assertion subpatterns are not capturing subpatterns, and may not be repeated,
1504 because it makes no sense to assert the same thing several times. If any kind
1505 of assertion contains capturing subpatterns within it, these are counted for
1506 the purposes of numbering the capturing subpatterns in the whole pattern.
1507 However, substring capturing is carried out only for positive assertions,
1508 because it does not make sense for negative assertions.
1509
1510 Assertions count towards the maximum of 200 parenthesized subpatterns.
1511
1512
1513 .SH ONCE-ONLY SUBPATTERNS
1514 With both maximizing and minimizing repetition, failure of what follows
1515 normally causes the repeated item to be re-evaluated to see if a different
1516 number of repeats allows the rest of the pattern to match. Sometimes it is
1517 useful to prevent this, either to change the nature of the match, or to cause
1518 it fail earlier than it otherwise might, when the author of the pattern knows
1519 there is no point in carrying on.
1520
1521 Consider, for example, the pattern \\d+foo when applied to the subject line
1522
1523 123456bar
1524
1525 After matching all 6 digits and then failing to match "foo", the normal
1526 action of the matcher is to try again with only 5 digits matching the \\d+
1527 item, and then with 4, and so on, before ultimately failing. Once-only
1528 subpatterns provide the means for specifying that once a portion of the pattern
1529 has matched, it is not to be re-evaluated in this way, so the matcher would
1530 give up immediately on failing to match "foo" the first time. The notation is
1531 another kind of special parenthesis, starting with (?> as in this example:
1532
1533 (?>\\d+)bar
1534
1535 This kind of parenthesis "locks up" the part of the pattern it contains once
1536 it has matched, and a failure further into the pattern is prevented from
1537 backtracking into it. Backtracking past it to previous items, however, works as
1538 normal.
1539
1540 An alternative description is that a subpattern of this type matches the string
1541 of characters that an identical standalone pattern would match, if anchored at
1542 the current point in the subject string.
1543
1544 Once-only subpatterns are not capturing subpatterns. Simple cases such as the
1545 above example can be thought of as a maximizing repeat that must swallow
1546 everything it can. So, while both \\d+ and \\d+? are prepared to adjust the
1547 number of digits they match in order to make the rest of the pattern match,
1548 (?>\\d+) can only match an entire sequence of digits.
1549
1550 This construction can of course contain arbitrarily complicated subpatterns,
1551 and it can be nested.
1552
1553 Once-only subpatterns can be used in conjunction with lookbehind assertions to
1554 specify efficient matching at the end of the subject string. Consider a simple
1555 pattern such as
1556
1557 abcd$
1558
1559 when applied to a long string which does not match. Because matching proceeds
1560 from left to right, PCRE will look for each "a" in the subject and then see if
1561 what follows matches the rest of the pattern. If the pattern is specified as
1562
1563 ^.*abcd$
1564
1565 the initial .* matches the entire string at first, but when this fails (because
1566 there is no following "a"), it backtracks to match all but the last character,
1567 then all but the last two characters, and so on. Once again the search for "a"
1568 covers the entire string, from right to left, so we are no better off. However,
1569 if the pattern is written as
1570
1571 ^(?>.*)(?<=abcd)
1572
1573 there can be no backtracking for the .* item; it can match only the entire
1574 string. The subsequent lookbehind assertion does a single test on the last four
1575 characters. If it fails, the match fails immediately. For long strings, this
1576 approach makes a significant difference to the processing time.
1577
1578 When a pattern contains an unlimited repeat inside a subpattern that can itself
1579 be repeated an unlimited number of times, the use of a once-only subpattern is
1580 the only way to avoid some failing matches taking a very long time indeed.
1581 The pattern
1582
1583 (\\D+|<\\d+>)*[!?]
1584
1585 matches an unlimited number of substrings that either consist of non-digits, or
1586 digits enclosed in <>, followed by either ! or ?. When it matches, it runs
1587 quickly. However, if it is applied to
1588
1589 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
1590
1591 it takes a long time before reporting failure. This is because the string can
1592 be divided between the two repeats in a large number of ways, and all have to
1593 be tried. (The example used [!?] rather than a single character at the end,
1594 because both PCRE and Perl have an optimization that allows for fast failure
1595 when a single character is used. They remember the last single character that
1596 is required for a match, and fail early if it is not present in the string.)
1597 If the pattern is changed to
1598
1599 ((?>\\D+)|<\\d+>)*[!?]
1600
1601 sequences of non-digits cannot be broken, and failure happens quickly.
1602
1603
1604 .SH CONDITIONAL SUBPATTERNS
1605 It is possible to cause the matching process to obey a subpattern
1606 conditionally or to choose between two alternative subpatterns, depending on
1607 the result of an assertion, or whether a previous capturing subpattern matched
1608 or not. The two possible forms of conditional subpattern are
1609
1610 (?(condition)yes-pattern)
1611 (?(condition)yes-pattern|no-pattern)
1612
1613 If the condition is satisfied, the yes-pattern is used; otherwise the
1614 no-pattern (if present) is used. If there are more than two alternatives in the
1615 subpattern, a compile-time error occurs.
1616
1617 There are two kinds of condition. If the text between the parentheses consists
1618 of a sequence of digits, the condition is satisfied if the capturing subpattern
1619 of that number has previously matched. The number must be greater than zero.
1620 Consider the following pattern, which contains non-significant white space to
1621 make it more readable (assume the PCRE_EXTENDED option) and to divide it into
1622 three parts for ease of discussion:
1623
1624 ( \\( )? [^()]+ (?(1) \\) )
1625
1626 The first part matches an optional opening parenthesis, and if that
1627 character is present, sets it as the first captured substring. The second part
1628 matches one or more characters that are not parentheses. The third part is a
1629 conditional subpattern that tests whether the first set of parentheses matched
1630 or not. If they did, that is, if subject started with an opening parenthesis,
1631 the condition is true, and so the yes-pattern is executed and a closing
1632 parenthesis is required. Otherwise, since no-pattern is not present, the
1633 subpattern matches nothing. In other words, this pattern matches a sequence of
1634 non-parentheses, optionally enclosed in parentheses.
1635
1636 If the condition is not a sequence of digits, it must be an assertion. This may
1637 be a positive or negative lookahead or lookbehind assertion. Consider this
1638 pattern, again containing non-significant white space, and with the two
1639 alternatives on the second line:
1640
1641 (?(?=[^a-z]*[a-z])
1642 \\d{2}-[a-z]{3}-\\d{2} | \\d{2}-\\d{2}-\\d{2} )
1643
1644 The condition is a positive lookahead assertion that matches an optional
1645 sequence of non-letters followed by a letter. In other words, it tests for the
1646 presence of at least one letter in the subject. If a letter is found, the
1647 subject is matched against the first alternative; otherwise it is matched
1648 against the second. This pattern matches strings in one of the two forms
1649 dd-aaa-dd or dd-dd-dd, where aaa are letters and dd are digits.
1650
1651
1652 .SH COMMENTS
1653 The sequence (?# marks the start of a comment which continues up to the next
1654 closing parenthesis. Nested parentheses are not permitted. The characters
1655 that make up a comment play no part in the pattern matching at all.
1656
1657 If the PCRE_EXTENDED option is set, an unescaped # character outside a
1658 character class introduces a comment that continues up to the next newline
1659 character in the pattern.
1660
1661
1662 .SH RECURSIVE PATTERNS
1663 Consider the problem of matching a string in parentheses, allowing for
1664 unlimited nested parentheses. Without the use of recursion, the best that can
1665 be done is to use a pattern that matches up to some fixed depth of nesting. It
1666 is not possible to handle an arbitrary nesting depth. Perl 5.6 has provided an
1667 experimental facility that allows regular expressions to recurse (amongst other
1668 things). It does this by interpolating Perl code in the expression at run time,
1669 and the code can refer to the expression itself. A Perl pattern to solve the
1670 parentheses problem can be created like this:
1671
1672 $re = qr{\\( (?: (?>[^()]+) | (?p{$re}) )* \\)}x;
1673
1674 The (?p{...}) item interpolates Perl code at run time, and in this case refers
1675 recursively to the pattern in which it appears. Obviously, PCRE cannot support
1676 the interpolation of Perl code. Instead, the special item (?R) is provided for
1677 the specific case of recursion. This PCRE pattern solves the parentheses
1678 problem (assume the PCRE_EXTENDED option is set so that white space is
1679 ignored):
1680
1681 \\( ( (?>[^()]+) | (?R) )* \\)
1682
1683 First it matches an opening parenthesis. Then it matches any number of
1684 substrings which can either be a sequence of non-parentheses, or a recursive
1685 match of the pattern itself (i.e. a correctly parenthesized substring). Finally
1686 there is a closing parenthesis.
1687
1688 This particular example pattern contains nested unlimited repeats, and so the
1689 use of a once-only subpattern for matching strings of non-parentheses is
1690 important when applying the pattern to strings that do not match. For example,
1691 when it is applied to
1692
1693 (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()
1694
1695 it yields "no match" quickly. However, if a once-only subpattern is not used,
1696 the match runs for a very long time indeed because there are so many different
1697 ways the + and * repeats can carve up the subject, and all have to be tested
1698 before failure can be reported.
1699
1700 The values set for any capturing subpatterns are those from the outermost level
1701 of the recursion at which the subpattern value is set. If the pattern above is
1702 matched against
1703
1704 (ab(cd)ef)
1705
1706 the value for the capturing parentheses is "ef", which is the last value taken
1707 on at the top level. If additional parentheses are added, giving
1708
1709 \\( ( ( (?>[^()]+) | (?R) )* ) \\)
1710 ^ ^
1711 ^ ^
1712 the string they capture is "ab(cd)ef", the contents of the top level
1713 parentheses. If there are more than 15 capturing parentheses in a pattern, PCRE
1714 has to obtain extra memory to store data during a recursion, which it does by
1715 using \fBpcre_malloc\fR, freeing it via \fBpcre_free\fR afterwards. If no
1716 memory can be obtained, it saves data for the first 15 capturing parentheses
1717 only, as there is no way to give an out-of-memory error from within a
1718 recursion.
1719
1720
1721 .SH PERFORMANCE
1722 Certain items that may appear in patterns are more efficient than others. It is
1723 more efficient to use a character class like [aeiou] than a set of alternatives
1724 such as (a|e|i|o|u). In general, the simplest construction that provides the
1725 required behaviour is usually the most efficient. Jeffrey Friedl's book
1726 contains a lot of discussion about optimizing regular expressions for efficient
1727 performance.
1728
1729 When a pattern begins with .* and the PCRE_DOTALL option is set, the pattern is
1730 implicitly anchored by PCRE, since it can match only at the start of a subject
1731 string. However, if PCRE_DOTALL is not set, PCRE cannot make this optimization,
1732 because the . metacharacter does not then match a newline, and if the subject
1733 string contains newlines, the pattern may match from the character immediately
1734 following one of them instead of from the very start. For example, the pattern
1735
1736 (.*) second
1737
1738 matches the subject "first\\nand second" (where \\n stands for a newline
1739 character) with the first captured substring being "and". In order to do this,
1740 PCRE has to retry the match starting after every newline in the subject.
1741
1742 If you are using such a pattern with subject strings that do not contain
1743 newlines, the best performance is obtained by setting PCRE_DOTALL, or starting
1744 the pattern with ^.* to indicate explicit anchoring. That saves PCRE from
1745 having to scan along the subject looking for a newline to restart at.
1746
1747 Beware of patterns that contain nested indefinite repeats. These can take a
1748 long time to run when applied to a string that does not match. Consider the
1749 pattern fragment
1750
1751 (a+)*
1752
1753 This can match "aaaa" in 33 different ways, and this number increases very
1754 rapidly as the string gets longer. (The * repeat can match 0, 1, 2, 3, or 4
1755 times, and for each of those cases other than 0, the + repeats can match
1756 different numbers of times.) When the remainder of the pattern is such that the
1757 entire match is going to fail, PCRE has in principle to try every possible
1758 variation, and this can take an extremely long time.
1759
1760 An optimization catches some of the more simple cases such as
1761
1762 (a+)*b
1763
1764 where a literal character follows. Before embarking on the standard matching
1765 procedure, PCRE checks that there is a "b" later in the subject string, and if
1766 there is not, it fails the match immediately. However, when there is no
1767 following literal this optimization cannot be used. You can see the difference
1768 by comparing the behaviour of
1769
1770 (a+)*\\d
1771
1772 with the pattern above. The former gives a failure almost instantly when
1773 applied to a whole line of "a" characters, whereas the latter takes an
1774 appreciable time with strings longer than about 20 characters.
1775
1776
1777 .SH UTF-8 SUPPORT
1778 Starting at release 3.3, PCRE has some support for character strings encoded
1779 in the UTF-8 format. This is incomplete, and is regarded as experimental. In
1780 order to use it, you must configure PCRE to include UTF-8 support in the code,
1781 and, in addition, you must call \fBpcre_compile()\fR with the PCRE_UTF8 option
1782 flag. When you do this, both the pattern and any subject strings that are
1783 matched against it are treated as UTF-8 strings instead of just strings of
1784 bytes, but only in the cases that are mentioned below.
1785
1786 If you compile PCRE with UTF-8 support, but do not use it at run time, the
1787 library will be a bit bigger, but the additional run time overhead is limited
1788 to testing the PCRE_UTF8 flag in several places, so should not be very large.
1789
1790 PCRE assumes that the strings it is given contain valid UTF-8 codes. It does
1791 not diagnose invalid UTF-8 strings. If you pass invalid UTF-8 strings to PCRE,
1792 the results are undefined.
1793
1794 Running with PCRE_UTF8 set causes these changes in the way PCRE works:
1795
1796 1. In a pattern, the escape sequence \\x{...}, where the contents of the braces
1797 is a string of hexadecimal digits, is interpreted as a UTF-8 character whose
1798 code number is the given hexadecimal number, for example: \\x{1234}. This
1799 inserts from one to six literal bytes into the pattern, using the UTF-8
1800 encoding. If a non-hexadecimal digit appears between the braces, the item is
1801 not recognized.
1802
1803 2. The original hexadecimal escape sequence, \\xhh, generates a two-byte UTF-8
1804 character if its value is greater than 127.
1805
1806 3. Repeat quantifiers are NOT correctly handled if they follow a multibyte
1807 character. For example, \\x{100}* and \\xc3+ do not work. If you want to
1808 repeat such characters, you must enclose them in non-capturing parentheses,
1809 for example (?:\\x{100}), at present.
1810
1811 4. The dot metacharacter matches one UTF-8 character instead of a single byte.
1812
1813 5. Unlike literal UTF-8 characters, the dot metacharacter followed by a
1814 repeat quantifier does operate correctly on UTF-8 characters instead of
1815 single bytes.
1816
1817 4. Although the \\x{...} escape is permitted in a character class, characters
1818 whose values are greater than 255 cannot be included in a class.
1819
1820 5. A class is matched against a UTF-8 character instead of just a single byte,
1821 but it can match only characters whose values are less than 256. Characters
1822 with greater values always fail to match a class.
1823
1824 6. Repeated classes work correctly on multiple characters.
1825
1826 7. Classes containing just a single character whose value is greater than 127
1827 (but less than 256), for example, [\\x80] or [^\\x{93}], do not work because
1828 these are optimized into single byte matches. In the first case, of course,
1829 the class brackets are just redundant.
1830
1831 8. Lookbehind assertions move backwards in the subject by a fixed number of
1832 characters instead of a fixed number of bytes. Simple cases have been tested
1833 to work correctly, but there may be hidden gotchas herein.
1834
1835 9. The character types such as \\d and \\w do not work correctly with UTF-8
1836 characters. They continue to test a single byte.
1837
1838 10. Anything not explicitly mentioned here continues to work in bytes rather
1839 than in characters.
1840
1841 The following UTF-8 features of Perl 5.6 are not implemented:
1842
1843 1. The escape sequence \\C to match a single byte.
1844
1845 2. The use of Unicode tables and properties and escapes \\p, \\P, and \\X.
1846
1847
1848 .SH SAMPLE PROGRAM
1849 The code below is a simple, complete demonstration program, to get you started
1850 with using PCRE. This code is also supplied in the file \fIpcredemo.c\fR in the
1851 PCRE distribution.
1852
1853 The program compiles the regular expression that is its first argument, and
1854 matches it against the subject string in its second argument. No options are
1855 set, and default character tables are used. If matching succeeds, the program
1856 outputs the portion of the subject that matched, together with the contents of
1857 any captured substrings.
1858
1859 On a Unix system that has PCRE installed in \fI/usr/local\fR, you can compile
1860 the demonstration program using a command like this:
1861
1862 gcc -o pcredemo pcredemo.c -I/usr/local/include -L/usr/local/lib -lpcre
1863
1864 Then you can run simple tests like this:
1865
1866 ./pcredemo 'cat|dog' 'the cat sat on the mat'
1867
1868 Note that there is a much more comprehensive test program, called
1869 \fBpcretest\fR, which supports many more facilities for testing regular
1870 expressions. The \fBpcredemo\fR program is provided as a simple coding example.
1871
1872 On some operating systems (e.g. Solaris) you may get an error like this when
1873 you try to run \fBpcredemo\fR:
1874
1875 ld.so.1: a.out: fatal: libpcre.so.0: open failed: No such file or directory
1876
1877 This is caused by the way shared library support works on those systems. You
1878 need to add
1879
1880 -R/usr/local/lib
1881
1882 to the compile command to get round this problem. Here's the code:
1883
1884 #include <stdio.h>
1885 #include <string.h>
1886 #include <pcre.h>
1887
1888 #define OVECCOUNT 30 /* should be a multiple of 3 */
1889
1890 int main(int argc, char **argv)
1891 {
1892 pcre *re;
1893 const char *error;
1894 int erroffset;
1895 int ovector[OVECCOUNT];
1896 int rc, i;
1897
1898 if (argc != 3)
1899 {
1900 printf("Two arguments required: a regex and a "
1901 "subject string\\n");
1902 return 1;
1903 }
1904
1905 /* Compile the regular expression in the first argument */
1906
1907 re = pcre_compile(
1908 argv[1], /* the pattern */
1909 0, /* default options */
1910 &error, /* for error message */
1911 &erroffset, /* for error offset */
1912 NULL); /* use default character tables */
1913
1914 /* Compilation failed: print the error message and exit */
1915
1916 if (re == NULL)
1917 {
1918 printf("PCRE compilation failed at offset %d: %s\\n",
1919 erroffset, error);
1920 return 1;
1921 }
1922
1923 /* Compilation succeeded: match the subject in the second
1924 argument */
1925
1926 rc = pcre_exec(
1927 re, /* the compiled pattern */
1928 NULL, /* we didn't study the pattern */
1929 argv[2], /* the subject string */
1930 (int)strlen(argv[2]), /* the length of the subject */
1931 0, /* start at offset 0 in the subject */
1932 0, /* default options */
1933 ovector, /* vector for substring information */
1934 OVECCOUNT); /* number of elements in the vector */
1935
1936 /* Matching failed: handle error cases */
1937
1938 if (rc < 0)
1939 {
1940 switch(rc)
1941 {
1942 case PCRE_ERROR_NOMATCH: printf("No match\\n"); break;
1943 /*
1944 Handle other special cases if you like
1945 */
1946 default: printf("Matching error %d\\n", rc); break;
1947 }
1948 return 1;
1949 }
1950
1951 /* Match succeded */
1952
1953 printf("Match succeeded\\n");
1954
1955 /* The output vector wasn't big enough */
1956
1957 if (rc == 0)
1958 {
1959 rc = OVECCOUNT/3;
1960 printf("ovector only has room for %d captured "
1961 substrings\\n", rc - 1);
1962 }
1963
1964 /* Show substrings stored in the output vector */
1965
1966 for (i = 0; i < rc; i++)
1967 {
1968 char *substring_start = argv[2] + ovector[2*i];
1969 int substring_length = ovector[2*i+1] - ovector[2*i];
1970 printf("%2d: %.*s\\n", i, substring_length,
1971 substring_start);
1972 }
1973
1974 return 0;
1975 }
1976
1977
1978 .SH AUTHOR
1979 Philip Hazel <ph10@cam.ac.uk>
1980 .br
1981 University Computing Service,
1982 .br
1983 New Museums Site,
1984 .br
1985 Cambridge CB2 3QG, England.
1986 .br
1987 Phone: +44 1223 334714
1988
1989 Last updated: 15 August 2001
1990 .br
1991 Copyright (c) 1997-2001 University of Cambridge.

webmaster@exim.org
ViewVC Help
Powered by ViewVC 1.1.12