3 pcre - Perl-compatible regular expressions.
\r
9 .B pcre *pcre_compile(const char *\fIpattern\fR, int \fIoptions\fR,
\r
11 .B const char **\fIerrptr\fR, int *\fIerroffset\fR,
\r
13 .B const unsigned char *\fItableptr\fR);
\r
16 .B pcre_extra *pcre_study(const pcre *\fIcode\fR, int \fIoptions\fR,
\r
18 .B const char **\fIerrptr\fR);
\r
21 .B int pcre_exec(const pcre *\fIcode\fR, "const pcre_extra *\fIextra\fR,"
\r
23 .B "const char *\fIsubject\fR," int \fIlength\fR, int \fIstartoffset\fR,
\r
25 .B int \fIoptions\fR, int *\fIovector\fR, int \fIovecsize\fR);
\r
28 .B int pcre_copy_substring(const char *\fIsubject\fR, int *\fIovector\fR,
\r
30 .B int \fIstringcount\fR, int \fIstringnumber\fR, char *\fIbuffer\fR,
\r
32 .B int \fIbuffersize\fR);
\r
35 .B int pcre_get_substring(const char *\fIsubject\fR, int *\fIovector\fR,
\r
37 .B int \fIstringcount\fR, int \fIstringnumber\fR,
\r
39 .B const char **\fIstringptr\fR);
\r
42 .B int pcre_get_substring_list(const char *\fIsubject\fR,
\r
44 .B int *\fIovector\fR, int \fIstringcount\fR, "const char ***\fIlistptr\fR);"
\r
47 .B void pcre_free_substring(const char *\fIstringptr\fR);
\r
50 .B void pcre_free_substring_list(const char **\fIstringptr\fR);
\r
53 .B const unsigned char *pcre_maketables(void);
\r
56 .B int pcre_fullinfo(const pcre *\fIcode\fR, "const pcre_extra *\fIextra\fR,"
\r
58 .B int \fIwhat\fR, void *\fIwhere\fR);
\r
61 .B int pcre_info(const pcre *\fIcode\fR, int *\fIoptptr\fR, int
\r
62 .B *\fIfirstcharptr\fR);
\r
65 .B char *pcre_version(void);
\r
68 .B void *(*pcre_malloc)(size_t);
\r
71 .B void (*pcre_free)(void *);
\r
76 The PCRE library is a set of functions that implement regular expression
\r
77 pattern matching using the same syntax and semantics as Perl 5, with just a few
\r
78 differences (see below). The current implementation corresponds to Perl 5.005,
\r
79 with some additional features from later versions. This includes some
\r
80 experimental, incomplete support for UTF-8 encoded strings. Details of exactly
\r
81 what is and what is not supported are given below.
\r
83 PCRE has its own native API, which is described in this document. There is also
\r
84 a set of wrapper functions that correspond to the POSIX regular expression API.
\r
85 These are described in the \fBpcreposix\fR documentation.
\r
87 The native API function prototypes are defined in the header file \fBpcre.h\fR,
\r
88 and on Unix systems the library itself is called \fBlibpcre.a\fR, so can be
\r
89 accessed by adding \fB-lpcre\fR to the command for linking an application which
\r
90 calls it. The header file defines the macros PCRE_MAJOR and PCRE_MINOR to
\r
91 contain the major and minor release numbers for the library. Applications can
\r
92 use these to include support for different releases.
\r
94 The functions \fBpcre_compile()\fR, \fBpcre_study()\fR, and \fBpcre_exec()\fR
\r
95 are used for compiling and matching regular expressions.
\r
97 The functions \fBpcre_copy_substring()\fR, \fBpcre_get_substring()\fR, and
\r
98 \fBpcre_get_substring_list()\fR are convenience functions for extracting
\r
99 captured substrings from a matched subject string; \fBpcre_free_substring()\fR
\r
100 and \fBpcre_free_substring_list()\fR are also provided, to free the memory used
\r
101 for extracted strings.
\r
103 The function \fBpcre_maketables()\fR is used (optionally) to build a set of
\r
104 character tables in the current locale for passing to \fBpcre_compile()\fR.
\r
106 The function \fBpcre_fullinfo()\fR is used to find out information about a
\r
107 compiled pattern; \fBpcre_info()\fR is an obsolete version which returns only
\r
108 some of the available information, but is retained for backwards compatibility.
\r
109 The function \fBpcre_version()\fR returns a pointer to a string containing the
\r
110 version of PCRE and its date of release.
\r
112 The global variables \fBpcre_malloc\fR and \fBpcre_free\fR initially contain
\r
113 the entry points of the standard \fBmalloc()\fR and \fBfree()\fR functions
\r
114 respectively. PCRE calls the memory management functions via these variables,
\r
115 so a calling program can replace them if it wishes to intercept the calls. This
\r
116 should be done before calling any PCRE functions.
\r
119 .SH MULTI-THREADING
\r
120 The PCRE functions can be used in multi-threading applications, with the
\r
121 proviso that the memory management functions pointed to by \fBpcre_malloc\fR
\r
122 and \fBpcre_free\fR are shared by all threads.
\r
124 The compiled form of a regular expression is not altered during matching, so
\r
125 the same compiled pattern can safely be used by several threads at once.
\r
128 .SH COMPILING A PATTERN
\r
129 The function \fBpcre_compile()\fR is called to compile a pattern into an
\r
130 internal form. The pattern is a C string terminated by a binary zero, and
\r
131 is passed in the argument \fIpattern\fR. A pointer to a single block of memory
\r
132 that is obtained via \fBpcre_malloc\fR is returned. This contains the
\r
133 compiled code and related data. The \fBpcre\fR type is defined for this for
\r
134 convenience, but in fact \fBpcre\fR is just a typedef for \fBvoid\fR, since the
\r
135 contents of the block are not externally defined. It is up to the caller to
\r
136 free the memory when it is no longer required.
\r
138 The size of a compiled pattern is roughly proportional to the length of the
\r
139 pattern string, except that each character class (other than those containing
\r
140 just a single character, negated or not) requires 33 bytes, and repeat
\r
141 quantifiers with a minimum greater than one or a bounded maximum cause the
\r
142 relevant portions of the compiled pattern to be replicated.
\r
144 The \fIoptions\fR argument contains independent bits that affect the
\r
145 compilation. It should be zero if no options are required. Some of the options,
\r
146 in particular, those that are compatible with Perl, can also be set and unset
\r
147 from within the pattern (see the detailed description of regular expressions
\r
148 below). For these options, the contents of the \fIoptions\fR argument specifies
\r
149 their initial settings at the start of compilation and execution. The
\r
150 PCRE_ANCHORED option can be set at the time of matching as well as at compile
\r
153 If \fIerrptr\fR is NULL, \fBpcre_compile()\fR returns NULL immediately.
\r
154 Otherwise, if compilation of a pattern fails, \fBpcre_compile()\fR returns
\r
155 NULL, and sets the variable pointed to by \fIerrptr\fR to point to a textual
\r
156 error message. The offset from the start of the pattern to the character where
\r
157 the error was discovered is placed in the variable pointed to by
\r
158 \fIerroffset\fR, which must not be NULL. If it is, an immediate error is given.
\r
160 If the final argument, \fItableptr\fR, is NULL, PCRE uses a default set of
\r
161 character tables which are built when it is compiled, using the default C
\r
162 locale. Otherwise, \fItableptr\fR must be the result of a call to
\r
163 \fBpcre_maketables()\fR. See the section on locale support below.
\r
165 The following option bits are defined in the header file:
\r
169 If this bit is set, the pattern is forced to be "anchored", that is, it is
\r
170 constrained to match only at the start of the string which is being searched
\r
171 (the "subject string"). This effect can also be achieved by appropriate
\r
172 constructs in the pattern itself, which is the only way to do it in Perl.
\r
176 If this bit is set, letters in the pattern match both upper and lower case
\r
177 letters. It is equivalent to Perl's /i option.
\r
179 PCRE_DOLLAR_ENDONLY
\r
181 If this bit is set, a dollar metacharacter in the pattern matches only at the
\r
182 end of the subject string. Without this option, a dollar also matches
\r
183 immediately before the final character if it is a newline (but not before any
\r
184 other newlines). The PCRE_DOLLAR_ENDONLY option is ignored if PCRE_MULTILINE is
\r
185 set. There is no equivalent to this option in Perl.
\r
189 If this bit is set, a dot metacharater in the pattern matches all characters,
\r
190 including newlines. Without it, newlines are excluded. This option is
\r
191 equivalent to Perl's /s option. A negative class such as [^a] always matches a
\r
192 newline character, independent of the setting of this option.
\r
196 If this bit is set, whitespace data characters in the pattern are totally
\r
197 ignored except when escaped or inside a character class, and characters between
\r
198 an unescaped # outside a character class and the next newline character,
\r
199 inclusive, are also ignored. This is equivalent to Perl's /x option, and makes
\r
200 it possible to include comments inside complicated patterns. Note, however,
\r
201 that this applies only to data characters. Whitespace characters may never
\r
202 appear within special character sequences in a pattern, for example within the
\r
203 sequence (?( which introduces a conditional subpattern.
\r
207 This option was invented in order to turn on additional functionality of PCRE
\r
208 that is incompatible with Perl, but it is currently of very little use. When
\r
209 set, any backslash in a pattern that is followed by a letter that has no
\r
210 special meaning causes an error, thus reserving these combinations for future
\r
211 expansion. By default, as in Perl, a backslash followed by a letter with no
\r
212 special meaning is treated as a literal. There are at present no other features
\r
213 controlled by this option. It can also be set by a (?X) option setting within a
\r
218 By default, PCRE treats the subject string as consisting of a single "line" of
\r
219 characters (even if it actually contains several newlines). The "start of line"
\r
220 metacharacter (^) matches only at the start of the string, while the "end of
\r
221 line" metacharacter ($) matches only at the end of the string, or before a
\r
222 terminating newline (unless PCRE_DOLLAR_ENDONLY is set). This is the same as
\r
225 When PCRE_MULTILINE it is set, the "start of line" and "end of line" constructs
\r
226 match immediately following or immediately before any newline in the subject
\r
227 string, respectively, as well as at the very start and end. This is equivalent
\r
228 to Perl's /m option. If there are no "\\n" characters in a subject string, or
\r
229 no occurrences of ^ or $ in a pattern, setting PCRE_MULTILINE has no
\r
234 This option inverts the "greediness" of the quantifiers so that they are not
\r
235 greedy by default, but become greedy if followed by "?". It is not compatible
\r
236 with Perl. It can also be set by a (?U) option setting within the pattern.
\r
240 This option causes PCRE to regard both the pattern and the subject as strings
\r
241 of UTF-8 characters instead of just byte strings. However, it is available only
\r
242 if PCRE has been built to include UTF-8 support. If not, the use of this option
\r
243 provokes an error. Support for UTF-8 is new, experimental, and incomplete.
\r
244 Details of exactly what it entails are given below.
\r
247 .SH STUDYING A PATTERN
\r
248 When a pattern is going to be used several times, it is worth spending more
\r
249 time analyzing it in order to speed up the time taken for matching. The
\r
250 function \fBpcre_study()\fR takes a pointer to a compiled pattern as its first
\r
251 argument, and returns a pointer to a \fBpcre_extra\fR block (another \fBvoid\fR
\r
252 typedef) containing additional information about the pattern; this can be
\r
253 passed to \fBpcre_exec()\fR. If no additional information is available, NULL
\r
256 The second argument contains option bits. At present, no options are defined
\r
257 for \fBpcre_study()\fR, and this argument should always be zero.
\r
259 The third argument for \fBpcre_study()\fR is a pointer to an error message. If
\r
260 studying succeeds (even if no data is returned), the variable it points to is
\r
261 set to NULL. Otherwise it points to a textual error message.
\r
263 At present, studying a pattern is useful only for non-anchored patterns that do
\r
264 not have a single fixed starting character. A bitmap of possible starting
\r
265 characters is created.
\r
269 PCRE handles caseless matching, and determines whether characters are letters,
\r
270 digits, or whatever, by reference to a set of tables. The library contains a
\r
271 default set of tables which is created in the default C locale when PCRE is
\r
272 compiled. This is used when the final argument of \fBpcre_compile()\fR is NULL,
\r
273 and is sufficient for many applications.
\r
275 An alternative set of tables can, however, be supplied. Such tables are built
\r
276 by calling the \fBpcre_maketables()\fR function, which has no arguments, in the
\r
277 relevant locale. The result can then be passed to \fBpcre_compile()\fR as often
\r
278 as necessary. For example, to build and use tables that are appropriate for the
\r
279 French locale (where accented characters with codes greater than 128 are
\r
280 treated as letters), the following code could be used:
\r
282 setlocale(LC_CTYPE, "fr");
\r
283 tables = pcre_maketables();
\r
284 re = pcre_compile(..., tables);
\r
286 The tables are built in memory that is obtained via \fBpcre_malloc\fR. The
\r
287 pointer that is passed to \fBpcre_compile\fR is saved with the compiled
\r
288 pattern, and the same tables are used via this pointer by \fBpcre_study()\fR
\r
289 and \fBpcre_exec()\fR. Thus for any single pattern, compilation, studying and
\r
290 matching all happen in the same locale, but different patterns can be compiled
\r
291 in different locales. It is the caller's responsibility to ensure that the
\r
292 memory containing the tables remains available for as long as it is needed.
\r
295 .SH INFORMATION ABOUT A PATTERN
\r
296 The \fBpcre_fullinfo()\fR function returns information about a compiled
\r
297 pattern. It replaces the obsolete \fBpcre_info()\fR function, which is
\r
298 nevertheless retained for backwards compability (and is documented below).
\r
300 The first argument for \fBpcre_fullinfo()\fR is a pointer to the compiled
\r
301 pattern. The second argument is the result of \fBpcre_study()\fR, or NULL if
\r
302 the pattern was not studied. The third argument specifies which piece of
\r
303 information is required, while the fourth argument is a pointer to a variable
\r
304 to receive the data. The yield of the function is zero for success, or one of
\r
305 the following negative numbers:
\r
307 PCRE_ERROR_NULL the argument \fIcode\fR was NULL
\r
308 the argument \fIwhere\fR was NULL
\r
309 PCRE_ERROR_BADMAGIC the "magic number" was not found
\r
310 PCRE_ERROR_BADOPTION the value of \fIwhat\fR was invalid
\r
312 The possible values for the third argument are defined in \fBpcre.h\fR, and are
\r
317 Return a copy of the options with which the pattern was compiled. The fourth
\r
318 argument should point to au \fBunsigned long int\fR variable. These option bits
\r
319 are those specified in the call to \fBpcre_compile()\fR, modified by any
\r
320 top-level option settings within the pattern itself, and with the PCRE_ANCHORED
\r
321 bit forcibly set if the form of the pattern implies that it can match only at
\r
322 the start of a subject string.
\r
326 Return the size of the compiled pattern, that is, the value that was passed as
\r
327 the argument to \fBpcre_malloc()\fR when PCRE was getting memory in which to
\r
328 place the compiled data. The fourth argument should point to a \fBsize_t\fR
\r
331 PCRE_INFO_CAPTURECOUNT
\r
333 Return the number of capturing subpatterns in the pattern. The fourth argument
\r
334 should point to an \fbint\fR variable.
\r
336 PCRE_INFO_BACKREFMAX
\r
338 Return the number of the highest back reference in the pattern. The fourth
\r
339 argument should point to an \fBint\fR variable. Zero is returned if there are
\r
340 no back references.
\r
342 PCRE_INFO_FIRSTCHAR
\r
344 Return information about the first character of any matched string, for a
\r
345 non-anchored pattern. If there is a fixed first character, e.g. from a pattern
\r
346 such as (cat|cow|coyote), it is returned in the integer pointed to by
\r
347 \fIwhere\fR. Otherwise, if either
\r
349 (a) the pattern was compiled with the PCRE_MULTILINE option, and every branch
\r
350 starts with "^", or
\r
352 (b) every branch of the pattern starts with ".*" and PCRE_DOTALL is not set
\r
353 (if it were set, the pattern would be anchored),
\r
355 -1 is returned, indicating that the pattern matches only at the start of a
\r
356 subject string or after any "\\n" within the string. Otherwise -2 is returned.
\r
357 For anchored patterns, -2 is returned.
\r
359 PCRE_INFO_FIRSTTABLE
\r
361 If the pattern was studied, and this resulted in the construction of a 256-bit
\r
362 table indicating a fixed set of characters for the first character in any
\r
363 matching string, a pointer to the table is returned. Otherwise NULL is
\r
364 returned. The fourth argument should point to an \fBunsigned char *\fR
\r
367 PCRE_INFO_LASTLITERAL
\r
369 For a non-anchored pattern, return the value of the rightmost literal character
\r
370 which must exist in any matched string, other than at its start. The fourth
\r
371 argument should point to an \fBint\fR variable. If there is no such character,
\r
372 or if the pattern is anchored, -1 is returned. For example, for the pattern
\r
373 /a\\d+z\\d+/ the returned value is 'z'.
\r
375 The \fBpcre_info()\fR function is now obsolete because its interface is too
\r
376 restrictive to return all the available data about a compiled pattern. New
\r
377 programs should use \fBpcre_fullinfo()\fR instead. The yield of
\r
378 \fBpcre_info()\fR is the number of capturing subpatterns, or one of the
\r
379 following negative numbers:
\r
381 PCRE_ERROR_NULL the argument \fIcode\fR was NULL
\r
382 PCRE_ERROR_BADMAGIC the "magic number" was not found
\r
384 If the \fIoptptr\fR argument is not NULL, a copy of the options with which the
\r
385 pattern was compiled is placed in the integer it points to (see
\r
386 PCRE_INFO_OPTIONS above).
\r
388 If the pattern is not anchored and the \fIfirstcharptr\fR argument is not NULL,
\r
389 it is used to pass back information about the first character of any matched
\r
390 string (see PCRE_INFO_FIRSTCHAR above).
\r
393 .SH MATCHING A PATTERN
\r
394 The function \fBpcre_exec()\fR is called to match a subject string against a
\r
395 pre-compiled pattern, which is passed in the \fIcode\fR argument. If the
\r
396 pattern has been studied, the result of the study should be passed in the
\r
397 \fIextra\fR argument. Otherwise this must be NULL.
\r
399 The PCRE_ANCHORED option can be passed in the \fIoptions\fR argument, whose
\r
400 unused bits must be zero. However, if a pattern was compiled with
\r
401 PCRE_ANCHORED, or turned out to be anchored by virtue of its contents, it
\r
402 cannot be made unachored at matching time.
\r
404 There are also three further options that can be set only at matching time:
\r
408 The first character of the string is not the beginning of a line, so the
\r
409 circumflex metacharacter should not match before it. Setting this without
\r
410 PCRE_MULTILINE (at compile time) causes circumflex never to match.
\r
414 The end of the string is not the end of a line, so the dollar metacharacter
\r
415 should not match it nor (except in multiline mode) a newline immediately before
\r
416 it. Setting this without PCRE_MULTILINE (at compile time) causes dollar never
\r
421 An empty string is not considered to be a valid match if this option is set. If
\r
422 there are alternatives in the pattern, they are tried. If all the alternatives
\r
423 match the empty string, the entire match fails. For example, if the pattern
\r
427 is applied to a string not beginning with "a" or "b", it matches the empty
\r
428 string at the start of the subject. With PCRE_NOTEMPTY set, this match is not
\r
429 valid, so PCRE searches further into the string for occurrences of "a" or "b".
\r
431 Perl has no direct equivalent of PCRE_NOTEMPTY, but it does make a special case
\r
432 of a pattern match of the empty string within its \fBsplit()\fR function, and
\r
433 when using the /g modifier. It is possible to emulate Perl's behaviour after
\r
434 matching a null string by first trying the match again at the same offset with
\r
435 PCRE_NOTEMPTY set, and then if that fails by advancing the starting offset (see
\r
436 below) and trying an ordinary match again.
\r
438 The subject string is passed as a pointer in \fIsubject\fR, a length in
\r
439 \fIlength\fR, and a starting offset in \fIstartoffset\fR. Unlike the pattern
\r
440 string, it may contain binary zero characters. When the starting offset is
\r
441 zero, the search for a match starts at the beginning of the subject, and this
\r
442 is by far the most common case.
\r
444 A non-zero starting offset is useful when searching for another match in the
\r
445 same subject by calling \fBpcre_exec()\fR again after a previous success.
\r
446 Setting \fIstartoffset\fR differs from just passing over a shortened string and
\r
447 setting PCRE_NOTBOL in the case of a pattern that begins with any kind of
\r
448 lookbehind. For example, consider the pattern
\r
452 which finds occurrences of "iss" in the middle of words. (\\B matches only if
\r
453 the current position in the subject is not a word boundary.) When applied to
\r
454 the string "Mississipi" the first call to \fBpcre_exec()\fR finds the first
\r
455 occurrence. If \fBpcre_exec()\fR is called again with just the remainder of the
\r
456 subject, namely "issipi", it does not match, because \\B is always false at the
\r
457 start of the subject, which is deemed to be a word boundary. However, if
\r
458 \fBpcre_exec()\fR is passed the entire string again, but with \fIstartoffset\fR
\r
459 set to 4, it finds the second occurrence of "iss" because it is able to look
\r
460 behind the starting point to discover that it is preceded by a letter.
\r
462 If a non-zero starting offset is passed when the pattern is anchored, one
\r
463 attempt to match at the given offset is tried. This can only succeed if the
\r
464 pattern does not require the match to be at the start of the subject.
\r
466 In general, a pattern matches a certain portion of the subject, and in
\r
467 addition, further substrings from the subject may be picked out by parts of the
\r
468 pattern. Following the usage in Jeffrey Friedl's book, this is called
\r
469 "capturing" in what follows, and the phrase "capturing subpattern" is used for
\r
470 a fragment of a pattern that picks out a substring. PCRE supports several other
\r
471 kinds of parenthesized subpattern that do not cause substrings to be captured.
\r
473 Captured substrings are returned to the caller via a vector of integer offsets
\r
474 whose address is passed in \fIovector\fR. The number of elements in the vector
\r
475 is passed in \fIovecsize\fR. The first two-thirds of the vector is used to pass
\r
476 back captured substrings, each substring using a pair of integers. The
\r
477 remaining third of the vector is used as workspace by \fBpcre_exec()\fR while
\r
478 matching capturing subpatterns, and is not available for passing back
\r
479 information. The length passed in \fIovecsize\fR should always be a multiple of
\r
480 three. If it is not, it is rounded down.
\r
482 When a match has been successful, information about captured substrings is
\r
483 returned in pairs of integers, starting at the beginning of \fIovector\fR, and
\r
484 continuing up to two-thirds of its length at the most. The first element of a
\r
485 pair is set to the offset of the first character in a substring, and the second
\r
486 is set to the offset of the first character after the end of a substring. The
\r
487 first pair, \fIovector[0]\fR and \fIovector[1]\fR, identify the portion of the
\r
488 subject string matched by the entire pattern. The next pair is used for the
\r
489 first capturing subpattern, and so on. The value returned by \fBpcre_exec()\fR
\r
490 is the number of pairs that have been set. If there are no capturing
\r
491 subpatterns, the return value from a successful match is 1, indicating that
\r
492 just the first pair of offsets has been set.
\r
494 Some convenience functions are provided for extracting the captured substrings
\r
495 as separate strings. These are described in the following section.
\r
497 It is possible for an capturing subpattern number \fIn+1\fR to match some
\r
498 part of the subject when subpattern \fIn\fR has not been used at all. For
\r
499 example, if the string "abc" is matched against the pattern (a|(z))(bc)
\r
500 subpatterns 1 and 3 are matched, but 2 is not. When this happens, both offset
\r
501 values corresponding to the unused subpattern are set to -1.
\r
503 If a capturing subpattern is matched repeatedly, it is the last portion of the
\r
504 string that it matched that gets returned.
\r
506 If the vector is too small to hold all the captured substrings, it is used as
\r
507 far as possible (up to two-thirds of its length), and the function returns a
\r
508 value of zero. In particular, if the substring offsets are not of interest,
\r
509 \fBpcre_exec()\fR may be called with \fIovector\fR passed as NULL and
\r
510 \fIovecsize\fR as zero. However, if the pattern contains back references and
\r
511 the \fIovector\fR isn't big enough to remember the related substrings, PCRE has
\r
512 to get additional memory for use during matching. Thus it is usually advisable
\r
513 to supply an \fIovector\fR.
\r
515 Note that \fBpcre_info()\fR can be used to find out how many capturing
\r
516 subpatterns there are in a compiled pattern. The smallest size for
\r
517 \fIovector\fR that will allow for \fIn\fR captured substrings in addition to
\r
518 the offsets of the substring matched by the whole pattern is (\fIn\fR+1)*3.
\r
520 If \fBpcre_exec()\fR fails, it returns a negative number. The following are
\r
521 defined in the header file:
\r
523 PCRE_ERROR_NOMATCH (-1)
\r
525 The subject string did not match the pattern.
\r
527 PCRE_ERROR_NULL (-2)
\r
529 Either \fIcode\fR or \fIsubject\fR was passed as NULL, or \fIovector\fR was
\r
530 NULL and \fIovecsize\fR was not zero.
\r
532 PCRE_ERROR_BADOPTION (-3)
\r
534 An unrecognized bit was set in the \fIoptions\fR argument.
\r
536 PCRE_ERROR_BADMAGIC (-4)
\r
538 PCRE stores a 4-byte "magic number" at the start of the compiled code, to catch
\r
539 the case when it is passed a junk pointer. This is the error it gives when the
\r
540 magic number isn't present.
\r
542 PCRE_ERROR_UNKNOWN_NODE (-5)
\r
544 While running the pattern match, an unknown item was encountered in the
\r
545 compiled pattern. This error could be caused by a bug in PCRE or by overwriting
\r
546 of the compiled pattern.
\r
548 PCRE_ERROR_NOMEMORY (-6)
\r
550 If a pattern contains back references, but the \fIovector\fR that is passed to
\r
551 \fBpcre_exec()\fR is not big enough to remember the referenced substrings, PCRE
\r
552 gets a block of memory at the start of matching to use for this purpose. If the
\r
553 call via \fBpcre_malloc()\fR fails, this error is given. The memory is freed at
\r
554 the end of matching.
\r
557 .SH EXTRACTING CAPTURED SUBSTRINGS
\r
558 Captured substrings can be accessed directly by using the offsets returned by
\r
559 \fBpcre_exec()\fR in \fIovector\fR. For convenience, the functions
\r
560 \fBpcre_copy_substring()\fR, \fBpcre_get_substring()\fR, and
\r
561 \fBpcre_get_substring_list()\fR are provided for extracting captured substrings
\r
562 as new, separate, zero-terminated strings. A substring that contains a binary
\r
563 zero is correctly extracted and has a further zero added on the end, but the
\r
564 result does not, of course, function as a C string.
\r
566 The first three arguments are the same for all three functions: \fIsubject\fR
\r
567 is the subject string which has just been successfully matched, \fIovector\fR
\r
568 is a pointer to the vector of integer offsets that was passed to
\r
569 \fBpcre_exec()\fR, and \fIstringcount\fR is the number of substrings that
\r
570 were captured by the match, including the substring that matched the entire
\r
571 regular expression. This is the value returned by \fBpcre_exec\fR if it
\r
572 is greater than zero. If \fBpcre_exec()\fR returned zero, indicating that it
\r
573 ran out of space in \fIovector\fR, the value passed as \fIstringcount\fR should
\r
574 be the size of the vector divided by three.
\r
576 The functions \fBpcre_copy_substring()\fR and \fBpcre_get_substring()\fR
\r
577 extract a single substring, whose number is given as \fIstringnumber\fR. A
\r
578 value of zero extracts the substring that matched the entire pattern, while
\r
579 higher values extract the captured substrings. For \fBpcre_copy_substring()\fR,
\r
580 the string is placed in \fIbuffer\fR, whose length is given by
\r
581 \fIbuffersize\fR, while for \fBpcre_get_substring()\fR a new block of memory is
\r
582 obtained via \fBpcre_malloc\fR, and its address is returned via
\r
583 \fIstringptr\fR. The yield of the function is the length of the string, not
\r
584 including the terminating zero, or one of
\r
586 PCRE_ERROR_NOMEMORY (-6)
\r
588 The buffer was too small for \fBpcre_copy_substring()\fR, or the attempt to get
\r
589 memory failed for \fBpcre_get_substring()\fR.
\r
591 PCRE_ERROR_NOSUBSTRING (-7)
\r
593 There is no substring whose number is \fIstringnumber\fR.
\r
595 The \fBpcre_get_substring_list()\fR function extracts all available substrings
\r
596 and builds a list of pointers to them. All this is done in a single block of
\r
597 memory which is obtained via \fBpcre_malloc\fR. The address of the memory block
\r
598 is returned via \fIlistptr\fR, which is also the start of the list of string
\r
599 pointers. The end of the list is marked by a NULL pointer. The yield of the
\r
600 function is zero if all went well, or
\r
602 PCRE_ERROR_NOMEMORY (-6)
\r
604 if the attempt to get the memory block failed.
\r
606 When any of these functions encounter a substring that is unset, which can
\r
607 happen when capturing subpattern number \fIn+1\fR matches some part of the
\r
608 subject, but subpattern \fIn\fR has not been used at all, they return an empty
\r
609 string. This can be distinguished from a genuine zero-length substring by
\r
610 inspecting the appropriate offset in \fIovector\fR, which is negative for unset
\r
613 The two convenience functions \fBpcre_free_substring()\fR and
\r
614 \fBpcre_free_substring_list()\fR can be used to free the memory returned by
\r
615 a previous call of \fBpcre_get_substring()\fR or
\r
616 \fBpcre_get_substring_list()\fR, respectively. They do nothing more than call
\r
617 the function pointed to by \fBpcre_free\fR, which of course could be called
\r
618 directly from a C program. However, PCRE is used in some situations where it is
\r
619 linked via a special interface to another programming language which cannot use
\r
620 \fBpcre_free\fR directly; it is for these cases that the functions are
\r
625 There are some size limitations in PCRE but it is hoped that they will never in
\r
626 practice be relevant.
\r
627 The maximum length of a compiled pattern is 65539 (sic) bytes.
\r
628 All values in repeating quantifiers must be less than 65536.
\r
629 The maximum number of capturing subpatterns is 99.
\r
630 The maximum number of all parenthesized subpatterns, including capturing
\r
631 subpatterns, assertions, and other types of subpattern, is 200.
\r
633 The maximum length of a subject string is the largest positive number that an
\r
634 integer variable can hold. However, PCRE uses recursion to handle subpatterns
\r
635 and indefinite repetition. This means that the available stack space may limit
\r
636 the size of a subject string that can be processed by certain patterns.
\r
639 .SH DIFFERENCES FROM PERL
\r
640 The differences described here are with respect to Perl 5.005.
\r
642 1. By default, a whitespace character is any character that the C library
\r
643 function \fBisspace()\fR recognizes, though it is possible to compile PCRE with
\r
644 alternative character type tables. Normally \fBisspace()\fR matches space,
\r
645 formfeed, newline, carriage return, horizontal tab, and vertical tab. Perl 5
\r
646 no longer includes vertical tab in its set of whitespace characters. The \\v
\r
647 escape that was in the Perl documentation for a long time was never in fact
\r
648 recognized. However, the character itself was treated as whitespace at least
\r
649 up to 5.002. In 5.004 and 5.005 it does not match \\s.
\r
651 2. PCRE does not allow repeat quantifiers on lookahead assertions. Perl permits
\r
652 them, but they do not mean what you might think. For example, (?!a){3} does
\r
653 not assert that the next three characters are not "a". It just asserts that the
\r
654 next character is not "a" three times.
\r
656 3. Capturing subpatterns that occur inside negative lookahead assertions are
\r
657 counted, but their entries in the offsets vector are never set. Perl sets its
\r
658 numerical variables from any such patterns that are matched before the
\r
659 assertion fails to match something (thereby succeeding), but only if the
\r
660 negative lookahead assertion contains just one branch.
\r
662 4. Though binary zero characters are supported in the subject string, they are
\r
663 not allowed in a pattern string because it is passed as a normal C string,
\r
664 terminated by zero. The escape sequence "\\0" can be used in the pattern to
\r
665 represent a binary zero.
\r
667 5. The following Perl escape sequences are not supported: \\l, \\u, \\L, \\U,
\r
668 \\E, \\Q. In fact these are implemented by Perl's general string-handling and
\r
669 are not part of its pattern matching engine.
\r
671 6. The Perl \\G assertion is not supported as it is not relevant to single
\r
674 7. Fairly obviously, PCRE does not support the (?{code}) and (?p{code})
\r
675 constructions. However, there is some experimental support for recursive
\r
676 patterns using the non-Perl item (?R).
\r
678 8. There are at the time of writing some oddities in Perl 5.005_02 concerned
\r
679 with the settings of captured strings when part of a pattern is repeated. For
\r
680 example, matching "aba" against the pattern /^(a(b)?)+$/ sets $2 to the value
\r
681 "b", but matching "aabbaa" against /^(aa(bb)?)+$/ leaves $2 unset. However, if
\r
682 the pattern is changed to /^(aa(b(b))?)+$/ then $2 (and $3) are set.
\r
684 In Perl 5.004 $2 is set in both cases, and that is also true of PCRE. If in the
\r
685 future Perl changes to a consistent state that is different, PCRE may change to
\r
688 9. Another as yet unresolved discrepancy is that in Perl 5.005_02 the pattern
\r
689 /^(a)?(?(1)a|b)+$/ matches the string "a", whereas in PCRE it does not.
\r
690 However, in both Perl and PCRE /^(a)?a/ matched against "a" leaves $1 unset.
\r
692 10. PCRE provides some extensions to the Perl regular expression facilities:
\r
694 (a) Although lookbehind assertions must match fixed length strings, each
\r
695 alternative branch of a lookbehind assertion can match a different length of
\r
696 string. Perl 5.005 requires them all to have the same length.
\r
698 (b) If PCRE_DOLLAR_ENDONLY is set and PCRE_MULTILINE is not set, the $ meta-
\r
699 character matches only at the very end of the string.
\r
701 (c) If PCRE_EXTRA is set, a backslash followed by a letter with no special
\r
702 meaning is faulted.
\r
704 (d) If PCRE_UNGREEDY is set, the greediness of the repetition quantifiers is
\r
705 inverted, that is, by default they are not greedy, but if followed by a
\r
706 question mark they are.
\r
708 (e) PCRE_ANCHORED can be used to force a pattern to be tried only at the start
\r
711 (f) The PCRE_NOTBOL, PCRE_NOTEOL, and PCRE_NOTEMPTY options for
\r
712 \fBpcre_exec()\fR have no Perl equivalents.
\r
714 (g) The (?R) construct allows for recursive pattern matching (Perl 5.6 can do
\r
715 this using the (?p{code}) construct, which PCRE cannot of course support.)
\r
718 .SH REGULAR EXPRESSION DETAILS
\r
719 The syntax and semantics of the regular expressions supported by PCRE are
\r
720 described below. Regular expressions are also described in the Perl
\r
721 documentation and in a number of other books, some of which have copious
\r
722 examples. Jeffrey Friedl's "Mastering Regular Expressions", published by
\r
723 O'Reilly (ISBN 1-56592-257), covers them in great detail.
\r
725 The description here is intended as reference documentation. The basic
\r
726 operation of PCRE is on strings of bytes. However, there is the beginnings of
\r
727 some support for UTF-8 character strings. To use this support you must
\r
728 configure PCRE to include it, and then call \fBpcre_compile()\fR with the
\r
729 PCRE_UTF8 option. How this affects the pattern matching is described in the
\r
730 final section of this document.
\r
732 A regular expression is a pattern that is matched against a subject string from
\r
733 left to right. Most characters stand for themselves in a pattern, and match the
\r
734 corresponding characters in the subject. As a trivial example, the pattern
\r
736 The quick brown fox
\r
738 matches a portion of a subject string that is identical to itself. The power of
\r
739 regular expressions comes from the ability to include alternatives and
\r
740 repetitions in the pattern. These are encoded in the pattern by the use of
\r
741 \fImeta-characters\fR, which do not stand for themselves but instead are
\r
742 interpreted in some special way.
\r
744 There are two different sets of meta-characters: those that are recognized
\r
745 anywhere in the pattern except within square brackets, and those that are
\r
746 recognized in square brackets. Outside square brackets, the meta-characters are
\r
749 \\ general escape character with several uses
\r
750 ^ assert start of subject (or line, in multiline mode)
\r
751 $ assert end of subject (or line, in multiline mode)
\r
752 . match any character except newline (by default)
\r
753 [ start character class definition
\r
754 | start of alternative branch
\r
757 ? extends the meaning of (
\r
758 also 0 or 1 quantifier
\r
759 also quantifier minimizer
\r
760 * 0 or more quantifier
\r
761 + 1 or more quantifier
\r
762 { start min/max quantifier
\r
764 Part of a pattern that is in square brackets is called a "character class". In
\r
765 a character class the only meta-characters are:
\r
767 \\ general escape character
\r
768 ^ negate the class, but only if the first character
\r
769 - indicates character range
\r
770 ] terminates the character class
\r
772 The following sections describe the use of each of the meta-characters.
\r
776 The backslash character has several uses. Firstly, if it is followed by a
\r
777 non-alphameric character, it takes away any special meaning that character may
\r
778 have. This use of backslash as an escape character applies both inside and
\r
779 outside character classes.
\r
781 For example, if you want to match a "*" character, you write "\\*" in the
\r
782 pattern. This applies whether or not the following character would otherwise be
\r
783 interpreted as a meta-character, so it is always safe to precede a
\r
784 non-alphameric with "\\" to specify that it stands for itself. In particular,
\r
785 if you want to match a backslash, you write "\\\\".
\r
787 If a pattern is compiled with the PCRE_EXTENDED option, whitespace in the
\r
788 pattern (other than in a character class) and characters between a "#" outside
\r
789 a character class and the next newline character are ignored. An escaping
\r
790 backslash can be used to include a whitespace or "#" character as part of the
\r
793 A second use of backslash provides a way of encoding non-printing characters
\r
794 in patterns in a visible manner. There is no restriction on the appearance of
\r
795 non-printing characters, apart from the binary zero that terminates a pattern,
\r
796 but when a pattern is being prepared by text editing, it is usually easier to
\r
797 use one of the following escape sequences than the binary character it
\r
800 \\a alarm, that is, the BEL character (hex 07)
\r
801 \\cx "control-x", where x is any character
\r
802 \\e escape (hex 1B)
\r
803 \\f formfeed (hex 0C)
\r
804 \\n newline (hex 0A)
\r
805 \\r carriage return (hex 0D)
\r
807 \\xhh character with hex code hh
\r
808 \\ddd character with octal code ddd, or backreference
\r
810 The precise effect of "\\cx" is as follows: if "x" is a lower case letter, it
\r
811 is converted to upper case. Then bit 6 of the character (hex 40) is inverted.
\r
812 Thus "\\cz" becomes hex 1A, but "\\c{" becomes hex 3B, while "\\c;" becomes hex
\r
815 After "\\x", up to two hexadecimal digits are read (letters can be in upper or
\r
818 After "\\0" up to two further octal digits are read. In both cases, if there
\r
819 are fewer than two digits, just those that are present are used. Thus the
\r
820 sequence "\\0\\x\\07" specifies two binary zeros followed by a BEL character.
\r
821 Make sure you supply two digits after the initial zero if the character that
\r
822 follows is itself an octal digit.
\r
824 The handling of a backslash followed by a digit other than 0 is complicated.
\r
825 Outside a character class, PCRE reads it and any following digits as a decimal
\r
826 number. If the number is less than 10, or if there have been at least that many
\r
827 previous capturing left parentheses in the expression, the entire sequence is
\r
828 taken as a \fIback reference\fR. A description of how this works is given
\r
829 later, following the discussion of parenthesized subpatterns.
\r
831 Inside a character class, or if the decimal number is greater than 9 and there
\r
832 have not been that many capturing subpatterns, PCRE re-reads up to three octal
\r
833 digits following the backslash, and generates a single byte from the least
\r
834 significant 8 bits of the value. Any subsequent digits stand for themselves.
\r
837 \\040 is another way of writing a space
\r
838 \\40 is the same, provided there are fewer than 40
\r
839 previous capturing subpatterns
\r
840 \\7 is always a back reference
\r
841 \\11 might be a back reference, or another way of
\r
843 \\011 is always a tab
\r
844 \\0113 is a tab followed by the character "3"
\r
845 \\113 is the character with octal code 113 (since there
\r
846 can be no more than 99 back references)
\r
847 \\377 is a byte consisting entirely of 1 bits
\r
848 \\81 is either a back reference, or a binary zero
\r
849 followed by the two characters "8" and "1"
\r
851 Note that octal values of 100 or greater must not be introduced by a leading
\r
852 zero, because no more than three octal digits are ever read.
\r
854 All the sequences that define a single byte value can be used both inside and
\r
855 outside character classes. In addition, inside a character class, the sequence
\r
856 "\\b" is interpreted as the backspace character (hex 08). Outside a character
\r
857 class it has a different meaning (see below).
\r
859 The third use of backslash is for specifying generic character types:
\r
861 \\d any decimal digit
\r
862 \\D any character that is not a decimal digit
\r
863 \\s any whitespace character
\r
864 \\S any character that is not a whitespace character
\r
865 \\w any "word" character
\r
866 \\W any "non-word" character
\r
868 Each pair of escape sequences partitions the complete set of characters into
\r
869 two disjoint sets. Any given character matches one, and only one, of each pair.
\r
871 A "word" character is any letter or digit or the underscore character, that is,
\r
872 any character which can be part of a Perl "word". The definition of letters and
\r
873 digits is controlled by PCRE's character tables, and may vary if locale-
\r
874 specific matching is taking place (see "Locale support" above). For example, in
\r
875 the "fr" (French) locale, some character codes greater than 128 are used for
\r
876 accented letters, and these are matched by \\w.
\r
878 These character type sequences can appear both inside and outside character
\r
879 classes. They each match one character of the appropriate type. If the current
\r
880 matching point is at the end of the subject string, all of them fail, since
\r
881 there is no character to match.
\r
883 The fourth use of backslash is for certain simple assertions. An assertion
\r
884 specifies a condition that has to be met at a particular point in a match,
\r
885 without consuming any characters from the subject string. The use of
\r
886 subpatterns for more complicated assertions is described below. The backslashed
\r
890 \\B not a word boundary
\r
891 \\A start of subject (independent of multiline mode)
\r
892 \\Z end of subject or newline at end (independent of multiline mode)
\r
893 \\z end of subject (independent of multiline mode)
\r
895 These assertions may not appear in character classes (but note that "\\b" has a
\r
896 different meaning, namely the backspace character, inside a character class).
\r
898 A word boundary is a position in the subject string where the current character
\r
899 and the previous character do not both match \\w or \\W (i.e. one matches
\r
900 \\w and the other matches \\W), or the start or end of the string if the
\r
901 first or last character matches \\w, respectively.
\r
903 The \\A, \\Z, and \\z assertions differ from the traditional circumflex and
\r
904 dollar (described below) in that they only ever match at the very start and end
\r
905 of the subject string, whatever options are set. They are not affected by the
\r
906 PCRE_NOTBOL or PCRE_NOTEOL options. If the \fIstartoffset\fR argument of
\r
907 \fBpcre_exec()\fR is non-zero, \\A can never match. The difference between \\Z
\r
908 and \\z is that \\Z matches before a newline that is the last character of the
\r
909 string as well as at the end of the string, whereas \\z matches only at the
\r
913 .SH CIRCUMFLEX AND DOLLAR
\r
914 Outside a character class, in the default matching mode, the circumflex
\r
915 character is an assertion which is true only if the current matching point is
\r
916 at the start of the subject string. If the \fIstartoffset\fR argument of
\r
917 \fBpcre_exec()\fR is non-zero, circumflex can never match. Inside a character
\r
918 class, circumflex has an entirely different meaning (see below).
\r
920 Circumflex need not be the first character of the pattern if a number of
\r
921 alternatives are involved, but it should be the first thing in each alternative
\r
922 in which it appears if the pattern is ever to match that branch. If all
\r
923 possible alternatives start with a circumflex, that is, if the pattern is
\r
924 constrained to match only at the start of the subject, it is said to be an
\r
925 "anchored" pattern. (There are also other constructs that can cause a pattern
\r
928 A dollar character is an assertion which is true only if the current matching
\r
929 point is at the end of the subject string, or immediately before a newline
\r
930 character that is the last character in the string (by default). Dollar need
\r
931 not be the last character of the pattern if a number of alternatives are
\r
932 involved, but it should be the last item in any branch in which it appears.
\r
933 Dollar has no special meaning in a character class.
\r
935 The meaning of dollar can be changed so that it matches only at the very end of
\r
936 the string, by setting the PCRE_DOLLAR_ENDONLY option at compile or matching
\r
937 time. This does not affect the \\Z assertion.
\r
939 The meanings of the circumflex and dollar characters are changed if the
\r
940 PCRE_MULTILINE option is set. When this is the case, they match immediately
\r
941 after and immediately before an internal "\\n" character, respectively, in
\r
942 addition to matching at the start and end of the subject string. For example,
\r
943 the pattern /^abc$/ matches the subject string "def\\nabc" in multiline mode,
\r
944 but not otherwise. Consequently, patterns that are anchored in single line mode
\r
945 because all branches start with "^" are not anchored in multiline mode, and a
\r
946 match for circumflex is possible when the \fIstartoffset\fR argument of
\r
947 \fBpcre_exec()\fR is non-zero. The PCRE_DOLLAR_ENDONLY option is ignored if
\r
948 PCRE_MULTILINE is set.
\r
950 Note that the sequences \\A, \\Z, and \\z can be used to match the start and
\r
951 end of the subject in both modes, and if all branches of a pattern start with
\r
952 \\A is it always anchored, whether PCRE_MULTILINE is set or not.
\r
955 .SH FULL STOP (PERIOD, DOT)
\r
956 Outside a character class, a dot in the pattern matches any one character in
\r
957 the subject, including a non-printing character, but not (by default) newline.
\r
958 If the PCRE_DOTALL option is set, dots match newlines as well. The handling of
\r
959 dot is entirely independent of the handling of circumflex and dollar, the only
\r
960 relationship being that they both involve newline characters. Dot has no
\r
961 special meaning in a character class.
\r
964 .SH SQUARE BRACKETS
\r
965 An opening square bracket introduces a character class, terminated by a closing
\r
966 square bracket. A closing square bracket on its own is not special. If a
\r
967 closing square bracket is required as a member of the class, it should be the
\r
968 first data character in the class (after an initial circumflex, if present) or
\r
969 escaped with a backslash.
\r
971 A character class matches a single character in the subject; the character must
\r
972 be in the set of characters defined by the class, unless the first character in
\r
973 the class is a circumflex, in which case the subject character must not be in
\r
974 the set defined by the class. If a circumflex is actually required as a member
\r
975 of the class, ensure it is not the first character, or escape it with a
\r
978 For example, the character class [aeiou] matches any lower case vowel, while
\r
979 [^aeiou] matches any character that is not a lower case vowel. Note that a
\r
980 circumflex is just a convenient notation for specifying the characters which
\r
981 are in the class by enumerating those that are not. It is not an assertion: it
\r
982 still consumes a character from the subject string, and fails if the current
\r
983 pointer is at the end of the string.
\r
985 When caseless matching is set, any letters in a class represent both their
\r
986 upper case and lower case versions, so for example, a caseless [aeiou] matches
\r
987 "A" as well as "a", and a caseless [^aeiou] does not match "A", whereas a
\r
988 caseful version would.
\r
990 The newline character is never treated in any special way in character classes,
\r
991 whatever the setting of the PCRE_DOTALL or PCRE_MULTILINE options is. A class
\r
992 such as [^a] will always match a newline.
\r
994 The minus (hyphen) character can be used to specify a range of characters in a
\r
995 character class. For example, [d-m] matches any letter between d and m,
\r
996 inclusive. If a minus character is required in a class, it must be escaped with
\r
997 a backslash or appear in a position where it cannot be interpreted as
\r
998 indicating a range, typically as the first or last character in the class.
\r
1000 It is not possible to have the literal character "]" as the end character of a
\r
1001 range. A pattern such as [W-]46] is interpreted as a class of two characters
\r
1002 ("W" and "-") followed by a literal string "46]", so it would match "W46]" or
\r
1003 "-46]". However, if the "]" is escaped with a backslash it is interpreted as
\r
1004 the end of range, so [W-\\]46] is interpreted as a single class containing a
\r
1005 range followed by two separate characters. The octal or hexadecimal
\r
1006 representation of "]" can also be used to end a range.
\r
1008 Ranges operate in ASCII collating sequence. They can also be used for
\r
1009 characters specified numerically, for example [\\000-\\037]. If a range that
\r
1010 includes letters is used when caseless matching is set, it matches the letters
\r
1011 in either case. For example, [W-c] is equivalent to [][\\^_`wxyzabc], matched
\r
1012 caselessly, and if character tables for the "fr" locale are in use,
\r
1013 [\\xc8-\\xcb] matches accented E characters in both cases.
\r
1015 The character types \\d, \\D, \\s, \\S, \\w, and \\W may also appear in a
\r
1016 character class, and add the characters that they match to the class. For
\r
1017 example, [\\dABCDEF] matches any hexadecimal digit. A circumflex can
\r
1018 conveniently be used with the upper case character types to specify a more
\r
1019 restricted set of characters than the matching lower case type. For example,
\r
1020 the class [^\\W_] matches any letter or digit, but not underscore.
\r
1022 All non-alphameric characters other than \\, -, ^ (at the start) and the
\r
1023 terminating ] are non-special in character classes, but it does no harm if they
\r
1027 .SH POSIX CHARACTER CLASSES
\r
1028 Perl 5.6 (not yet released at the time of writing) is going to support the
\r
1029 POSIX notation for character classes, which uses names enclosed by [: and :]
\r
1030 within the enclosing square brackets. PCRE supports this notation. For example,
\r
1034 matches "0", "1", any alphabetic character, or "%". The supported class names
\r
1037 alnum letters and digits
\r
1039 ascii character codes 0 - 127
\r
1040 cntrl control characters
\r
1041 digit decimal digits (same as \\d)
\r
1042 graph printing characters, excluding space
\r
1043 lower lower case letters
\r
1044 print printing characters, including space
\r
1045 punct printing characters, excluding letters and digits
\r
1046 space white space (same as \\s)
\r
1047 upper upper case letters
\r
1048 word "word" characters (same as \\w)
\r
1049 xdigit hexadecimal digits
\r
1051 The names "ascii" and "word" are Perl extensions. Another Perl extension is
\r
1052 negation, which is indicated by a ^ character after the colon. For example,
\r
1056 matches "1", "2", or any non-digit. PCRE (and Perl) also recogize the POSIX
\r
1057 syntax [.ch.] and [=ch=] where "ch" is a "collating element", but these are not
\r
1058 supported, and an error is given if they are encountered.
\r
1062 Vertical bar characters are used to separate alternative patterns. For example,
\r
1067 matches either "gilbert" or "sullivan". Any number of alternatives may appear,
\r
1068 and an empty alternative is permitted (matching the empty string).
\r
1069 The matching process tries each alternative in turn, from left to right,
\r
1070 and the first one that succeeds is used. If the alternatives are within a
\r
1071 subpattern (defined below), "succeeds" means matching the rest of the main
\r
1072 pattern as well as the alternative in the subpattern.
\r
1075 .SH INTERNAL OPTION SETTING
\r
1076 The settings of PCRE_CASELESS, PCRE_MULTILINE, PCRE_DOTALL, and PCRE_EXTENDED
\r
1077 can be changed from within the pattern by a sequence of Perl option letters
\r
1078 enclosed between "(?" and ")". The option letters are
\r
1080 i for PCRE_CASELESS
\r
1081 m for PCRE_MULTILINE
\r
1083 x for PCRE_EXTENDED
\r
1085 For example, (?im) sets caseless, multiline matching. It is also possible to
\r
1086 unset these options by preceding the letter with a hyphen, and a combined
\r
1087 setting and unsetting such as (?im-sx), which sets PCRE_CASELESS and
\r
1088 PCRE_MULTILINE while unsetting PCRE_DOTALL and PCRE_EXTENDED, is also
\r
1089 permitted. If a letter appears both before and after the hyphen, the option is
\r
1092 The scope of these option changes depends on where in the pattern the setting
\r
1093 occurs. For settings that are outside any subpattern (defined below), the
\r
1094 effect is the same as if the options were set or unset at the start of
\r
1095 matching. The following patterns all behave in exactly the same way:
\r
1102 which in turn is the same as compiling the pattern abc with PCRE_CASELESS set.
\r
1103 In other words, such "top level" settings apply to the whole pattern (unless
\r
1104 there are other changes inside subpatterns). If there is more than one setting
\r
1105 of the same option at top level, the rightmost setting is used.
\r
1107 If an option change occurs inside a subpattern, the effect is different. This
\r
1108 is a change of behaviour in Perl 5.005. An option change inside a subpattern
\r
1109 affects only that part of the subpattern that follows it, so
\r
1113 matches abc and aBc and no other strings (assuming PCRE_CASELESS is not used).
\r
1114 By this means, options can be made to have different settings in different
\r
1115 parts of the pattern. Any changes made in one alternative do carry on
\r
1116 into subsequent branches within the same subpattern. For example,
\r
1120 matches "ab", "aB", "c", and "C", even though when matching "C" the first
\r
1121 branch is abandoned before the option setting. This is because the effects of
\r
1122 option settings happen at compile time. There would be some very weird
\r
1123 behaviour otherwise.
\r
1125 The PCRE-specific options PCRE_UNGREEDY and PCRE_EXTRA can be changed in the
\r
1126 same way as the Perl-compatible options by using the characters U and X
\r
1127 respectively. The (?X) flag setting is special in that it must always occur
\r
1128 earlier in the pattern than any of the additional features it turns on, even
\r
1129 when it is at top level. It is best put at the start.
\r
1133 Subpatterns are delimited by parentheses (round brackets), which can be nested.
\r
1134 Marking part of a pattern as a subpattern does two things:
\r
1136 1. It localizes a set of alternatives. For example, the pattern
\r
1138 cat(aract|erpillar|)
\r
1140 matches one of the words "cat", "cataract", or "caterpillar". Without the
\r
1141 parentheses, it would match "cataract", "erpillar" or the empty string.
\r
1143 2. It sets up the subpattern as a capturing subpattern (as defined above).
\r
1144 When the whole pattern matches, that portion of the subject string that matched
\r
1145 the subpattern is passed back to the caller via the \fIovector\fR argument of
\r
1146 \fBpcre_exec()\fR. Opening parentheses are counted from left to right (starting
\r
1147 from 1) to obtain the numbers of the capturing subpatterns.
\r
1149 For example, if the string "the red king" is matched against the pattern
\r
1151 the ((red|white) (king|queen))
\r
1153 the captured substrings are "red king", "red", and "king", and are numbered 1,
\r
1156 The fact that plain parentheses fulfil two functions is not always helpful.
\r
1157 There are often times when a grouping subpattern is required without a
\r
1158 capturing requirement. If an opening parenthesis is followed by "?:", the
\r
1159 subpattern does not do any capturing, and is not counted when computing the
\r
1160 number of any subsequent capturing subpatterns. For example, if the string "the
\r
1161 white queen" is matched against the pattern
\r
1163 the ((?:red|white) (king|queen))
\r
1165 the captured substrings are "white queen" and "queen", and are numbered 1 and
\r
1166 2. The maximum number of captured substrings is 99, and the maximum number of
\r
1167 all subpatterns, both capturing and non-capturing, is 200.
\r
1169 As a convenient shorthand, if any option settings are required at the start of
\r
1170 a non-capturing subpattern, the option letters may appear between the "?" and
\r
1171 the ":". Thus the two patterns
\r
1173 (?i:saturday|sunday)
\r
1174 (?:(?i)saturday|sunday)
\r
1176 match exactly the same set of strings. Because alternative branches are tried
\r
1177 from left to right, and options are not reset until the end of the subpattern
\r
1178 is reached, an option setting in one branch does affect subsequent branches, so
\r
1179 the above patterns match "SUNDAY" as well as "Saturday".
\r
1183 Repetition is specified by quantifiers, which can follow any of the following
\r
1186 a single character, possibly escaped
\r
1187 the . metacharacter
\r
1189 a back reference (see next section)
\r
1190 a parenthesized subpattern (unless it is an assertion - see below)
\r
1192 The general repetition quantifier specifies a minimum and maximum number of
\r
1193 permitted matches, by giving the two numbers in curly brackets (braces),
\r
1194 separated by a comma. The numbers must be less than 65536, and the first must
\r
1195 be less than or equal to the second. For example:
\r
1199 matches "zz", "zzz", or "zzzz". A closing brace on its own is not a special
\r
1200 character. If the second number is omitted, but the comma is present, there is
\r
1201 no upper limit; if the second number and the comma are both omitted, the
\r
1202 quantifier specifies an exact number of required matches. Thus
\r
1206 matches at least 3 successive vowels, but may match many more, while
\r
1210 matches exactly 8 digits. An opening curly bracket that appears in a position
\r
1211 where a quantifier is not allowed, or one that does not match the syntax of a
\r
1212 quantifier, is taken as a literal character. For example, {,6} is not a
\r
1213 quantifier, but a literal string of four characters.
\r
1215 The quantifier {0} is permitted, causing the expression to behave as if the
\r
1216 previous item and the quantifier were not present.
\r
1218 For convenience (and historical compatibility) the three most common
\r
1219 quantifiers have single-character abbreviations:
\r
1221 * is equivalent to {0,}
\r
1222 + is equivalent to {1,}
\r
1223 ? is equivalent to {0,1}
\r
1225 It is possible to construct infinite loops by following a subpattern that can
\r
1226 match no characters with a quantifier that has no upper limit, for example:
\r
1230 Earlier versions of Perl and PCRE used to give an error at compile time for
\r
1231 such patterns. However, because there are cases where this can be useful, such
\r
1232 patterns are now accepted, but if any repetition of the subpattern does in fact
\r
1233 match no characters, the loop is forcibly broken.
\r
1235 By default, the quantifiers are "greedy", that is, they match as much as
\r
1236 possible (up to the maximum number of permitted times), without causing the
\r
1237 rest of the pattern to fail. The classic example of where this gives problems
\r
1238 is in trying to match comments in C programs. These appear between the
\r
1239 sequences /* and */ and within the sequence, individual * and / characters may
\r
1240 appear. An attempt to match C comments by applying the pattern
\r
1246 /* first command */ not comment /* second comment */
\r
1248 fails, because it matches the entire string owing to the greediness of the .*
\r
1251 However, if a quantifier is followed by a question mark, it ceases to be
\r
1252 greedy, and instead matches the minimum number of times possible, so the
\r
1257 does the right thing with the C comments. The meaning of the various
\r
1258 quantifiers is not otherwise changed, just the preferred number of matches.
\r
1259 Do not confuse this use of question mark with its use as a quantifier in its
\r
1260 own right. Because it has two uses, it can sometimes appear doubled, as in
\r
1264 which matches one digit by preference, but can match two if that is the only
\r
1265 way the rest of the pattern matches.
\r
1267 If the PCRE_UNGREEDY option is set (an option which is not available in Perl),
\r
1268 the quantifiers are not greedy by default, but individual ones can be made
\r
1269 greedy by following them with a question mark. In other words, it inverts the
\r
1270 default behaviour.
\r
1272 When a parenthesized subpattern is quantified with a minimum repeat count that
\r
1273 is greater than 1 or with a limited maximum, more store is required for the
\r
1274 compiled pattern, in proportion to the size of the minimum or maximum.
\r
1276 If a pattern starts with .* or .{0,} and the PCRE_DOTALL option (equivalent
\r
1277 to Perl's /s) is set, thus allowing the . to match newlines, the pattern is
\r
1278 implicitly anchored, because whatever follows will be tried against every
\r
1279 character position in the subject string, so there is no point in retrying the
\r
1280 overall match at any position after the first. PCRE treats such a pattern as
\r
1281 though it were preceded by \\A. In cases where it is known that the subject
\r
1282 string contains no newlines, it is worth setting PCRE_DOTALL when the pattern
\r
1283 begins with .* in order to obtain this optimization, or alternatively using ^
\r
1284 to indicate anchoring explicitly.
\r
1286 When a capturing subpattern is repeated, the value captured is the substring
\r
1287 that matched the final iteration. For example, after
\r
1289 (tweedle[dume]{3}\\s*)+
\r
1291 has matched "tweedledum tweedledee" the value of the captured substring is
\r
1292 "tweedledee". However, if there are nested capturing subpatterns, the
\r
1293 corresponding captured values may have been set in previous iterations. For
\r
1298 matches "aba" the value of the second captured substring is "b".
\r
1301 .SH BACK REFERENCES
\r
1302 Outside a character class, a backslash followed by a digit greater than 0 (and
\r
1303 possibly further digits) is a back reference to a capturing subpattern earlier
\r
1304 (i.e. to its left) in the pattern, provided there have been that many previous
\r
1305 capturing left parentheses.
\r
1307 However, if the decimal number following the backslash is less than 10, it is
\r
1308 always taken as a back reference, and causes an error only if there are not
\r
1309 that many capturing left parentheses in the entire pattern. In other words, the
\r
1310 parentheses that are referenced need not be to the left of the reference for
\r
1311 numbers less than 10. See the section entitled "Backslash" above for further
\r
1312 details of the handling of digits following a backslash.
\r
1314 A back reference matches whatever actually matched the capturing subpattern in
\r
1315 the current subject string, rather than anything matching the subpattern
\r
1316 itself. So the pattern
\r
1318 (sens|respons)e and \\1ibility
\r
1320 matches "sense and sensibility" and "response and responsibility", but not
\r
1321 "sense and responsibility". If caseful matching is in force at the time of the
\r
1322 back reference, the case of letters is relevant. For example,
\r
1326 matches "rah rah" and "RAH RAH", but not "RAH rah", even though the original
\r
1327 capturing subpattern is matched caselessly.
\r
1329 There may be more than one back reference to the same subpattern. If a
\r
1330 subpattern has not actually been used in a particular match, any back
\r
1331 references to it always fail. For example, the pattern
\r
1335 always fails if it starts to match "a" rather than "bc". Because there may be
\r
1336 up to 99 back references, all digits following the backslash are taken
\r
1337 as part of a potential back reference number. If the pattern continues with a
\r
1338 digit character, some delimiter must be used to terminate the back reference.
\r
1339 If the PCRE_EXTENDED option is set, this can be whitespace. Otherwise an empty
\r
1340 comment can be used.
\r
1342 A back reference that occurs inside the parentheses to which it refers fails
\r
1343 when the subpattern is first used, so, for example, (a\\1) never matches.
\r
1344 However, such references can be useful inside repeated subpatterns. For
\r
1345 example, the pattern
\r
1349 matches any number of "a"s and also "aba", "ababbaa" etc. At each iteration of
\r
1350 the subpattern, the back reference matches the character string corresponding
\r
1351 to the previous iteration. In order for this to work, the pattern must be such
\r
1352 that the first iteration does not need to match the back reference. This can be
\r
1353 done using alternation, as in the example above, or by a quantifier with a
\r
1358 An assertion is a test on the characters following or preceding the current
\r
1359 matching point that does not actually consume any characters. The simple
\r
1360 assertions coded as \\b, \\B, \\A, \\Z, \\z, ^ and $ are described above. More
\r
1361 complicated assertions are coded as subpatterns. There are two kinds: those
\r
1362 that look ahead of the current position in the subject string, and those that
\r
1365 An assertion subpattern is matched in the normal way, except that it does not
\r
1366 cause the current matching position to be changed. Lookahead assertions start
\r
1367 with (?= for positive assertions and (?! for negative assertions. For example,
\r
1371 matches a word followed by a semicolon, but does not include the semicolon in
\r
1376 matches any occurrence of "foo" that is not followed by "bar". Note that the
\r
1377 apparently similar pattern
\r
1381 does not find an occurrence of "bar" that is preceded by something other than
\r
1382 "foo"; it finds any occurrence of "bar" whatsoever, because the assertion
\r
1383 (?!foo) is always true when the next three characters are "bar". A
\r
1384 lookbehind assertion is needed to achieve this effect.
\r
1386 Lookbehind assertions start with (?<= for positive assertions and (?<! for
\r
1387 negative assertions. For example,
\r
1391 does find an occurrence of "bar" that is not preceded by "foo". The contents of
\r
1392 a lookbehind assertion are restricted such that all the strings it matches must
\r
1393 have a fixed length. However, if there are several alternatives, they do not
\r
1394 all have to have the same fixed length. Thus
\r
1396 (?<=bullock|donkey)
\r
1402 causes an error at compile time. Branches that match different length strings
\r
1403 are permitted only at the top level of a lookbehind assertion. This is an
\r
1404 extension compared with Perl 5.005, which requires all branches to match the
\r
1405 same length of string. An assertion such as
\r
1409 is not permitted, because its single top-level branch can match two different
\r
1410 lengths, but it is acceptable if rewritten to use two top-level branches:
\r
1414 The implementation of lookbehind assertions is, for each alternative, to
\r
1415 temporarily move the current position back by the fixed width and then try to
\r
1416 match. If there are insufficient characters before the current position, the
\r
1417 match is deemed to fail. Lookbehinds in conjunction with once-only subpatterns
\r
1418 can be particularly useful for matching at the ends of strings; an example is
\r
1419 given at the end of the section on once-only subpatterns.
\r
1421 Several assertions (of any sort) may occur in succession. For example,
\r
1423 (?<=\\d{3})(?<!999)foo
\r
1425 matches "foo" preceded by three digits that are not "999". Notice that each of
\r
1426 the assertions is applied independently at the same point in the subject
\r
1427 string. First there is a check that the previous three characters are all
\r
1428 digits, and then there is a check that the same three characters are not "999".
\r
1429 This pattern does \fInot\fR match "foo" preceded by six characters, the first
\r
1430 of which are digits and the last three of which are not "999". For example, it
\r
1431 doesn't match "123abcfoo". A pattern to do that is
\r
1433 (?<=\\d{3}...)(?<!999)foo
\r
1435 This time the first assertion looks at the preceding six characters, checking
\r
1436 that the first three are digits, and then the second assertion checks that the
\r
1437 preceding three characters are not "999".
\r
1439 Assertions can be nested in any combination. For example,
\r
1441 (?<=(?<!foo)bar)baz
\r
1443 matches an occurrence of "baz" that is preceded by "bar" which in turn is not
\r
1444 preceded by "foo", while
\r
1446 (?<=\\d{3}(?!999)...)foo
\r
1448 is another pattern which matches "foo" preceded by three digits and any three
\r
1449 characters that are not "999".
\r
1451 Assertion subpatterns are not capturing subpatterns, and may not be repeated,
\r
1452 because it makes no sense to assert the same thing several times. If any kind
\r
1453 of assertion contains capturing subpatterns within it, these are counted for
\r
1454 the purposes of numbering the capturing subpatterns in the whole pattern.
\r
1455 However, substring capturing is carried out only for positive assertions,
\r
1456 because it does not make sense for negative assertions.
\r
1458 Assertions count towards the maximum of 200 parenthesized subpatterns.
\r
1461 .SH ONCE-ONLY SUBPATTERNS
\r
1462 With both maximizing and minimizing repetition, failure of what follows
\r
1463 normally causes the repeated item to be re-evaluated to see if a different
\r
1464 number of repeats allows the rest of the pattern to match. Sometimes it is
\r
1465 useful to prevent this, either to change the nature of the match, or to cause
\r
1466 it fail earlier than it otherwise might, when the author of the pattern knows
\r
1467 there is no point in carrying on.
\r
1469 Consider, for example, the pattern \\d+foo when applied to the subject line
\r
1473 After matching all 6 digits and then failing to match "foo", the normal
\r
1474 action of the matcher is to try again with only 5 digits matching the \\d+
\r
1475 item, and then with 4, and so on, before ultimately failing. Once-only
\r
1476 subpatterns provide the means for specifying that once a portion of the pattern
\r
1477 has matched, it is not to be re-evaluated in this way, so the matcher would
\r
1478 give up immediately on failing to match "foo" the first time. The notation is
\r
1479 another kind of special parenthesis, starting with (?> as in this example:
\r
1483 This kind of parenthesis "locks up" the part of the pattern it contains once
\r
1484 it has matched, and a failure further into the pattern is prevented from
\r
1485 backtracking into it. Backtracking past it to previous items, however, works as
\r
1488 An alternative description is that a subpattern of this type matches the string
\r
1489 of characters that an identical standalone pattern would match, if anchored at
\r
1490 the current point in the subject string.
\r
1492 Once-only subpatterns are not capturing subpatterns. Simple cases such as the
\r
1493 above example can be thought of as a maximizing repeat that must swallow
\r
1494 everything it can. So, while both \\d+ and \\d+? are prepared to adjust the
\r
1495 number of digits they match in order to make the rest of the pattern match,
\r
1496 (?>\\d+) can only match an entire sequence of digits.
\r
1498 This construction can of course contain arbitrarily complicated subpatterns,
\r
1499 and it can be nested.
\r
1501 Once-only subpatterns can be used in conjunction with lookbehind assertions to
\r
1502 specify efficient matching at the end of the subject string. Consider a simple
\r
1507 when applied to a long string which does not match. Because matching proceeds
\r
1508 from left to right, PCRE will look for each "a" in the subject and then see if
\r
1509 what follows matches the rest of the pattern. If the pattern is specified as
\r
1513 the initial .* matches the entire string at first, but when this fails (because
\r
1514 there is no following "a"), it backtracks to match all but the last character,
\r
1515 then all but the last two characters, and so on. Once again the search for "a"
\r
1516 covers the entire string, from right to left, so we are no better off. However,
\r
1517 if the pattern is written as
\r
1521 there can be no backtracking for the .* item; it can match only the entire
\r
1522 string. The subsequent lookbehind assertion does a single test on the last four
\r
1523 characters. If it fails, the match fails immediately. For long strings, this
\r
1524 approach makes a significant difference to the processing time.
\r
1526 When a pattern contains an unlimited repeat inside a subpattern that can itself
\r
1527 be repeated an unlimited number of times, the use of a once-only subpattern is
\r
1528 the only way to avoid some failing matches taking a very long time indeed.
\r
1531 (\\D+|<\\d+>)*[!?]
\r
1533 matches an unlimited number of substrings that either consist of non-digits, or
\r
1534 digits enclosed in <>, followed by either ! or ?. When it matches, it runs
\r
1535 quickly. However, if it is applied to
\r
1537 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
\r
1539 it takes a long time before reporting failure. This is because the string can
\r
1540 be divided between the two repeats in a large number of ways, and all have to
\r
1541 be tried. (The example used [!?] rather than a single character at the end,
\r
1542 because both PCRE and Perl have an optimization that allows for fast failure
\r
1543 when a single character is used. They remember the last single character that
\r
1544 is required for a match, and fail early if it is not present in the string.)
\r
1545 If the pattern is changed to
\r
1547 ((?>\\D+)|<\\d+>)*[!?]
\r
1549 sequences of non-digits cannot be broken, and failure happens quickly.
\r
1552 .SH CONDITIONAL SUBPATTERNS
\r
1553 It is possible to cause the matching process to obey a subpattern
\r
1554 conditionally or to choose between two alternative subpatterns, depending on
\r
1555 the result of an assertion, or whether a previous capturing subpattern matched
\r
1556 or not. The two possible forms of conditional subpattern are
\r
1558 (?(condition)yes-pattern)
\r
1559 (?(condition)yes-pattern|no-pattern)
\r
1561 If the condition is satisfied, the yes-pattern is used; otherwise the
\r
1562 no-pattern (if present) is used. If there are more than two alternatives in the
\r
1563 subpattern, a compile-time error occurs.
\r
1565 There are two kinds of condition. If the text between the parentheses consists
\r
1566 of a sequence of digits, the condition is satisfied if the capturing subpattern
\r
1567 of that number has previously matched. The number must be greater than zero.
\r
1568 Consider the following pattern, which contains non-significant white space to
\r
1569 make it more readable (assume the PCRE_EXTENDED option) and to divide it into
\r
1570 three parts for ease of discussion:
\r
1572 ( \\( )? [^()]+ (?(1) \\) )
\r
1574 The first part matches an optional opening parenthesis, and if that
\r
1575 character is present, sets it as the first captured substring. The second part
\r
1576 matches one or more characters that are not parentheses. The third part is a
\r
1577 conditional subpattern that tests whether the first set of parentheses matched
\r
1578 or not. If they did, that is, if subject started with an opening parenthesis,
\r
1579 the condition is true, and so the yes-pattern is executed and a closing
\r
1580 parenthesis is required. Otherwise, since no-pattern is not present, the
\r
1581 subpattern matches nothing. In other words, this pattern matches a sequence of
\r
1582 non-parentheses, optionally enclosed in parentheses.
\r
1584 If the condition is not a sequence of digits, it must be an assertion. This may
\r
1585 be a positive or negative lookahead or lookbehind assertion. Consider this
\r
1586 pattern, again containing non-significant white space, and with the two
\r
1587 alternatives on the second line:
\r
1589 (?(?=[^a-z]*[a-z])
\r
1590 \\d{2}-[a-z]{3}-\\d{2} | \\d{2}-\\d{2}-\\d{2} )
\r
1592 The condition is a positive lookahead assertion that matches an optional
\r
1593 sequence of non-letters followed by a letter. In other words, it tests for the
\r
1594 presence of at least one letter in the subject. If a letter is found, the
\r
1595 subject is matched against the first alternative; otherwise it is matched
\r
1596 against the second. This pattern matches strings in one of the two forms
\r
1597 dd-aaa-dd or dd-dd-dd, where aaa are letters and dd are digits.
\r
1601 The sequence (?# marks the start of a comment which continues up to the next
\r
1602 closing parenthesis. Nested parentheses are not permitted. The characters
\r
1603 that make up a comment play no part in the pattern matching at all.
\r
1605 If the PCRE_EXTENDED option is set, an unescaped # character outside a
\r
1606 character class introduces a comment that continues up to the next newline
\r
1607 character in the pattern.
\r
1610 .SH RECURSIVE PATTERNS
\r
1611 Consider the problem of matching a string in parentheses, allowing for
\r
1612 unlimited nested parentheses. Without the use of recursion, the best that can
\r
1613 be done is to use a pattern that matches up to some fixed depth of nesting. It
\r
1614 is not possible to handle an arbitrary nesting depth. Perl 5.6 has provided an
\r
1615 experimental facility that allows regular expressions to recurse (amongst other
\r
1616 things). It does this by interpolating Perl code in the expression at run time,
\r
1617 and the code can refer to the expression itself. A Perl pattern to solve the
\r
1618 parentheses problem can be created like this:
\r
1620 $re = qr{\\( (?: (?>[^()]+) | (?p{$re}) )* \\)}x;
\r
1622 The (?p{...}) item interpolates Perl code at run time, and in this case refers
\r
1623 recursively to the pattern in which it appears. Obviously, PCRE cannot support
\r
1624 the interpolation of Perl code. Instead, the special item (?R) is provided for
\r
1625 the specific case of recursion. This PCRE pattern solves the parentheses
\r
1626 problem (assume the PCRE_EXTENDED option is set so that white space is
\r
1629 \\( ( (?>[^()]+) | (?R) )* \\)
\r
1631 First it matches an opening parenthesis. Then it matches any number of
\r
1632 substrings which can either be a sequence of non-parentheses, or a recursive
\r
1633 match of the pattern itself (i.e. a correctly parenthesized substring). Finally
\r
1634 there is a closing parenthesis.
\r
1636 This particular example pattern contains nested unlimited repeats, and so the
\r
1637 use of a once-only subpattern for matching strings of non-parentheses is
\r
1638 important when applying the pattern to strings that do not match. For example,
\r
1639 when it is applied to
\r
1641 (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()
\r
1643 it yields "no match" quickly. However, if a once-only subpattern is not used,
\r
1644 the match runs for a very long time indeed because there are so many different
\r
1645 ways the + and * repeats can carve up the subject, and all have to be tested
\r
1646 before failure can be reported.
\r
1648 The values set for any capturing subpatterns are those from the outermost level
\r
1649 of the recursion at which the subpattern value is set. If the pattern above is
\r
1654 the value for the capturing parentheses is "ef", which is the last value taken
\r
1655 on at the top level. If additional parentheses are added, giving
\r
1657 \\( ( ( (?>[^()]+) | (?R) )* ) \\)
\r
1660 the string they capture is "ab(cd)ef", the contents of the top level
\r
1661 parentheses. If there are more than 15 capturing parentheses in a pattern, PCRE
\r
1662 has to obtain extra memory to store data during a recursion, which it does by
\r
1663 using \fBpcre_malloc\fR, freeing it via \fBpcre_free\fR afterwards. If no
\r
1664 memory can be obtained, it saves data for the first 15 capturing parentheses
\r
1665 only, as there is no way to give an out-of-memory error from within a
\r
1670 Certain items that may appear in patterns are more efficient than others. It is
\r
1671 more efficient to use a character class like [aeiou] than a set of alternatives
\r
1672 such as (a|e|i|o|u). In general, the simplest construction that provides the
\r
1673 required behaviour is usually the most efficient. Jeffrey Friedl's book
\r
1674 contains a lot of discussion about optimizing regular expressions for efficient
\r
1677 When a pattern begins with .* and the PCRE_DOTALL option is set, the pattern is
\r
1678 implicitly anchored by PCRE, since it can match only at the start of a subject
\r
1679 string. However, if PCRE_DOTALL is not set, PCRE cannot make this optimization,
\r
1680 because the . metacharacter does not then match a newline, and if the subject
\r
1681 string contains newlines, the pattern may match from the character immediately
\r
1682 following one of them instead of from the very start. For example, the pattern
\r
1686 matches the subject "first\\nand second" (where \\n stands for a newline
\r
1687 character) with the first captured substring being "and". In order to do this,
\r
1688 PCRE has to retry the match starting after every newline in the subject.
\r
1690 If you are using such a pattern with subject strings that do not contain
\r
1691 newlines, the best performance is obtained by setting PCRE_DOTALL, or starting
\r
1692 the pattern with ^.* to indicate explicit anchoring. That saves PCRE from
\r
1693 having to scan along the subject looking for a newline to restart at.
\r
1695 Beware of patterns that contain nested indefinite repeats. These can take a
\r
1696 long time to run when applied to a string that does not match. Consider the
\r
1701 This can match "aaaa" in 33 different ways, and this number increases very
\r
1702 rapidly as the string gets longer. (The * repeat can match 0, 1, 2, 3, or 4
\r
1703 times, and for each of those cases other than 0, the + repeats can match
\r
1704 different numbers of times.) When the remainder of the pattern is such that the
\r
1705 entire match is going to fail, PCRE has in principle to try every possible
\r
1706 variation, and this can take an extremely long time.
\r
1708 An optimization catches some of the more simple cases such as
\r
1712 where a literal character follows. Before embarking on the standard matching
\r
1713 procedure, PCRE checks that there is a "b" later in the subject string, and if
\r
1714 there is not, it fails the match immediately. However, when there is no
\r
1715 following literal this optimization cannot be used. You can see the difference
\r
1716 by comparing the behaviour of
\r
1720 with the pattern above. The former gives a failure almost instantly when
\r
1721 applied to a whole line of "a" characters, whereas the latter takes an
\r
1722 appreciable time with strings longer than about 20 characters.
\r
1726 Starting at release 3.3, PCRE has some support for character strings encoded
\r
1727 in the UTF-8 format. This is incomplete, and is regarded as experimental. In
\r
1728 order to use it, you must configure PCRE to include UTF-8 support in the code,
\r
1729 and, in addition, you must call \fBpcre_compile()\fR with the PCRE_UTF8 option
\r
1730 flag. When you do this, both the pattern and any subject strings that are
\r
1731 matched against it are treated as UTF-8 strings instead of just strings of
\r
1732 bytes, but only in the cases that are mentioned below.
\r
1734 If you compile PCRE with UTF-8 support, but do not use it at run time, the
\r
1735 library will be a bit bigger, but the additional run time overhead is limited
\r
1736 to testing the PCRE_UTF8 flag in several places, so should not be very large.
\r
1738 PCRE assumes that the strings it is given contain valid UTF-8 codes. It does
\r
1739 not diagnose invalid UTF-8 strings. If you pass invalid UTF-8 strings to PCRE,
\r
1740 the results are undefined.
\r
1742 Running with PCRE_UTF8 set causes these changes in the way PCRE works:
\r
1744 1. In a pattern, the escape sequence \\x{...}, where the contents of the braces
\r
1745 is a string of hexadecimal digits, is interpreted as a UTF-8 character whose
\r
1746 code number is the given hexadecimal number, for example: \\x{1234}. This
\r
1747 inserts from one to six literal bytes into the pattern, using the UTF-8
\r
1748 encoding. If a non-hexadecimal digit appears between the braces, the item is
\r
1751 2. The original hexadecimal escape sequence, \\xhh, generates a two-byte UTF-8
\r
1752 character if its value is greater than 127.
\r
1754 3. Repeat quantifiers are NOT correctly handled if they follow a multibyte
\r
1755 character. For example, \\x{100}* and \\xc3+ do not work. If you want to
\r
1756 repeat such characters, you must enclose them in non-capturing parentheses,
\r
1757 for example (?:\\x{100}), at present.
\r
1759 4. The dot metacharacter matches one UTF-8 character instead of a single byte.
\r
1761 5. Unlike literal UTF-8 characters, the dot metacharacter followed by a
\r
1762 repeat quantifier does operate correctly on UTF-8 characters instead of
\r
1765 4. Although the \\x{...} escape is permitted in a character class, characters
\r
1766 whose values are greater than 255 cannot be included in a class.
\r
1768 5. A class is matched against a UTF-8 character instead of just a single byte,
\r
1769 but it can match only characters whose values are less than 256. Characters
\r
1770 with greater values always fail to match a class.
\r
1772 6. Repeated classes work correctly on multiple characters.
\r
1774 7. Classes containing just a single character whose value is greater than 127
\r
1775 (but less than 256), for example, [\\x80] or [^\\x{93}], do not work because
\r
1776 these are optimized into single byte matches. In the first case, of course,
\r
1777 the class brackets are just redundant.
\r
1779 8. Lookbehind assertions move backwards in the subject by a fixed number of
\r
1780 characters instead of a fixed number of bytes. Simple cases have been tested
\r
1781 to work correctly, but there may be hidden gotchas herein.
\r
1783 9. The character types such as \\d and \\w do not work correctly with UTF-8
\r
1784 characters. They continue to test a single byte.
\r
1786 10. Anything not explicitly mentioned here continues to work in bytes rather
\r
1787 than in characters.
\r
1789 The following UTF-8 features of Perl 5.6 are not implemented:
\r
1791 1. The escape sequence \\C to match a single byte.
\r
1793 2. The use of Unicode tables and properties and escapes \\p, \\P, and \\X.
\r
1796 Philip Hazel <ph10@cam.ac.uk>
\r
1798 University Computing Service,
\r
1802 Cambridge CB2 3QG, England.
\r
1804 Phone: +44 1223 334714
\r
1806 Last updated: 28 August 2000,
\r
1808 the 250th anniversary of the death of J.S. Bach.
\r
1810 Copyright (c) 1997-2000 University of Cambridge.
\r