diff options
Diffstat (limited to 'ext/pcre/pcrelib/doc')
-rw-r--r-- | ext/pcre/pcrelib/doc/Tech.Notes | 32 | ||||
-rw-r--r-- | ext/pcre/pcrelib/doc/pcre.txt | 1510 |
2 files changed, 926 insertions, 616 deletions
diff --git a/ext/pcre/pcrelib/doc/Tech.Notes b/ext/pcre/pcrelib/doc/Tech.Notes index aa5398d0fa..21dbe1f9b5 100644 --- a/ext/pcre/pcrelib/doc/Tech.Notes +++ b/ext/pcre/pcrelib/doc/Tech.Notes @@ -1,6 +1,9 @@ Technical Notes about PCRE -------------------------- +These are very rough technical notes that record potentially useful information +about PCRE internals. + Historical note 1 ----------------- @@ -21,13 +24,14 @@ the pattern, as is expected in Unix and Perl-style regular expressions. Historical note 2 ----------------- -By contrast, the code originally written by Henry Spencer and subsequently -heavily modified for Perl actually compiles the expression twice: once in a -dummy mode in order to find out how much store will be needed, and then for -real. The execution function operates by backtracking and maximizing (or, -optionally, minimizing in Perl) the amount of the subject that matches -individual wild portions of the pattern. This is an "NFA algorithm" in Friedl's -terminology. +By contrast, the code originally written by Henry Spencer (which was +subsequently heavily modified for Perl) compiles the expression twice: once in +a dummy mode in order to find out how much store will be needed, and then for +real. (The Perl version probably doesn't do this any more; I'm talking about +the original library.) The execution function operates by backtracking and +maximizing (or, optionally, minimizing in Perl) the amount of the subject that +matches individual wild portions of the pattern. This is an "NFA algorithm" in +Friedl's terminology. OK, here's the real stuff ------------------------- @@ -43,7 +47,7 @@ then a second pass to do the real compile - which may use a bit less than the predicted amount of store. The idea is that this is going to turn out faster because the first pass is degenerate and the second pass can just store stuff straight into the vector, which it knows is big enough. It does make the -compiling functions bigger, of course, but they have got quite big anyway to +compiling functions bigger, of course, but they have become quite big anyway to handle all the Perl stuff. Traditional matching function @@ -63,7 +67,7 @@ pcre_dfa_exec(). This implements a DFA matching algorithm that searches simultaneously for all possible matches that start at one point in the subject string. (Going back to my roots: see Historical Note 1 above.) This function intreprets the same compiled pattern data as pcre_exec(); however, not all the -facilities are available, and those that are don't always work in quite the +facilities are available, and those that are do not always work in quite the same way. See the user documentation for details. Format of compiled patterns @@ -157,10 +161,12 @@ Match by Unicode property OP_PROP and OP_NOTPROP are used for positive and negative matches of a character by testing its Unicode property (the \p and \P escape sequences). -Each is followed by a single byte that encodes the desired property value. +Each is followed by two bytes that encode the desired property as a type and a +value. -Repeats of these items use the OP_TYPESTAR etc. set of opcodes, followed by two -bytes: OP_PROP or OP_NOTPROP and then the desired property value. +Repeats of these items use the OP_TYPESTAR etc. set of opcodes, followed by +three bytes: OP_PROP or OP_NOTPROP and then the desired property type and +value. Matching literal characters @@ -339,4 +345,4 @@ at compile time, and so does not cause anything to be put into the compiled data. Philip Hazel -January 2006 +June 2006 diff --git a/ext/pcre/pcrelib/doc/pcre.txt b/ext/pcre/pcrelib/doc/pcre.txt index fe57de4731..d6c204b574 100644 --- a/ext/pcre/pcrelib/doc/pcre.txt +++ b/ext/pcre/pcrelib/doc/pcre.txt @@ -81,6 +81,7 @@ USER DOCUMENTATION pcreposix the POSIX-compatible C API pcreprecompile details of saving and re-using precompiled patterns pcresample discussion of the sample program + pcrestack discussion of stack usage pcretest description of the pcretest testing command In addition, in the "man" and HTML formats, there is a short page for @@ -100,19 +101,24 @@ LIMITATIONS In these cases the limit is substantially larger. However, the speed of execution will be slower. - All values in repeating quantifiers must be less than 65536. The maxi- - mum number of capturing subpatterns is 65535. + All values in repeating quantifiers must be less than 65536. The maxi- + mum compiled length of subpattern with an explicit repeat count is + 30000 bytes. The maximum number of capturing subpatterns is 65535. - There is no limit to the number of non-capturing subpatterns, but the - maximum depth of nesting of all kinds of parenthesized subpattern, + There is no limit to the number of non-capturing subpatterns, but the + maximum depth of nesting of all kinds of parenthesized subpattern, including capturing subpatterns, assertions, and other types of subpat- tern, is 200. + The maximum length of name for a named subpattern is 32, and the maxi- + mum number of named subpatterns is 10000. + The maximum length of a subject string is the largest positive number that an integer variable can hold. However, when using the traditional matching function, PCRE uses recursion to handle subpatterns and indef- inite repetition. This means that the available stack space may limit the size of a subject string that can be processed by certain patterns. + For a discussion of stack issues, see the pcrestack documentation. UTF-8 AND UNICODE PROPERTY SUPPORT @@ -162,37 +168,40 @@ UTF-8 AND UNICODE PROPERTY SUPPORT 2. An unbraced hexadecimal escape sequence (such as \xb3) matches a two-byte UTF-8 character if the value is greater than 127. - 3. Repeat quantifiers apply to complete UTF-8 characters, not to indi- + 3. Octal numbers up to \777 are recognized, and match two-byte UTF-8 + characters for values greater than \177. + + 4. Repeat quantifiers apply to complete UTF-8 characters, not to indi- vidual bytes, for example: \x{100}{3}. - 4. The dot metacharacter matches one UTF-8 character instead of a sin- + 5. The dot metacharacter matches one UTF-8 character instead of a sin- gle byte. - 5. The escape sequence \C can be used to match a single byte in UTF-8 - mode, but its use can lead to some strange effects. This facility is + 6. The escape sequence \C can be used to match a single byte in UTF-8 + mode, but its use can lead to some strange effects. This facility is not available in the alternative matching function, pcre_dfa_exec(). - 6. The character escapes \b, \B, \d, \D, \s, \S, \w, and \W correctly - test characters of any code value, but the characters that PCRE recog- - nizes as digits, spaces, or word characters remain the same set as + 7. The character escapes \b, \B, \d, \D, \s, \S, \w, and \W correctly + test characters of any code value, but the characters that PCRE recog- + nizes as digits, spaces, or word characters remain the same set as before, all with values less than 256. This remains true even when PCRE - includes Unicode property support, because to do otherwise would slow - down PCRE in many common cases. If you really want to test for a wider - sense of, say, "digit", you must use Unicode property tests such as + includes Unicode property support, because to do otherwise would slow + down PCRE in many common cases. If you really want to test for a wider + sense of, say, "digit", you must use Unicode property tests such as \p{Nd}. - 7. Similarly, characters that match the POSIX named character classes + 8. Similarly, characters that match the POSIX named character classes are all low-valued characters. - 8. Case-insensitive matching applies only to characters whose values - are less than 128, unless PCRE is built with Unicode property support. - Even when Unicode property support is available, PCRE still uses its - own character tables when checking the case of low-valued characters, - so as not to degrade performance. The Unicode property information is + 9. Case-insensitive matching applies only to characters whose values + are less than 128, unless PCRE is built with Unicode property support. + Even when Unicode property support is available, PCRE still uses its + own character tables when checking the case of low-valued characters, + so as not to degrade performance. The Unicode property information is used only for characters with higher values. Even when Unicode property support is available, PCRE supports case-insensitive matching only when - there is a one-to-one mapping between a letter's cases. There are a - small number of many-to-one mappings in Unicode; these are not sup- + there is a one-to-one mapping between a letter's cases. There are a + small number of many-to-one mappings in Unicode; these are not sup- ported by PCRE. @@ -202,11 +211,11 @@ AUTHOR University Computing Service, Cambridge CB2 3QG, England. - Putting an actual email address here seems to have been a spam magnet, + Putting an actual email address here seems to have been a spam magnet, so I've taken it away. If you want to email me, use my initial and sur- name, separated by a dot, at the domain ucs.cam.ac.uk. -Last updated: 24 January 2006 +Last updated: 05 June 2006 Copyright (c) 1997-2006 University of Cambridge. ------------------------------------------------------------------------------ @@ -281,15 +290,25 @@ UNICODE CHARACTER PROPERTY SUPPORT CODE VALUE OF NEWLINE - By default, PCRE treats character 10 (linefeed) as the newline charac- - ter. This is the normal newline character on Unix-like systems. You can - compile PCRE to use character 13 (carriage return) instead by adding + By default, PCRE interprets character 10 (linefeed, LF) as indicating + the end of a line. This is the normal newline character on Unix-like + systems. You can compile PCRE to use character 13 (carriage return, CR) + instead, by adding --enable-newline-is-cr - to the configure command. For completeness there is also a --enable- - newline-is-lf option, which explicitly specifies linefeed as the new- - line character. + to the configure command. There is also a --enable-newline-is-lf + option, which explicitly specifies linefeed as the newline character. + + Alternatively, you can specify that line endings are to be indicated by + the two character sequence CRLF. If you want this, add + + --enable-newline-is-crlf + + to the configure command. Whatever line ending convention is selected + when PCRE is built can be overridden when the library functions are + called. At build time it is conventional to use the standard for your + operating system. BUILDING SHARED AND STATIC LIBRARIES @@ -320,23 +339,6 @@ POSIX MALLOC USAGE to the configure command. -LIMITING PCRE RESOURCE USAGE - - Internally, PCRE has a function called match(), which it calls repeat- - edly (possibly recursively) when matching a pattern with the - pcre_exec() function. By controlling the maximum number of times this - function may be called during a single matching operation, a limit can - be placed on the resources used by a single call to pcre_exec(). The - limit can be changed at run time, as described in the pcreapi documen- - tation. The default is 10 million, but this can be changed by adding a - setting such as - - --with-match-limit=500000 - - to the configure command. This setting has no effect on the - pcre_dfa_exec() matching function. - - HANDLING VERY LARGE PATTERNS Within a compiled pattern, offset values are used to point from one @@ -366,10 +368,12 @@ AVOIDING EXCESSIVE STACK USAGE ing by making recursive calls to an internal function called match(). In environments where the size of the stack is limited, this can se- verely limit PCRE's operation. (The Unix environment does not usually - suffer from this problem.) An alternative approach that uses memory - from the heap to remember data, instead of using recursive function - calls, has been implemented to work round this problem. If you want to - build a version of PCRE that works this way, add + suffer from this problem, but it may sometimes be necessary to increase + the maximum stack size. There is a discussion in the pcrestack docu- + mentation.) An alternative approach to recursion that uses memory from + the heap to remember data, instead of using recursive function calls, + has been implemented to work round the problem of limited stack size. + If you want to build a version of PCRE that works this way, add --disable-stack-for-recursion @@ -384,19 +388,49 @@ AVOIDING EXCESSIVE STACK USAGE function; it is not relevant for the the pcre_dfa_exec() function. +LIMITING PCRE RESOURCE USAGE + + Internally, PCRE has a function called match(), which it calls repeat- + edly (sometimes recursively) when matching a pattern with the + pcre_exec() function. By controlling the maximum number of times this + function may be called during a single matching operation, a limit can + be placed on the resources used by a single call to pcre_exec(). The + limit can be changed at run time, as described in the pcreapi documen- + tation. The default is 10 million, but this can be changed by adding a + setting such as + + --with-match-limit=500000 + + to the configure command. This setting has no effect on the + pcre_dfa_exec() matching function. + + In some environments it is desirable to limit the depth of recursive + calls of match() more strictly than the total number of calls, in order + to restrict the maximum amount of stack (or heap, if --disable-stack- + for-recursion is specified) that is used. A second limit controls this; + it defaults to the value that is set for --with-match-limit, which + imposes no additional constraints. However, you can set a lower limit + by adding, for example, + + --with-match-limit-recursion=10000 + + to the configure command. This value can also be overridden at run + time. + + USING EBCDIC CODE - PCRE assumes by default that it will run in an environment where the - character code is ASCII (or Unicode, which is a superset of ASCII). - PCRE can, however, be compiled to run in an EBCDIC environment by + PCRE assumes by default that it will run in an environment where the + character code is ASCII (or Unicode, which is a superset of ASCII). + PCRE can, however, be compiled to run in an EBCDIC environment by adding --enable-ebcdic to the configure command. -Last updated: 15 August 2005 -Copyright (c) 1997-2005 University of Cambridge. +Last updated: 06 June 2006 +Copyright (c) 1997-2006 University of Cambridge. ------------------------------------------------------------------------------ @@ -441,9 +475,9 @@ REGULAR EXPRESSIONS AS TREES resented as a tree structure. An unlimited repetition in the pattern makes the tree of infinite size, but it is still a tree. Matching the pattern to a given subject string (from a given starting point) can be - thought of as a search of the tree. There are two standard ways to - search a tree: depth-first and breadth-first, and these correspond to - the two matching algorithms provided by PCRE. + thought of as a search of the tree. There are two ways to search a + tree: depth-first and breadth-first, and these correspond to the two + matching algorithms provided by PCRE. THE STANDARD MATCHING ALGORITHM @@ -563,8 +597,8 @@ DISADVANTAGES OF THE DFA ALGORITHM but does not provide the advantage that it does for the standard algo- rithm. -Last updated: 28 February 2005 -Copyright (c) 1997-2005 University of Cambridge. +Last updated: 06 June 2006 +Copyright (c) 1997-2006 University of Cambridge. ------------------------------------------------------------------------------ @@ -617,6 +651,9 @@ PCRE NATIVE API int pcre_get_stringnumber(const pcre *code, const char *name); + int pcre_get_stringtable_entries(const pcre *code, + const char *name, char **first, char **last); + int pcre_get_substring(const char *subject, int *ovector, int stringcount, int stringnumber, const char **stringptr); @@ -677,11 +714,11 @@ PCRE API OVERVIEW A second matching function, pcre_dfa_exec(), which is not Perl-compati- ble, is also provided. This uses a different algorithm for the match- - ing. This allows it to find all possible matches (at a given point in - the subject), not just one. However, this algorithm does not return - captured substrings. A description of the two matching algorithms and - their advantages and disadvantages is given in the pcrematching docu- - mentation. + ing. The alternative algorithm finds all possible matches (at a given + point in the subject). However, this algorithm does not return captured + substrings. A description of the two matching algorithms and their + advantages and disadvantages is given in the pcrematching documenta- + tion. In addition to the main compiling and matching functions, there are convenience functions for extracting captured substrings from a subject @@ -693,6 +730,7 @@ PCRE API OVERVIEW pcre_get_named_substring() pcre_get_substring_list() pcre_get_stringnumber() + pcre_get_stringtable_entries() pcre_free_substring() and pcre_free_substring_list() are also provided, to free the memory used for extracted strings. @@ -724,12 +762,15 @@ PCRE API OVERVIEW indirections to memory management functions. These special functions are used only when PCRE is compiled to use the heap for remembering data, instead of recursive function calls, when running the pcre_exec() - function. This is a non-standard way of building PCRE, for use in envi- - ronments that have limited stacks. Because of the greater use of memory - management, it runs more slowly. Separate functions are provided so - that special-purpose external code can be used for this case. When - used, these functions are always called in a stack-like manner (last - obtained, first freed), and always for memory blocks of the same size. + function. See the pcrebuild documentation for details of how to do + this. It is a non-standard way of building PCRE, for use in environ- + ments that have limited stacks. Because of the greater use of memory + management, it runs more slowly. Separate functions are provided so + that special-purpose external code can be used for this case. When + used, these functions are always called in a stack-like manner (last + obtained, first freed), and always for memory blocks of the same size. + There is a discussion about PCRE's stack usage in the pcrestack docu- + mentation. The global variable pcre_callout initially contains NULL. It can be set by the caller to a "callout" function, which PCRE will then call at @@ -737,14 +778,27 @@ PCRE API OVERVIEW pcrecallout documentation. +NEWLINES + PCRE supports three different conventions for indicating line breaks in + strings: a single CR character, a single LF character, or the two-char- + acter sequence CRLF. All three are used as "standard" by different + operating systems. When PCRE is built, a default can be specified. The + default default is LF, which is the Unix standard. When PCRE is run, + the default can be overridden, either when a pattern is compiled, or + when it is matched. + + In the PCRE documentation the word "newline" is used to mean "the char- + acter or pair of characters that indicate a line break". + + MULTITHREADING - The PCRE functions can be used in multi-threading applications, with + The PCRE functions can be used in multi-threading applications, with the proviso that the memory management functions pointed to by pcre_malloc, pcre_free, pcre_stack_malloc, and pcre_stack_free, and the callout function pointed to by pcre_callout, are shared by all threads. - The compiled form of a regular expression is not altered during match- + The compiled form of a regular expression is not altered during match- ing, so the same compiled pattern can safely be used by several threads at once. @@ -752,8 +806,8 @@ MULTITHREADING SAVING PRECOMPILED PATTERNS FOR LATER USE The compiled form of a regular expression can be saved and re-used at a - later time, possibly by a different program, and even on a host other - than the one on which it was compiled. Details are given in the + later time, possibly by a different program, and even on a host other + than the one on which it was compiled. Details are given in the pcreprecompile documentation. @@ -761,68 +815,68 @@ CHECKING BUILD-TIME OPTIONS int pcre_config(int what, void *where); - The function pcre_config() makes it possible for a PCRE client to dis- + The function pcre_config() makes it possible for a PCRE client to dis- cover which optional features have been compiled into the PCRE library. - The pcrebuild documentation has more details about these optional fea- + The pcrebuild documentation has more details about these optional fea- tures. - The first argument for pcre_config() is an integer, specifying which + The first argument for pcre_config() is an integer, specifying which information is required; the second argument is a pointer to a variable - into which the information is placed. The following information is + into which the information is placed. The following information is available: PCRE_CONFIG_UTF8 - The output is an integer that is set to one if UTF-8 support is avail- + The output is an integer that is set to one if UTF-8 support is avail- able; otherwise it is set to zero. PCRE_CONFIG_UNICODE_PROPERTIES - The output is an integer that is set to one if support for Unicode + The output is an integer that is set to one if support for Unicode character properties is available; otherwise it is set to zero. PCRE_CONFIG_NEWLINE - The output is an integer that is set to the value of the code that is - used for the newline character. It is either linefeed (10) or carriage - return (13), and should normally be the standard character for your - operating system. + The output is an integer whose value specifies the default character + sequence that is recognized as meaning "newline". The three values that + are supported are: 10 for LF, 13 for CR, and 3338 for CRLF. The default + should normally be the standard sequence for your operating system. PCRE_CONFIG_LINK_SIZE - The output is an integer that contains the number of bytes used for + The output is an integer that contains the number of bytes used for internal linkage in compiled regular expressions. The value is 2, 3, or - 4. Larger values allow larger regular expressions to be compiled, at - the expense of slower matching. The default value of 2 is sufficient - for all but the most massive patterns, since it allows the compiled + 4. Larger values allow larger regular expressions to be compiled, at + the expense of slower matching. The default value of 2 is sufficient + for all but the most massive patterns, since it allows the compiled pattern to be up to 64K in size. PCRE_CONFIG_POSIX_MALLOC_THRESHOLD - The output is an integer that contains the threshold above which the - POSIX interface uses malloc() for output vectors. Further details are + The output is an integer that contains the threshold above which the + POSIX interface uses malloc() for output vectors. Further details are given in the pcreposix documentation. PCRE_CONFIG_MATCH_LIMIT The output is an integer that gives the default limit for the number of - internal matching function calls in a pcre_exec() execution. Further + internal matching function calls in a pcre_exec() execution. Further details are given with pcre_exec() below. PCRE_CONFIG_MATCH_LIMIT_RECURSION - The output is an integer that gives the default limit for the depth of - recursion when calling the internal matching function in a pcre_exec() + The output is an integer that gives the default limit for the depth of + recursion when calling the internal matching function in a pcre_exec() execution. Further details are given with pcre_exec() below. PCRE_CONFIG_STACKRECURSE - The output is an integer that is set to one if internal recursion when + The output is an integer that is set to one if internal recursion when running pcre_exec() is implemented by recursive function calls that use - the stack to remember their state. This is the usual way that PCRE is + the stack to remember their state. This is the usual way that PCRE is compiled. The output is zero if PCRE was compiled to use blocks of data - on the heap instead of recursive function calls. In this case, - pcre_stack_malloc and pcre_stack_free are called to manage memory + on the heap instead of recursive function calls. In this case, + pcre_stack_malloc and pcre_stack_free are called to manage memory blocks on the heap, thus avoiding the use of the stack. @@ -839,55 +893,55 @@ COMPILING A PATTERN Either of the functions pcre_compile() or pcre_compile2() can be called to compile a pattern into an internal form. The only difference between - the two interfaces is that pcre_compile2() has an additional argument, + the two interfaces is that pcre_compile2() has an additional argument, errorcodeptr, via which a numerical error code can be returned. The pattern is a C string terminated by a binary zero, and is passed in - the pattern argument. A pointer to a single block of memory that is - obtained via pcre_malloc is returned. This contains the compiled code + the pattern argument. A pointer to a single block of memory that is + obtained via pcre_malloc is returned. This contains the compiled code and related data. The pcre type is defined for the returned block; this is a typedef for a structure whose contents are not externally defined. - It is up to the caller to free the memory when it is no longer - required. + It is up to the caller to free the memory (via pcre_free) when it is no + longer required. - Although the compiled code of a PCRE regex is relocatable, that is, it + Although the compiled code of a PCRE regex is relocatable, that is, it does not depend on memory location, the complete pcre data block is not - fully relocatable, because it may contain a copy of the tableptr argu- + fully relocatable, because it may contain a copy of the tableptr argu- ment, which is an address (see below). The options argument contains independent bits that affect the compila- - tion. It should be zero if no options are required. The available - options are described below. Some of them, in particular, those that - are compatible with Perl, can also be set and unset from within the - pattern (see the detailed description in the pcrepattern documenta- - tion). For these options, the contents of the options argument speci- - fies their initial settings at the start of compilation and execution. - The PCRE_ANCHORED option can be set at the time of matching as well as - at compile time. + tion. It should be zero if no options are required. The available + options are described below. Some of them, in particular, those that + are compatible with Perl, can also be set and unset from within the + pattern (see the detailed description in the pcrepattern documenta- + tion). For these options, the contents of the options argument speci- + fies their initial settings at the start of compilation and execution. + The PCRE_ANCHORED and PCRE_NEWLINE_xxx options can be set at the time + of matching as well as at compile time. If errptr is NULL, pcre_compile() returns NULL immediately. Otherwise, - if compilation of a pattern fails, pcre_compile() returns NULL, and + if compilation of a pattern fails, pcre_compile() returns NULL, and sets the variable pointed to by errptr to point to a textual error mes- sage. This is a static string that is part of the library. You must not try to free it. The offset from the start of the pattern to the charac- ter where the error was discovered is placed in the variable pointed to - by erroffset, which must not be NULL. If it is, an immediate error is + by erroffset, which must not be NULL. If it is, an immediate error is given. - If pcre_compile2() is used instead of pcre_compile(), and the error- - codeptr argument is not NULL, a non-zero error code number is returned - via this argument in the event of an error. This is in addition to the + If pcre_compile2() is used instead of pcre_compile(), and the error- + codeptr argument is not NULL, a non-zero error code number is returned + via this argument in the event of an error. This is in addition to the textual error message. Error codes and messages are listed below. - If the final argument, tableptr, is NULL, PCRE uses a default set of - character tables that are built when PCRE is compiled, using the - default C locale. Otherwise, tableptr must be an address that is the - result of a call to pcre_maketables(). This value is stored with the - compiled pattern, and used again by pcre_exec(), unless another table + If the final argument, tableptr, is NULL, PCRE uses a default set of + character tables that are built when PCRE is compiled, using the + default C locale. Otherwise, tableptr must be an address that is the + result of a call to pcre_maketables(). This value is stored with the + compiled pattern, and used again by pcre_exec(), unless another table pointer is passed to it. For more discussion, see the section on locale support below. - This code fragment shows a typical straightforward call to pcre_com- + This code fragment shows a typical straightforward call to pcre_com- pile(): pcre *re; @@ -900,86 +954,95 @@ COMPILING A PATTERN &erroffset, /* for error offset */ NULL); /* use default character tables */ - The following names for option bits are defined in the pcre.h header + The following names for option bits are defined in the pcre.h header file: PCRE_ANCHORED If this bit is set, the pattern is forced to be "anchored", that is, it - is constrained to match only at the first matching point in the string - that is being searched (the "subject string"). This effect can also be - achieved by appropriate constructs in the pattern itself, which is the + is constrained to match only at the first matching point in the string + that is being searched (the "subject string"). This effect can also be + achieved by appropriate constructs in the pattern itself, which is the only way to do it in Perl. PCRE_AUTO_CALLOUT If this bit is set, pcre_compile() automatically inserts callout items, - all with number 255, before each pattern item. For discussion of the + all with number 255, before each pattern item. For discussion of the callout facility, see the pcrecallout documentation. PCRE_CASELESS - If this bit is set, letters in the pattern match both upper and lower - case letters. It is equivalent to Perl's /i option, and it can be - changed within a pattern by a (?i) option setting. In UTF-8 mode, PCRE - always understands the concept of case for characters whose values are - less than 128, so caseless matching is always possible. For characters - with higher values, the concept of case is supported if PCRE is com- - piled with Unicode property support, but not otherwise. If you want to - use caseless matching for characters 128 and above, you must ensure - that PCRE is compiled with Unicode property support as well as with + If this bit is set, letters in the pattern match both upper and lower + case letters. It is equivalent to Perl's /i option, and it can be + changed within a pattern by a (?i) option setting. In UTF-8 mode, PCRE + always understands the concept of case for characters whose values are + less than 128, so caseless matching is always possible. For characters + with higher values, the concept of case is supported if PCRE is com- + piled with Unicode property support, but not otherwise. If you want to + use caseless matching for characters 128 and above, you must ensure + that PCRE is compiled with Unicode property support as well as with UTF-8 support. PCRE_DOLLAR_ENDONLY - If this bit is set, a dollar metacharacter in the pattern matches only - at the end of the subject string. Without this option, a dollar also - matches immediately before the final character if it is a newline (but - not before any other newlines). The PCRE_DOLLAR_ENDONLY option is - ignored if PCRE_MULTILINE is set. There is no equivalent to this option - in Perl, and no way to set it within a pattern. + If this bit is set, a dollar metacharacter in the pattern matches only + at the end of the subject string. Without this option, a dollar also + matches immediately before a newline at the end of the string (but not + before any other newlines). The PCRE_DOLLAR_ENDONLY option is ignored + if PCRE_MULTILINE is set. There is no equivalent to this option in + Perl, and no way to set it within a pattern. PCRE_DOTALL If this bit is set, a dot metacharater in the pattern matches all char- - acters, including newlines. Without it, newlines are excluded. This - option is equivalent to Perl's /s option, and it can be changed within - a pattern by a (?s) option setting. A negative class such as [^a] - always matches a newline character, independent of the setting of this - option. + acters, including those that indicate newline. Without it, a dot does + not match when the current position is at a newline. This option is + equivalent to Perl's /s option, and it can be changed within a pattern + by a (?s) option setting. A negative class such as [^a] always matches + newlines, independent of the setting of this option. + + PCRE_DUPNAMES + + If this bit is set, names used to identify capturing subpatterns need + not be unique. This can be helpful for certain types of pattern when it + is known that only one instance of the named subpattern can ever be + matched. There are more details of named subpatterns below; see also + the pcrepattern documentation. PCRE_EXTENDED - If this bit is set, whitespace data characters in the pattern are + If this bit is set, whitespace data characters in the pattern are totally ignored except when escaped or inside a character class. White- space does not include the VT character (code 11). In addition, charac- ters between an unescaped # outside a character class and the next new- - line character, inclusive, are also ignored. This is equivalent to - Perl's /x option, and it can be changed within a pattern by a (?x) - option setting. - - This option makes it possible to include comments inside complicated - patterns. Note, however, that this applies only to data characters. - Whitespace characters may never appear within special character - sequences in a pattern, for example within the sequence (?( which + line, inclusive, are also ignored. This is equivalent to Perl's /x + option, and it can be changed within a pattern by a (?x) option set- + ting. + + This option makes it possible to include comments inside complicated + patterns. Note, however, that this applies only to data characters. + Whitespace characters may never appear within special character + sequences in a pattern, for example within the sequence (?( which introduces a conditional subpattern. PCRE_EXTRA - This option was invented in order to turn on additional functionality - of PCRE that is incompatible with Perl, but it is currently of very - little use. When set, any backslash in a pattern that is followed by a - letter that has no special meaning causes an error, thus reserving - these combinations for future expansion. By default, as in Perl, a - backslash followed by a letter with no special meaning is treated as a - literal. There are at present no other features controlled by this - option. It can also be set by a (?X) option setting within a pattern. + This option was invented in order to turn on additional functionality + of PCRE that is incompatible with Perl, but it is currently of very + little use. When set, any backslash in a pattern that is followed by a + letter that has no special meaning causes an error, thus reserving + these combinations for future expansion. By default, as in Perl, a + backslash followed by a letter with no special meaning is treated as a + literal. (Perl can, however, be persuaded to give a warning for this.) + There are at present no other features controlled by this option. It + can also be set by a (?X) option setting within a pattern. PCRE_FIRSTLINE If this option is set, an unanchored pattern is required to match - before or at the first newline character in the subject string, though - the matched text may continue over the newline. + before or at the first newline in the subject string, though the + matched text may continue over the newline. PCRE_MULTILINE @@ -991,54 +1054,71 @@ COMPILING A PATTERN is set). This is the same as Perl. When PCRE_MULTILINE it is set, the "start of line" and "end of line" - constructs match immediately following or immediately before any new- - line in the subject string, respectively, as well as at the very start - and end. This is equivalent to Perl's /m option, and it can be changed - within a pattern by a (?m) option setting. If there are no "\n" charac- - ters in a subject string, or no occurrences of ^ or $ in a pattern, + constructs match immediately following or immediately before internal + newlines in the subject string, respectively, as well as at the very + start and end. This is equivalent to Perl's /m option, and it can be + changed within a pattern by a (?m) option setting. If there are no new- + lines in a subject string, or no occurrences of ^ or $ in a pattern, setting PCRE_MULTILINE has no effect. + PCRE_NEWLINE_CR + PCRE_NEWLINE_LF + PCRE_NEWLINE_CRLF + + These options override the default newline definition that was chosen + when PCRE was built. Setting the first or the second specifies that a + newline is indicated by a single character (CR or LF, respectively). + Setting both of them specifies that a newline is indicated by the two- + character CRLF sequence. For convenience, PCRE_NEWLINE_CRLF is defined + to contain both bits. The only time that a line break is relevant when + compiling a pattern is if PCRE_EXTENDED is set, and an unescaped # out- + side a character class is encountered. This indicates a comment that + lasts until after the next newline. + + The newline option set at compile time becomes the default that is used + for pcre_exec() and pcre_dfa_exec(), but it can be overridden. + PCRE_NO_AUTO_CAPTURE If this option is set, it disables the use of numbered capturing paren- - theses in the pattern. Any opening parenthesis that is not followed by - ? behaves as if it were followed by ?: but named parentheses can still - be used for capturing (and they acquire numbers in the usual way). + theses in the pattern. Any opening parenthesis that is not followed by + ? behaves as if it were followed by ?: but named parentheses can still + be used for capturing (and they acquire numbers in the usual way). There is no equivalent of this option in Perl. PCRE_UNGREEDY - This option inverts the "greediness" of the quantifiers so that they - are not greedy by default, but become greedy if followed by "?". It is - not compatible with Perl. It can also be set by a (?U) option setting + This option inverts the "greediness" of the quantifiers so that they + are not greedy by default, but become greedy if followed by "?". It is + not compatible with Perl. It can also be set by a (?U) option setting within the pattern. PCRE_UTF8 - This option causes PCRE to regard both the pattern and the subject as - strings of UTF-8 characters instead of single-byte character strings. - However, it is available only when PCRE is built to include UTF-8 sup- - port. If not, the use of this option provokes an error. Details of how - this option changes the behaviour of PCRE are given in the section on + This option causes PCRE to regard both the pattern and the subject as + strings of UTF-8 characters instead of single-byte character strings. + However, it is available only when PCRE is built to include UTF-8 sup- + port. If not, the use of this option provokes an error. Details of how + this option changes the behaviour of PCRE are given in the section on UTF-8 support in the main pcre page. PCRE_NO_UTF8_CHECK When PCRE_UTF8 is set, the validity of the pattern as a UTF-8 string is - automatically checked. If an invalid UTF-8 sequence of bytes is found, - pcre_compile() returns an error. If you already know that your pattern - is valid, and you want to skip this check for performance reasons, you - can set the PCRE_NO_UTF8_CHECK option. When it is set, the effect of + automatically checked. If an invalid UTF-8 sequence of bytes is found, + pcre_compile() returns an error. If you already know that your pattern + is valid, and you want to skip this check for performance reasons, you + can set the PCRE_NO_UTF8_CHECK option. When it is set, the effect of passing an invalid UTF-8 string as a pattern is undefined. It may cause - your program to crash. Note that this option can also be passed to - pcre_exec() and pcre_dfa_exec(), to suppress the UTF-8 validity check- + your program to crash. Note that this option can also be passed to + pcre_exec() and pcre_dfa_exec(), to suppress the UTF-8 validity check- ing of subject strings. COMPILATION ERROR CODES - The following table lists the error codes than may be returned by - pcre_compile2(), along with the error messages that may be returned by + The following table lists the error codes than may be returned by + pcre_compile2(), along with the error messages that may be returned by both compiling functions. 0 no error @@ -1067,7 +1147,7 @@ COMPILATION ERROR CODES 23 internal error: code overflow 24 unrecognized character after (?< 25 lookbehind assertion is not fixed length - 26 malformed number after (?( + 26 malformed number or name after (?( 27 conditional group contains more than two branches 28 assertion expected after (?( 29 (?R or (?digits must be followed by ) @@ -1084,11 +1164,15 @@ COMPILATION ERROR CODES 40 recursive call could loop indefinitely 41 unrecognized character after (?P 42 syntax error after (?P - 43 two named groups have the same name + 43 two named subpatterns have the same name 44 invalid UTF-8 string 45 support for \P, \p, and \X has not been compiled 46 malformed \P or \p sequence 47 unknown property name after \P or \p + 48 subpattern name is too long (maximum 32 characters) + 49 too many named subpatterns (maximum 10,000) + 50 repeated subpattern is too long + 51 octal value is greater than \377 (not in UTF-8 mode) STUDYING A PATTERN @@ -1096,32 +1180,32 @@ STUDYING A PATTERN pcre_extra *pcre_study(const pcre *code, int options const char **errptr); - If a compiled pattern is going to be used several times, it is worth + If a compiled pattern is going to be used several times, it is worth spending more time analyzing it in order to speed up the time taken for - matching. The function pcre_study() takes a pointer to a compiled pat- + matching. The function pcre_study() takes a pointer to a compiled pat- tern as its first argument. If studying the pattern produces additional - information that will help speed up matching, pcre_study() returns a - pointer to a pcre_extra block, in which the study_data field points to + information that will help speed up matching, pcre_study() returns a + pointer to a pcre_extra block, in which the study_data field points to the results of the study. The returned value from pcre_study() can be passed directly to - pcre_exec(). However, a pcre_extra block also contains other fields - that can be set by the caller before the block is passed; these are + pcre_exec(). However, a pcre_extra block also contains other fields + that can be set by the caller before the block is passed; these are described below in the section on matching a pattern. - If studying the pattern does not produce any additional information + If studying the pattern does not produce any additional information pcre_study() returns NULL. In that circumstance, if the calling program - wants to pass any of the other fields to pcre_exec(), it must set up + wants to pass any of the other fields to pcre_exec(), it must set up its own pcre_extra block. - The second argument of pcre_study() contains option bits. At present, + The second argument of pcre_study() contains option bits. At present, no options are defined, and this argument should always be zero. - The third argument for pcre_study() is a pointer for an error message. - If studying succeeds (even if no data is returned), the variable it - points to is set to NULL. Otherwise it is set to point to a textual + The third argument for pcre_study() is a pointer for an error message. + If studying succeeds (even if no data is returned), the variable it + points to is set to NULL. Otherwise it is set to point to a textual error message. This is a static string that is part of the library. You - must not try to free it. You should test the error pointer for NULL + must not try to free it. You should test the error pointer for NULL after calling pcre_study(), to be sure that it has run successfully. This is a typical call to pcre_study(): @@ -1133,52 +1217,52 @@ STUDYING A PATTERN &error); /* set to NULL or points to a message */ At present, studying a pattern is useful only for non-anchored patterns - that do not have a single fixed starting character. A bitmap of possi- + that do not have a single fixed starting character. A bitmap of possi- ble starting bytes is created. LOCALE SUPPORT - PCRE handles caseless matching, and determines whether characters are - letters digits, or whatever, by reference to a set of tables, indexed - by character value. When running in UTF-8 mode, this applies only to - characters with codes less than 128. Higher-valued codes never match - escapes such as \w or \d, but can be tested with \p if PCRE is built - with Unicode character property support. The use of locales with Uni- + PCRE handles caseless matching, and determines whether characters are + letters digits, or whatever, by reference to a set of tables, indexed + by character value. When running in UTF-8 mode, this applies only to + characters with codes less than 128. Higher-valued codes never match + escapes such as \w or \d, but can be tested with \p if PCRE is built + with Unicode character property support. The use of locales with Uni- code is discouraged. - An internal set of tables is created in the default C locale when PCRE - is built. This is used when the final argument of pcre_compile() is - NULL, and is sufficient for many applications. An alternative set of - tables can, however, be supplied. These may be created in a different - locale from the default. As more and more applications change to using + An internal set of tables is created in the default C locale when PCRE + is built. This is used when the final argument of pcre_compile() is + NULL, and is sufficient for many applications. An alternative set of + tables can, however, be supplied. These may be created in a different + locale from the default. As more and more applications change to using Unicode, the need for this locale support is expected to die away. - External tables are built by calling the pcre_maketables() function, - which has no arguments, in the relevant locale. The result can then be - passed to pcre_compile() or pcre_exec() as often as necessary. For - example, to build and use tables that are appropriate for the French - locale (where accented characters with values greater than 128 are + External tables are built by calling the pcre_maketables() function, + which has no arguments, in the relevant locale. The result can then be + passed to pcre_compile() or pcre_exec() as often as necessary. For + example, to build and use tables that are appropriate for the French + locale (where accented characters with values greater than 128 are treated as letters), the following code could be used: setlocale(LC_CTYPE, "fr_FR"); tables = pcre_maketables(); re = pcre_compile(..., tables); - When pcre_maketables() runs, the tables are built in memory that is - obtained via pcre_malloc. It is the caller's responsibility to ensure - that the memory containing the tables remains available for as long as + When pcre_maketables() runs, the tables are built in memory that is + obtained via pcre_malloc. It is the caller's responsibility to ensure + that the memory containing the tables remains available for as long as it is needed. The pointer that is passed to pcre_compile() is saved with the compiled - pattern, and the same tables are used via this pointer by pcre_study() + pattern, and the same tables are used via this pointer by pcre_study() and normally also by pcre_exec(). Thus, by default, for any single pat- tern, compilation, studying and matching all happen in the same locale, but different patterns can be compiled in different locales. - It is possible to pass a table pointer or NULL (indicating the use of - the internal tables) to pcre_exec(). Although not intended for this - purpose, this facility could be used to match a pattern in a different + It is possible to pass a table pointer or NULL (indicating the use of + the internal tables) to pcre_exec(). Although not intended for this + purpose, this facility could be used to match a pattern in a different locale from the one in which it was compiled. Passing table pointers at run time is discussed below in the section on matching a pattern. @@ -1188,15 +1272,15 @@ INFORMATION ABOUT A PATTERN int pcre_fullinfo(const pcre *code, const pcre_extra *extra, int what, void *where); - The pcre_fullinfo() function returns information about a compiled pat- + The pcre_fullinfo() function returns information about a compiled pat- tern. It replaces the obsolete pcre_info() function, which is neverthe- less retained for backwards compability (and is documented below). - The first argument for pcre_fullinfo() is a pointer to the compiled - pattern. The second argument is the result of pcre_study(), or NULL if - the pattern was not studied. The third argument specifies which piece - of information is required, and the fourth argument is a pointer to a - variable to receive the data. The yield of the function is zero for + The first argument for pcre_fullinfo() is a pointer to the compiled + pattern. The second argument is the result of pcre_study(), or NULL if + the pattern was not studied. The third argument specifies which piece + of information is required, and the fourth argument is a pointer to a + variable to receive the data. The yield of the function is zero for success, or one of the following negative numbers: PCRE_ERROR_NULL the argument code was NULL @@ -1204,51 +1288,50 @@ INFORMATION ABOUT A PATTERN PCRE_ERROR_BADMAGIC the "magic number" was not found PCRE_ERROR_BADOPTION the value of what was invalid - The "magic number" is placed at the start of each compiled pattern as - an simple check against passing an arbitrary memory pointer. Here is a - typical call of pcre_fullinfo(), to obtain the length of the compiled + The "magic number" is placed at the start of each compiled pattern as + an simple check against passing an arbitrary memory pointer. Here is a + typical call of pcre_fullinfo(), to obtain the length of the compiled pattern: int rc; - unsigned long int length; + size_t length; rc = pcre_fullinfo( re, /* result of pcre_compile() */ pe, /* result of pcre_study(), or NULL */ PCRE_INFO_SIZE, /* what is required */ &length); /* where to put the data */ - The possible values for the third argument are defined in pcre.h, and + The possible values for the third argument are defined in pcre.h, and are as follows: PCRE_INFO_BACKREFMAX - Return the number of the highest back reference in the pattern. The - fourth argument should point to an int variable. Zero is returned if + Return the number of the highest back reference in the pattern. The + fourth argument should point to an int variable. Zero is returned if there are no back references. PCRE_INFO_CAPTURECOUNT - Return the number of capturing subpatterns in the pattern. The fourth + Return the number of capturing subpatterns in the pattern. The fourth argument should point to an int variable. PCRE_INFO_DEFAULT_TABLES - Return a pointer to the internal default character tables within PCRE. - The fourth argument should point to an unsigned char * variable. This + Return a pointer to the internal default character tables within PCRE. + The fourth argument should point to an unsigned char * variable. This information call is provided for internal use by the pcre_study() func- - tion. External callers can cause PCRE to use its internal tables by + tion. External callers can cause PCRE to use its internal tables by passing a NULL table pointer. PCRE_INFO_FIRSTBYTE - Return information about the first byte of any matched string, for a - non-anchored pattern. (This option used to be called - PCRE_INFO_FIRSTCHAR; the old name is still recognized for backwards - compatibility.) + Return information about the first byte of any matched string, for a + non-anchored pattern. The fourth argument should point to an int vari- + able. (This option used to be called PCRE_INFO_FIRSTCHAR; the old name + is still recognized for backwards compatibility.) - If there is a fixed first byte, for example, from a pattern such as - (cat|cow|coyote), it is returned in the integer pointed to by where. - Otherwise, if either + If there is a fixed first byte, for example, from a pattern such as + (cat|cow|coyote). Otherwise, if either (a) the pattern was compiled with the PCRE_MULTILINE option, and every branch starts with "^", or @@ -1284,13 +1367,13 @@ INFORMATION ABOUT A PATTERN PCRE supports the use of named as well as numbered capturing parenthe- ses. The names are just an additional way of identifying the parenthe- - ses, which still acquire numbers. A convenience function called - pcre_get_named_substring() is provided for extracting an individual - captured substring by name. It is also possible to extract the data - directly, by first converting the name to a number in order to access - the correct pointers in the output vector (described with pcre_exec() - below). To do the conversion, you need to use the name-to-number map, - which is described by these three values. + ses, which still acquire numbers. Several convenience functions such as + pcre_get_named_substring() are provided for extracting captured sub- + strings by name. It is also possible to extract the data directly, by + first converting the name to a number in order to access the correct + pointers in the output vector (described with pcre_exec() below). To do + the conversion, you need to use the name-to-number map, which is + described by these three values. The map consists of a number of fixed-size entries. PCRE_INFO_NAMECOUNT gives the number of entries, and PCRE_INFO_NAMEENTRYSIZE gives the size @@ -1300,8 +1383,10 @@ INFORMATION ABOUT A PATTERN first two bytes of each entry are the number of the capturing parenthe- sis, most significant byte first. The rest of the entry is the corre- sponding name, zero terminated. The names are in alphabetical order. - For example, consider the following pattern (assume PCRE_EXTENDED is - set, so white space - including newlines - is ignored): + When PCRE_DUPNAMES is set, duplicate names are in order of their paren- + theses numbers. For example, consider the following pattern (assume + PCRE_EXTENDED is set, so white space - including newlines - is + ignored): (?P<date> (?P<year>(\d\d)?\d\d) - (?P<month>\d\d) - (?P<day>\d\d) ) @@ -1317,8 +1402,8 @@ INFORMATION ABOUT A PATTERN 00 02 y e a r 00 ?? When writing code to extract data from named subpatterns using the - name-to-number map, remember that the length of each entry is likely to - be different for each compiled pattern. + name-to-number map, remember that the length of the entries is likely + to be different for each compiled pattern. PCRE_INFO_OPTIONS @@ -1517,16 +1602,26 @@ MATCHING A PATTERN: THE TRADITIONAL FUNCTION Option bits for pcre_exec() The unused bits of the options argument for pcre_exec() must be zero. - The only bits that may be set are PCRE_ANCHORED, PCRE_NOTBOL, - PCRE_NOTEOL, PCRE_NOTEMPTY, PCRE_NO_UTF8_CHECK and PCRE_PARTIAL. + The only bits that may be set are PCRE_ANCHORED, PCRE_NEWLINE_xxx, + PCRE_NOTBOL, PCRE_NOTEOL, PCRE_NOTEMPTY, PCRE_NO_UTF8_CHECK and + PCRE_PARTIAL. PCRE_ANCHORED - The PCRE_ANCHORED option limits pcre_exec() to matching at the first - matching position. If a pattern was compiled with PCRE_ANCHORED, or - turned out to be anchored by virtue of its contents, it cannot be made + The PCRE_ANCHORED option limits pcre_exec() to matching at the first + matching position. If a pattern was compiled with PCRE_ANCHORED, or + turned out to be anchored by virtue of its contents, it cannot be made unachored at matching time. + PCRE_NEWLINE_CR + PCRE_NEWLINE_LF + PCRE_NEWLINE_CRLF + + These options override the newline definition that was chosen or + defaulted when the pattern was compiled. For details, see the descrip- + tion pcre_compile() above. During matching, the newline choice affects + the behaviour of the dot, circumflex, and dollar metacharacters. + PCRE_NOTBOL This option specifies that first character of the subject string is not @@ -1662,41 +1757,50 @@ MATCHING A PATTERN: THE TRADITIONAL FUNCTION after the end of a substring. The first pair, ovector[0] and ovec- tor[1], identify the portion of the subject string matched by the entire pattern. The next pair is used for the first capturing subpat- - tern, and so on. The value returned by pcre_exec() is the number of - pairs that have been set. If there are no capturing subpatterns, the - return value from a successful match is 1, indicating that just the - first pair of offsets has been set. - - Some convenience functions are provided for extracting the captured - substrings as separate strings. These are described in the following - section. - - It is possible for an capturing subpattern number n+1 to match some - part of the subject when subpattern n has not been used at all. For - example, if the string "abc" is matched against the pattern (a|(z))(bc) - subpatterns 1 and 3 are matched, but 2 is not. When this happens, both - offset values corresponding to the unused subpattern are set to -1. + tern, and so on. The value returned by pcre_exec() is one more than the + highest numbered pair that has been set. For example, if two substrings + have been captured, the returned value is 3. If there are no capturing + subpatterns, the return value from a successful match is 1, indicating + that just the first pair of offsets has been set. If a capturing subpattern is matched repeatedly, it is the last portion of the string that it matched that is returned. - If the vector is too small to hold all the captured substring offsets, + If the vector is too small to hold all the captured substring offsets, it is used as far as possible (up to two-thirds of its length), and the - function returns a value of zero. In particular, if the substring off- + function returns a value of zero. In particular, if the substring off- sets are not of interest, pcre_exec() may be called with ovector passed - as NULL and ovecsize as zero. However, if the pattern contains back - references and the ovector is not big enough to remember the related - substrings, PCRE has to get additional memory for use during matching. + as NULL and ovecsize as zero. However, if the pattern contains back + references and the ovector is not big enough to remember the related + substrings, PCRE has to get additional memory for use during matching. Thus it is usually advisable to supply an ovector. - Note that pcre_info() can be used to find out how many capturing sub- - patterns there are in a compiled pattern. The smallest size for ovector - that will allow for n captured substrings, in addition to the offsets - of the substring matched by the whole pattern, is (n+1)*3. + The pcre_info() function can be used to find out how many capturing + subpatterns there are in a compiled pattern. The smallest size for + ovector that will allow for n captured substrings, in addition to the + offsets of the substring matched by the whole pattern, is (n+1)*3. + + It is possible for capturing subpattern number n+1 to match some part + of the subject when subpattern n has not been used at all. For example, + if the string "abc" is matched against the pattern (a|(z))(bc) the + return from the function is 4, and subpatterns 1 and 3 are matched, but + 2 is not. When this happens, both values in the offset pairs corre- + sponding to unused subpatterns are set to -1. + + Offset values that correspond to unused subpatterns at the end of the + expression are also set to -1. For example, if the string "abc" is + matched against the pattern (abc)(x(yz)?)? subpatterns 2 and 3 are not + matched. The return from the function is 2, because the highest used + capturing subpattern number is 1. However, you can refer to the offsets + for the second and third capturing subpatterns if you wish (assuming + the vector is large enough, of course). - Return values from pcre_exec() + Some convenience functions are provided for extracting the captured + substrings as separate strings. These are described below. - If pcre_exec() fails, it returns a negative number. The following are + Error return values from pcre_exec() + + If pcre_exec() fails, it returns a negative number. The following are defined in the header file: PCRE_ERROR_NOMATCH (-1) @@ -1705,7 +1809,7 @@ MATCHING A PATTERN: THE TRADITIONAL FUNCTION PCRE_ERROR_NULL (-2) - Either code or subject was passed as NULL, or ovector was NULL and + Either code or subject was passed as NULL, or ovector was NULL and ovecsize was not zero. PCRE_ERROR_BADOPTION (-3) @@ -1714,80 +1818,80 @@ MATCHING A PATTERN: THE TRADITIONAL FUNCTION PCRE_ERROR_BADMAGIC (-4) - PCRE stores a 4-byte "magic number" at the start of the compiled code, + PCRE stores a 4-byte "magic number" at the start of the compiled code, to catch the case when it is passed a junk pointer and to detect when a pattern that was compiled in an environment of one endianness is run in - an environment with the other endianness. This is the error that PCRE + an environment with the other endianness. This is the error that PCRE gives when the magic number is not present. PCRE_ERROR_UNKNOWN_NODE (-5) While running the pattern match, an unknown item was encountered in the - compiled pattern. This error could be caused by a bug in PCRE or by + compiled pattern. This error could be caused by a bug in PCRE or by overwriting of the compiled pattern. PCRE_ERROR_NOMEMORY (-6) - If a pattern contains back references, but the ovector that is passed + If a pattern contains back references, but the ovector that is passed to pcre_exec() is not big enough to remember the referenced substrings, - PCRE gets a block of memory at the start of matching to use for this - purpose. If the call via pcre_malloc() fails, this error is given. The + PCRE gets a block of memory at the start of matching to use for this + purpose. If the call via pcre_malloc() fails, this error is given. The memory is automatically freed at the end of matching. PCRE_ERROR_NOSUBSTRING (-7) - This error is used by the pcre_copy_substring(), pcre_get_substring(), + This error is used by the pcre_copy_substring(), pcre_get_substring(), and pcre_get_substring_list() functions (see below). It is never returned by pcre_exec(). PCRE_ERROR_MATCHLIMIT (-8) - The backtracking limit, as specified by the match_limit field in a - pcre_extra structure (or defaulted) was reached. See the description + The backtracking limit, as specified by the match_limit field in a + pcre_extra structure (or defaulted) was reached. See the description above. PCRE_ERROR_RECURSIONLIMIT (-21) The internal recursion limit, as specified by the match_limit_recursion - field in a pcre_extra structure (or defaulted) was reached. See the + field in a pcre_extra structure (or defaulted) was reached. See the description above. PCRE_ERROR_CALLOUT (-9) This error is never generated by pcre_exec() itself. It is provided for - use by callout functions that want to yield a distinctive error code. + use by callout functions that want to yield a distinctive error code. See the pcrecallout documentation for details. PCRE_ERROR_BADUTF8 (-10) - A string that contains an invalid UTF-8 byte sequence was passed as a + A string that contains an invalid UTF-8 byte sequence was passed as a subject. PCRE_ERROR_BADUTF8_OFFSET (-11) The UTF-8 byte sequence that was passed as a subject was valid, but the - value of startoffset did not point to the beginning of a UTF-8 charac- + value of startoffset did not point to the beginning of a UTF-8 charac- ter. PCRE_ERROR_PARTIAL (-12) - The subject string did not match, but it did match partially. See the + The subject string did not match, but it did match partially. See the pcrepartial documentation for details of partial matching. PCRE_ERROR_BADPARTIAL (-13) - The PCRE_PARTIAL option was used with a compiled pattern containing - items that are not supported for partial matching. See the pcrepartial + The PCRE_PARTIAL option was used with a compiled pattern containing + items that are not supported for partial matching. See the pcrepartial documentation for details of partial matching. PCRE_ERROR_INTERNAL (-14) - An unexpected internal error has occurred. This error could be caused + An unexpected internal error has occurred. This error could be caused by a bug in PCRE or by overwriting of the compiled pattern. PCRE_ERROR_BADCOUNT (-15) - This error is given if the value of the ovecsize argument is negative. + This error is given if the value of the ovecsize argument is negative. EXTRACTING CAPTURED SUBSTRINGS BY NUMBER @@ -1803,71 +1907,77 @@ EXTRACTING CAPTURED SUBSTRINGS BY NUMBER int pcre_get_substring_list(const char *subject, int *ovector, int stringcount, const char ***listptr); - Captured substrings can be accessed directly by using the offsets - returned by pcre_exec() in ovector. For convenience, the functions + Captured substrings can be accessed directly by using the offsets + returned by pcre_exec() in ovector. For convenience, the functions pcre_copy_substring(), pcre_get_substring(), and pcre_get_sub- - string_list() are provided for extracting captured substrings as new, - separate, zero-terminated strings. These functions identify substrings - by number. The next section describes functions for extracting named - substrings. A substring that contains a binary zero is correctly - extracted and has a further zero added on the end, but the result is - not, of course, a C string. - - The first three arguments are the same for all three of these func- - tions: subject is the subject string that has just been successfully + string_list() are provided for extracting captured substrings as new, + separate, zero-terminated strings. These functions identify substrings + by number. The next section describes functions for extracting named + substrings. + + A substring that contains a binary zero is correctly extracted and has + a further zero added on the end, but the result is not, of course, a C + string. However, you can process such a string by referring to the + length that is returned by pcre_copy_substring() and pcre_get_sub- + string(). Unfortunately, the interface to pcre_get_substring_list() is + not adequate for handling strings containing binary zeros, because the + end of the final string is not independently indicated. + + The first three arguments are the same for all three of these func- + tions: subject is the subject string that has just been successfully matched, ovector is a pointer to the vector of integer offsets that was passed to pcre_exec(), and stringcount is the number of substrings that - were captured by the match, including the substring that matched the + were captured by the match, including the substring that matched the entire regular expression. This is the value returned by pcre_exec() if - it is greater than zero. If pcre_exec() returned zero, indicating that - it ran out of space in ovector, the value passed as stringcount should + it is greater than zero. If pcre_exec() returned zero, indicating that + it ran out of space in ovector, the value passed as stringcount should be the number of elements in the vector divided by three. - The functions pcre_copy_substring() and pcre_get_substring() extract a - single substring, whose number is given as stringnumber. A value of - zero extracts the substring that matched the entire pattern, whereas - higher values extract the captured substrings. For pcre_copy_sub- - string(), the string is placed in buffer, whose length is given by - buffersize, while for pcre_get_substring() a new block of memory is - obtained via pcre_malloc, and its address is returned via stringptr. - The yield of the function is the length of the string, not including + The functions pcre_copy_substring() and pcre_get_substring() extract a + single substring, whose number is given as stringnumber. A value of + zero extracts the substring that matched the entire pattern, whereas + higher values extract the captured substrings. For pcre_copy_sub- + string(), the string is placed in buffer, whose length is given by + buffersize, while for pcre_get_substring() a new block of memory is + obtained via pcre_malloc, and its address is returned via stringptr. + The yield of the function is the length of the string, not including the terminating zero, or one of PCRE_ERROR_NOMEMORY (-6) - The buffer was too small for pcre_copy_substring(), or the attempt to + The buffer was too small for pcre_copy_substring(), or the attempt to get memory failed for pcre_get_substring(). PCRE_ERROR_NOSUBSTRING (-7) There is no substring whose number is stringnumber. - The pcre_get_substring_list() function extracts all available sub- - strings and builds a list of pointers to them. All this is done in a + The pcre_get_substring_list() function extracts all available sub- + strings and builds a list of pointers to them. All this is done in a single block of memory that is obtained via pcre_malloc. The address of - the memory block is returned via listptr, which is also the start of - the list of string pointers. The end of the list is marked by a NULL + the memory block is returned via listptr, which is also the start of + the list of string pointers. The end of the list is marked by a NULL pointer. The yield of the function is zero if all went well, or PCRE_ERROR_NOMEMORY (-6) if the attempt to get the memory block failed. - When any of these functions encounter a substring that is unset, which - can happen when capturing subpattern number n+1 matches some part of - the subject, but subpattern n has not been used at all, they return an + When any of these functions encounter a substring that is unset, which + can happen when capturing subpattern number n+1 matches some part of + the subject, but subpattern n has not been used at all, they return an empty string. This can be distinguished from a genuine zero-length sub- - string by inspecting the appropriate offset in ovector, which is nega- + string by inspecting the appropriate offset in ovector, which is nega- tive for unset substrings. - The two convenience functions pcre_free_substring() and pcre_free_sub- - string_list() can be used to free the memory returned by a previous + The two convenience functions pcre_free_substring() and pcre_free_sub- + string_list() can be used to free the memory returned by a previous call of pcre_get_substring() or pcre_get_substring_list(), respec- - tively. They do nothing more than call the function pointed to by - pcre_free, which of course could be called directly from a C program. - However, PCRE is used in some situations where it is linked via a spe- - cial interface to another programming language which cannot use - pcre_free directly; it is for these cases that the functions are pro- + tively. They do nothing more than call the function pointed to by + pcre_free, which of course could be called directly from a C program. + However, PCRE is used in some situations where it is linked via a spe- + cial interface to another programming language that cannot use + pcre_free directly; it is for these cases that the functions are pro- vided. @@ -1886,16 +1996,17 @@ EXTRACTING CAPTURED SUBSTRINGS BY NAME int stringcount, const char *stringname, const char **stringptr); - To extract a substring by name, you first have to find associated num- + To extract a substring by name, you first have to find associated num- ber. For example, for this pattern (a+)b(?P<xxx>\d+)... - the number of the subpattern called "xxx" is 2. You can find the number - from the name by calling pcre_get_stringnumber(). The first argument is - the compiled pattern, and the second is the name. The yield of the - function is the subpattern number, or PCRE_ERROR_NOSUBSTRING (-7) if - there is no subpattern of that name. + the number of the subpattern called "xxx" is 2. If the name is known to + be unique (PCRE_DUPNAMES was not set), you can find the number from the + name by calling pcre_get_stringnumber(). The first argument is the com- + piled pattern, and the second is the name. The yield of the function is + the subpattern number, or PCRE_ERROR_NOSUBSTRING (-7) if there is no + subpattern of that name. Given the number, you can extract the substring directly, or use one of the functions described in the previous section. For convenience, there @@ -1917,21 +2028,50 @@ EXTRACTING CAPTURED SUBSTRINGS BY NAME ate. +DUPLICATE SUBPATTERN NAMES + + int pcre_get_stringtable_entries(const pcre *code, + const char *name, char **first, char **last); + + When a pattern is compiled with the PCRE_DUPNAMES option, names for + subpatterns are not required to be unique. Normally, patterns with + duplicate names are such that in any one match, only one of the named + subpatterns participates. An example is shown in the pcrepattern docu- + mentation. When duplicates are present, pcre_copy_named_substring() and + pcre_get_named_substring() return the first substring corresponding to + the given name that is set. If none are set, an empty string is + returned. The pcre_get_stringnumber() function returns one of the num- + bers that are associated with the name, but it is not defined which it + is. + + If you want to get full details of all captured substrings for a given + name, you must use the pcre_get_stringtable_entries() function. The + first argument is the compiled pattern, and the second is the name. The + third and fourth are pointers to variables which are updated by the + function. After it has run, they point to the first and last entries in + the name-to-number table for the given name. The function itself + returns the length of each entry, or PCRE_ERROR_NOSUBSTRING if there + are none. The format of the table is described above in the section + entitled Information about a pattern. Given all the relevant entries + for the name, you can extract each of their numbers, and hence the cap- + tured data, if any. + + FINDING ALL POSSIBLE MATCHES - The traditional matching function uses a similar algorithm to Perl, + The traditional matching function uses a similar algorithm to Perl, which stops when it finds the first match, starting at a given point in - the subject. If you want to find all possible matches, or the longest - possible match, consider using the alternative matching function (see - below) instead. If you cannot use the alternative function, but still - need to find all possible matches, you can kludge it up by making use + the subject. If you want to find all possible matches, or the longest + possible match, consider using the alternative matching function (see + below) instead. If you cannot use the alternative function, but still + need to find all possible matches, you can kludge it up by making use of the callout facility, which is described in the pcrecallout documen- tation. What you have to do is to insert a callout right at the end of the pat- - tern. When your callout function is called, extract and save the cur- - rent matched substring. Then return 1, which forces pcre_exec() to - backtrack and try other alternatives. Ultimately, when it runs out of + tern. When your callout function is called, extract and save the cur- + rent matched substring. Then return 1, which forces pcre_exec() to + backtrack and try other alternatives. Ultimately, when it runs out of matches, pcre_exec() will yield PCRE_ERROR_NOMATCH. @@ -1942,25 +2082,25 @@ MATCHING A PATTERN: THE ALTERNATIVE FUNCTION int options, int *ovector, int ovecsize, int *workspace, int wscount); - The function pcre_dfa_exec() is called to match a subject string - against a compiled pattern, using a "DFA" matching algorithm. This has - different characteristics to the normal algorithm, and is not compati- + The function pcre_dfa_exec() is called to match a subject string + against a compiled pattern, using a "DFA" matching algorithm. This has + different characteristics to the normal algorithm, and is not compati- ble with Perl. Some of the features of PCRE patterns are not supported. Nevertheless, there are times when this kind of matching can be useful. - For a discussion of the two matching algorithms, see the pcrematching + For a discussion of the two matching algorithms, see the pcrematching documentation. - The arguments for the pcre_dfa_exec() function are the same as for + The arguments for the pcre_dfa_exec() function are the same as for pcre_exec(), plus two extras. The ovector argument is used in a differ- - ent way, and this is described below. The other common arguments are - used in the same way as for pcre_exec(), so their description is not + ent way, and this is described below. The other common arguments are + used in the same way as for pcre_exec(), so their description is not repeated here. - The two additional arguments provide workspace for the function. The - workspace vector should contain at least 20 elements. It is used for + The two additional arguments provide workspace for the function. The + workspace vector should contain at least 20 elements. It is used for keeping track of multiple paths through the pattern tree. More - workspace will be needed for patterns and subjects where there are a - lot of possible matches. + workspace will be needed for patterns and subjects where there are a + lot of potential matches. Here is an example of a simple call to pcre_dfa_exec(): @@ -1981,47 +2121,47 @@ MATCHING A PATTERN: THE ALTERNATIVE FUNCTION Option bits for pcre_dfa_exec() - The unused bits of the options argument for pcre_dfa_exec() must be - zero. The only bits that may be set are PCRE_ANCHORED, PCRE_NOTBOL, - PCRE_NOTEOL, PCRE_NOTEMPTY, PCRE_NO_UTF8_CHECK, PCRE_PARTIAL, - PCRE_DFA_SHORTEST, and PCRE_DFA_RESTART. All but the last three of - these are the same as for pcre_exec(), so their description is not - repeated here. + The unused bits of the options argument for pcre_dfa_exec() must be + zero. The only bits that may be set are PCRE_ANCHORED, PCRE_NEW- + LINE_xxx, PCRE_NOTBOL, PCRE_NOTEOL, PCRE_NOTEMPTY, PCRE_NO_UTF8_CHECK, + PCRE_PARTIAL, PCRE_DFA_SHORTEST, and PCRE_DFA_RESTART. All but the last + three of these are the same as for pcre_exec(), so their description is + not repeated here. PCRE_PARTIAL - This has the same general effect as it does for pcre_exec(), but the - details are slightly different. When PCRE_PARTIAL is set for - pcre_dfa_exec(), the return code PCRE_ERROR_NOMATCH is converted into - PCRE_ERROR_PARTIAL if the end of the subject is reached, there have + This has the same general effect as it does for pcre_exec(), but the + details are slightly different. When PCRE_PARTIAL is set for + pcre_dfa_exec(), the return code PCRE_ERROR_NOMATCH is converted into + PCRE_ERROR_PARTIAL if the end of the subject is reached, there have been no complete matches, but there is still at least one matching pos- - sibility. The portion of the string that provided the partial match is + sibility. The portion of the string that provided the partial match is set as the first matching string. PCRE_DFA_SHORTEST - Setting the PCRE_DFA_SHORTEST option causes the matching algorithm to - stop as soon as it has found one match. Because of the way the DFA + Setting the PCRE_DFA_SHORTEST option causes the matching algorithm to + stop as soon as it has found one match. Because of the way the DFA algorithm works, this is necessarily the shortest possible match at the first possible matching point in the subject string. PCRE_DFA_RESTART - When pcre_dfa_exec() is called with the PCRE_PARTIAL option, and - returns a partial match, it is possible to call it again, with addi- - tional subject characters, and have it continue with the same match. - The PCRE_DFA_RESTART option requests this action; when it is set, the - workspace and wscount options must reference the same vector as before - because data about the match so far is left in them after a partial - match. There is more discussion of this facility in the pcrepartial + When pcre_dfa_exec() is called with the PCRE_PARTIAL option, and + returns a partial match, it is possible to call it again, with addi- + tional subject characters, and have it continue with the same match. + The PCRE_DFA_RESTART option requests this action; when it is set, the + workspace and wscount options must reference the same vector as before + because data about the match so far is left in them after a partial + match. There is more discussion of this facility in the pcrepartial documentation. Successful returns from pcre_dfa_exec() - When pcre_dfa_exec() succeeds, it may have matched more than one sub- + When pcre_dfa_exec() succeeds, it may have matched more than one sub- string in the subject. Note, however, that all the matches from one run - of the function start at the same point in the subject. The shorter - matches are all initial substrings of the longer matches. For example, + of the function start at the same point in the subject. The shorter + matches are all initial substrings of the longer matches. For example, if the pattern <.*> @@ -2036,58 +2176,58 @@ MATCHING A PATTERN: THE ALTERNATIVE FUNCTION <something> <something else> <something> <something else> <something further> - On success, the yield of the function is a number greater than zero, - which is the number of matched substrings. The substrings themselves - are returned in ovector. Each string uses two elements; the first is - the offset to the start, and the second is the offset to the end. All + On success, the yield of the function is a number greater than zero, + which is the number of matched substrings. The substrings themselves + are returned in ovector. Each string uses two elements; the first is + the offset to the start, and the second is the offset to the end. All the strings have the same start offset. (Space could have been saved by - giving this only once, but it was decided to retain some compatibility - with the way pcre_exec() returns data, even though the meaning of the + giving this only once, but it was decided to retain some compatibility + with the way pcre_exec() returns data, even though the meaning of the strings is different.) The strings are returned in reverse order of length; that is, the long- - est matching string is given first. If there were too many matches to - fit into ovector, the yield of the function is zero, and the vector is + est matching string is given first. If there were too many matches to + fit into ovector, the yield of the function is zero, and the vector is filled with the longest matches. Error returns from pcre_dfa_exec() - The pcre_dfa_exec() function returns a negative number when it fails. - Many of the errors are the same as for pcre_exec(), and these are - described above. There are in addition the following errors that are + The pcre_dfa_exec() function returns a negative number when it fails. + Many of the errors are the same as for pcre_exec(), and these are + described above. There are in addition the following errors that are specific to pcre_dfa_exec(): PCRE_ERROR_DFA_UITEM (-16) - This return is given if pcre_dfa_exec() encounters an item in the pat- - tern that it does not support, for instance, the use of \C or a back + This return is given if pcre_dfa_exec() encounters an item in the pat- + tern that it does not support, for instance, the use of \C or a back reference. PCRE_ERROR_DFA_UCOND (-17) - This return is given if pcre_dfa_exec() encounters a condition item in - a pattern that uses a back reference for the condition. This is not + This return is given if pcre_dfa_exec() encounters a condition item in + a pattern that uses a back reference for the condition. This is not supported. PCRE_ERROR_DFA_UMLIMIT (-18) - This return is given if pcre_dfa_exec() is called with an extra block + This return is given if pcre_dfa_exec() is called with an extra block that contains a setting of the match_limit field. This is not supported (it is meaningless). PCRE_ERROR_DFA_WSSIZE (-19) - This return is given if pcre_dfa_exec() runs out of space in the + This return is given if pcre_dfa_exec() runs out of space in the workspace vector. PCRE_ERROR_DFA_RECURSE (-20) - When a recursive subpattern is processed, the matching function calls - itself recursively, using private vectors for ovector and workspace. - This error is given if the output vector is not large enough. This + When a recursive subpattern is processed, the matching function calls + itself recursively, using private vectors for ovector and workspace. + This error is given if the output vector is not large enough. This should be extremely rare, as a vector of size 1000 is used. -Last updated: 18 January 2006 +Last updated: 08 June 2006 Copyright (c) 1997-2006 University of Cambridge. ------------------------------------------------------------------------------ @@ -2334,25 +2474,26 @@ DIFFERENCES BETWEEN PCRE AND PERL meta-character matches only at the very end of the string. (c) If PCRE_EXTRA is set, a backslash followed by a letter with no spe- - cial meaning is faulted. + cial meaning is faulted. Otherwise, like Perl, the backslash is + ignored. (Perl can be made to issue a warning.) - (d) If PCRE_UNGREEDY is set, the greediness of the repetition quanti- + (d) If PCRE_UNGREEDY is set, the greediness of the repetition quanti- fiers is inverted, that is, by default they are not greedy, but if fol- lowed by a question mark they are. (e) PCRE_ANCHORED can be used at matching time to force a pattern to be tried only at the first matching position in the subject string. - (f) The PCRE_NOTBOL, PCRE_NOTEOL, PCRE_NOTEMPTY, and PCRE_NO_AUTO_CAP- + (f) The PCRE_NOTBOL, PCRE_NOTEOL, PCRE_NOTEMPTY, and PCRE_NO_AUTO_CAP- TURE options for pcre_exec() have no Perl equivalents. - (g) The (?R), (?number), and (?P>name) constructs allows for recursive - pattern matching (Perl can do this using the (?p{code}) construct, + (g) The (?R), (?number), and (?P>name) constructs allows for recursive + pattern matching (Perl can do this using the (?p{code}) construct, which PCRE cannot support.) - (h) PCRE supports named capturing substrings, using the Python syntax. + (h) PCRE supports named capturing substrings, using the Python syntax. - (i) PCRE supports the possessive quantifier "++" syntax, taken from + (i) PCRE supports the possessive quantifier "++" syntax, taken from Sun's Java package. (j) The (R) condition, for testing recursion, is a PCRE extension. @@ -2364,10 +2505,10 @@ DIFFERENCES BETWEEN PCRE AND PERL (m) Patterns compiled by PCRE can be saved and re-used at a later time, even on different hosts that have the other endianness. - (n) The alternative matching function (pcre_dfa_exec()) matches in a + (n) The alternative matching function (pcre_dfa_exec()) matches in a different way and is not Perl-compatible. -Last updated: 24 January 2006 +Last updated: 06 June 2006 Copyright (c) 1997-2006 University of Cambridge. ------------------------------------------------------------------------------ @@ -2476,9 +2617,9 @@ BACKSLASH If a pattern is compiled with the PCRE_EXTENDED option, whitespace in the pattern (other than in a character class) and characters between a - # outside a character class and the next newline character are ignored. - An escaping backslash can be used to include a whitespace or # charac- - ter as part of the pattern. + # outside a character class and the next newline are ignored. An escap- + ing backslash can be used to include a whitespace or # character as + part of the pattern. If you want to remove the special meaning from a sequence of charac- ters, you can do so by putting them between \Q and \E. This is differ- @@ -2535,26 +2676,27 @@ BACKSLASH two syntaxes for \x. There is no difference in the way they are han- dled. For example, \xdc is exactly the same as \x{dc}. - After \0 up to two further octal digits are read. In both cases, if - there are fewer than two digits, just those that are present are used. - Thus the sequence \0\x\07 specifies two binary zeros followed by a BEL - character (code value 7). Make sure you supply two digits after the - initial zero if the pattern character that follows is itself an octal - digit. + After \0 up to two further octal digits are read. If there are fewer + than two digits, just those that are present are used. Thus the + sequence \0\x\07 specifies two binary zeros followed by a BEL character + (code value 7). Make sure you supply two digits after the initial zero + if the pattern character that follows is itself an octal digit. The handling of a backslash followed by a digit other than 0 is compli- cated. Outside a character class, PCRE reads it and any following dig- - its as a decimal number. If the number is less than 10, or if there + its as a decimal number. If the number is less than 10, or if there have been at least that many previous capturing left parentheses in the - expression, the entire sequence is taken as a back reference. A - description of how this works is given later, following the discussion + expression, the entire sequence is taken as a back reference. A + description of how this works is given later, following the discussion of parenthesized subpatterns. - Inside a character class, or if the decimal number is greater than 9 - and there have not been that many capturing subpatterns, PCRE re-reads - up to three octal digits following the backslash, and generates a sin- - gle byte from the least significant 8 bits of the value. Any subsequent - digits stand for themselves. For example: + Inside a character class, or if the decimal number is greater than 9 + and there have not been that many capturing subpatterns, PCRE re-reads + up to three octal digits following the backslash, ane uses them to gen- + erate a data character. Any subsequent digits stand for themselves. In + non-UTF-8 mode, the value of a character specified in octal must be + less than \400. In UTF-8 mode, values up to \777 are permitted. For + example: \040 is another way of writing a space \40 is the same, provided there are fewer than 40 @@ -2571,15 +2713,14 @@ BACKSLASH \81 is either a back reference, or a binary zero followed by the two characters "8" and "1" - Note that octal values of 100 or greater must not be introduced by a + Note that octal values of 100 or greater must not be introduced by a leading zero, because no more than three octal digits are ever read. - All the sequences that define a single byte value or a single UTF-8 - character (in UTF-8 mode) can be used both inside and outside character - classes. In addition, inside a character class, the sequence \b is - interpreted as the backspace character (hex 08), and the sequence \X is - interpreted as the character "X". Outside a character class, these - sequences have different meanings (see below). + All the sequences that define a single character value can be used both + inside and outside character classes. In addition, inside a character + class, the sequence \b is interpreted as the backspace character (hex + 08), and the sequence \X is interpreted as the character "X". Outside a + character class, these sequences have different meanings (see below). Generic character types @@ -2604,7 +2745,9 @@ BACKSLASH For compatibility with Perl, \s does not match the VT character (code 11). This makes it different from the the POSIX "space" class. The \s - characters are HT (9), LF (10), FF (12), CR (13), and space (32). + characters are HT (9), LF (10), FF (12), CR (13), and space (32). (If + "use locale;" is included in a Perl script, \s may match the VT charac- + ter. In PCRE, it never does.) A "word" character is an underscore or any character less than 256 that is a letter or digit. The definition of letters and digits is con- @@ -2719,7 +2862,7 @@ BACKSLASH classified as a modifier or "other". The long synonyms for these properties that Perl supports (such as - \p{Letter}) are not supported by PCRE. Nor is is permitted to prefix + \p{Letter}) are not supported by PCRE, nor is it permitted to prefix any of these properties with "Is". No character that is in the Unicode table has the Cn (unassigned) prop- @@ -2777,24 +2920,23 @@ BACKSLASH However, if the startoffset argument of pcre_exec() is non-zero, indi- cating that matching is to start at a point other than the beginning of the subject, \A can never match. The difference between \Z and \z is - that \Z matches before a newline that is the last character of the - string as well as at the end of the string, whereas \z matches only at - the end. - - The \G assertion is true only when the current matching position is at - the start point of the match, as specified by the startoffset argument - of pcre_exec(). It differs from \A when the value of startoffset is - non-zero. By calling pcre_exec() multiple times with appropriate argu- + that \Z matches before a newline at the end of the string as well as at + the very end, whereas \z matches only at the end. + + The \G assertion is true only when the current matching position is at + the start point of the match, as specified by the startoffset argument + of pcre_exec(). It differs from \A when the value of startoffset is + non-zero. By calling pcre_exec() multiple times with appropriate argu- ments, you can mimic Perl's /g option, and it is in this kind of imple- mentation where \G can be useful. - Note, however, that PCRE's interpretation of \G, as the start of the + Note, however, that PCRE's interpretation of \G, as the start of the current match, is subtly different from Perl's, which defines it as the - end of the previous match. In Perl, these can be different when the - previously matched string was empty. Because PCRE does just one match + end of the previous match. In Perl, these can be different when the + previously matched string was empty. Because PCRE does just one match at a time, it cannot reproduce this behaviour. - If all the alternatives of a pattern begin with \G, the expression is + If all the alternatives of a pattern begin with \G, the expression is anchored to the starting match position, and the "anchored" flag is set in the compiled regular expression. @@ -2802,68 +2944,81 @@ BACKSLASH CIRCUMFLEX AND DOLLAR Outside a character class, in the default matching mode, the circumflex - character is an assertion that is true only if the current matching - point is at the start of the subject string. If the startoffset argu- - ment of pcre_exec() is non-zero, circumflex can never match if the - PCRE_MULTILINE option is unset. Inside a character class, circumflex + character is an assertion that is true only if the current matching + point is at the start of the subject string. If the startoffset argu- + ment of pcre_exec() is non-zero, circumflex can never match if the + PCRE_MULTILINE option is unset. Inside a character class, circumflex has an entirely different meaning (see below). - Circumflex need not be the first character of the pattern if a number - of alternatives are involved, but it should be the first thing in each - alternative in which it appears if the pattern is ever to match that - branch. If all possible alternatives start with a circumflex, that is, - if the pattern is constrained to match only at the start of the sub- - ject, it is said to be an "anchored" pattern. (There are also other + Circumflex need not be the first character of the pattern if a number + of alternatives are involved, but it should be the first thing in each + alternative in which it appears if the pattern is ever to match that + branch. If all possible alternatives start with a circumflex, that is, + if the pattern is constrained to match only at the start of the sub- + ject, it is said to be an "anchored" pattern. (There are also other constructs that can cause a pattern to be anchored.) - A dollar character is an assertion that is true only if the current - matching point is at the end of the subject string, or immediately - before a newline character that is the last character in the string (by - default). Dollar need not be the last character of the pattern if a - number of alternatives are involved, but it should be the last item in - any branch in which it appears. Dollar has no special meaning in a - character class. + A dollar character is an assertion that is true only if the current + matching point is at the end of the subject string, or immediately + before a newline at the end of the string (by default). Dollar need not + be the last character of the pattern if a number of alternatives are + involved, but it should be the last item in any branch in which it + appears. Dollar has no special meaning in a character class. The meaning of dollar can be changed so that it matches only at the very end of the string, by setting the PCRE_DOLLAR_ENDONLY option at compile time. This does not affect the \Z assertion. The meanings of the circumflex and dollar characters are changed if the - PCRE_MULTILINE option is set. When this is the case, they match immedi- - ately after and immediately before an internal newline character, - respectively, in addition to matching at the start and end of the sub- - ject string. For example, the pattern /^abc$/ matches the subject - string "def\nabc" (where \n represents a newline character) in multi- - line mode, but not otherwise. Consequently, patterns that are anchored - in single line mode because all branches start with ^ are not anchored - in multiline mode, and a match for circumflex is possible when the - startoffset argument of pcre_exec() is non-zero. The PCRE_DOL- - LAR_ENDONLY option is ignored if PCRE_MULTILINE is set. - - Note that the sequences \A, \Z, and \z can be used to match the start - and end of the subject in both modes, and if all branches of a pattern - start with \A it is always anchored, whether PCRE_MULTILINE is set or - not. + PCRE_MULTILINE option is set. When this is the case, a circumflex + matches immediately after internal newlines as well as at the start of + the subject string. It does not match after a newline that ends the + string. A dollar matches before any newlines in the string, as well as + at the very end, when PCRE_MULTILINE is set. When newline is specified + as the two-character sequence CRLF, isolated CR and LF characters do + not indicate newlines. + + For example, the pattern /^abc$/ matches the subject string "def\nabc" + (where \n represents a newline) in multiline mode, but not otherwise. + Consequently, patterns that are anchored in single line mode because + all branches start with ^ are not anchored in multiline mode, and a + match for circumflex is possible when the startoffset argument of + pcre_exec() is non-zero. The PCRE_DOLLAR_ENDONLY option is ignored if + PCRE_MULTILINE is set. + + Note that the sequences \A, \Z, and \z can be used to match the start + and end of the subject in both modes, and if all branches of a pattern + start with \A it is always anchored, whether or not PCRE_MULTILINE is + set. FULL STOP (PERIOD, DOT) Outside a character class, a dot in the pattern matches any one charac- - ter in the subject, including a non-printing character, but not (by - default) newline. In UTF-8 mode, a dot matches any UTF-8 character, - which might be more than one byte long, except (by default) newline. If - the PCRE_DOTALL option is set, dots match newlines as well. The han- - dling of dot is entirely independent of the handling of circumflex and - dollar, the only relationship being that they both involve newline - characters. Dot has no special meaning in a character class. + ter in the subject string except (by default) a character that signi- + fies the end of a line. In UTF-8 mode, the matched character may be + more than one byte long. When a line ending is defined as a single + character (CR or LF), dot never matches that character; when the two- + character sequence CRLF is used, dot does not match CR if it is immedi- + ately followed by LF, but otherwise it matches all characters (includ- + ing isolated CRs and LFs). + + The behaviour of dot with regard to newlines can be changed. If the + PCRE_DOTALL option is set, a dot matches any one character, without + exception. If newline is defined as the two-character sequence CRLF, it + takes two dots to match it. + + The handling of dot is entirely independent of the handling of circum- + flex and dollar, the only relationship being that they both involve + newlines. Dot has no special meaning in a character class. MATCHING A SINGLE BYTE Outside a character class, the escape sequence \C matches any one byte, - both in and out of UTF-8 mode. Unlike a dot, it can match a newline. - The feature is provided in Perl in order to match individual bytes in - UTF-8 mode. Because it breaks up UTF-8 characters into individual + both in and out of UTF-8 mode. Unlike a dot, it always matches CR and + LF. The feature is provided in Perl in order to match individual bytes + in UTF-8 mode. Because it breaks up UTF-8 characters into individual bytes, what remains in the string may be a malformed UTF-8 string. For this reason, the \C escape sequence is best avoided. @@ -2912,9 +3067,11 @@ SQUARE BRACKETS AND CHARACTER CLASSES PCRE is compiled with Unicode property support as well as with UTF-8 support. - The newline character is never treated in any special way in character - classes, whatever the setting of the PCRE_DOTALL or PCRE_MULTILINE - options is. A class such as [^a] will always match a newline. + Characters that might indicate line breaks (CR and LF) are never + treated in any special way when matching character classes, whatever + line-ending sequence is in use, and whatever setting of the PCRE_DOTALL + and PCRE_MULTILINE options is used. A class such as [^a] always matches + one of these characters. The minus (hyphen) character can be used to specify a range of charac- ters in a character class. For example, [d-m] matches any letter @@ -3015,11 +3172,10 @@ VERTICAL BAR matches either "gilbert" or "sullivan". Any number of alternatives may appear, and an empty alternative is permitted (matching the empty - string). The matching process tries each alternative in turn, from - left to right, and the first one that succeeds is used. If the alterna- - tives are within a subpattern (defined below), "succeeds" means match- - ing the rest of the main pattern as well as the alternative in the sub- - pattern. + string). The matching process tries each alternative in turn, from left + to right, and the first one that succeeds is used. If the alternatives + are within a subpattern (defined below), "succeeds" means matching the + rest of the main pattern as well as the alternative in the subpattern. INTERNAL OPTION SETTING @@ -3065,12 +3221,9 @@ INTERNAL OPTION SETTING the effects of option settings happen at compile time. There would be some very weird behaviour otherwise. - The PCRE-specific options PCRE_UNGREEDY and PCRE_EXTRA can be changed - in the same way as the Perl-compatible options by using the characters - U and X respectively. The (?X) flag setting is special in that it must - always occur earlier in the pattern than any of the additional features - it turns on, even when it is at top level. It is best to put it at the - start. + The PCRE-specific options PCRE_DUPNAMES, PCRE_UNGREEDY, and PCRE_EXTRA + can be changed in the same way as the Perl-compatible options by using + the characters J, U and X respectively. SUBPATTERNS @@ -3082,18 +3235,18 @@ SUBPATTERNS cat(aract|erpillar|) - matches one of the words "cat", "cataract", or "caterpillar". Without - the parentheses, it would match "cataract", "erpillar" or the empty + matches one of the words "cat", "cataract", or "caterpillar". Without + the parentheses, it would match "cataract", "erpillar" or the empty string. - 2. It sets up the subpattern as a capturing subpattern. This means - that, when the whole pattern matches, that portion of the subject + 2. It sets up the subpattern as a capturing subpattern. This means + that, when the whole pattern matches, that portion of the subject string that matched the subpattern is passed back to the caller via the - ovector argument of pcre_exec(). Opening parentheses are counted from - left to right (starting from 1) to obtain numbers for the capturing + ovector argument of pcre_exec(). Opening parentheses are counted from + left to right (starting from 1) to obtain numbers for the capturing subpatterns. - For example, if the string "the red king" is matched against the pat- + For example, if the string "the red king" is matched against the pat- tern the ((red|white) (king|queen)) @@ -3101,50 +3254,75 @@ SUBPATTERNS the captured substrings are "red king", "red", and "king", and are num- bered 1, 2, and 3, respectively. - The fact that plain parentheses fulfil two functions is not always - helpful. There are often times when a grouping subpattern is required - without a capturing requirement. If an opening parenthesis is followed - by a question mark and a colon, the subpattern does not do any captur- - ing, and is not counted when computing the number of any subsequent - capturing subpatterns. For example, if the string "the white queen" is + The fact that plain parentheses fulfil two functions is not always + helpful. There are often times when a grouping subpattern is required + without a capturing requirement. If an opening parenthesis is followed + by a question mark and a colon, the subpattern does not do any captur- + ing, and is not counted when computing the number of any subsequent + capturing subpatterns. For example, if the string "the white queen" is matched against the pattern the ((?:red|white) (king|queen)) the captured substrings are "white queen" and "queen", and are numbered - 1 and 2. The maximum number of capturing subpatterns is 65535, and the - maximum depth of nesting of all subpatterns, both capturing and non- + 1 and 2. The maximum number of capturing subpatterns is 65535, and the + maximum depth of nesting of all subpatterns, both capturing and non- capturing, is 200. - As a convenient shorthand, if any option settings are required at the - start of a non-capturing subpattern, the option letters may appear + As a convenient shorthand, if any option settings are required at the + start of a non-capturing subpattern, the option letters may appear between the "?" and the ":". Thus the two patterns (?i:saturday|sunday) (?:(?i)saturday|sunday) match exactly the same set of strings. Because alternative branches are - tried from left to right, and options are not reset until the end of - the subpattern is reached, an option setting in one branch does affect - subsequent branches, so the above patterns match "SUNDAY" as well as + tried from left to right, and options are not reset until the end of + the subpattern is reached, an option setting in one branch does affect + subsequent branches, so the above patterns match "SUNDAY" as well as "Saturday". NAMED SUBPATTERNS - Identifying capturing parentheses by number is simple, but it can be - very hard to keep track of the numbers in complicated regular expres- - sions. Furthermore, if an expression is modified, the numbers may - change. To help with this difficulty, PCRE supports the naming of sub- - patterns, something that Perl does not provide. The Python syntax - (?P<name>...) is used. Names consist of alphanumeric characters and - underscores, and must be unique within a pattern. - - Named capturing parentheses are still allocated numbers as well as + Identifying capturing parentheses by number is simple, but it can be + very hard to keep track of the numbers in complicated regular expres- + sions. Furthermore, if an expression is modified, the numbers may + change. To help with this difficulty, PCRE supports the naming of sub- + patterns, something that Perl does not provide. The Python syntax + (?P<name>...) is used. References to capturing parentheses from other + parts of the pattern, such as backreferences, recursion, and condi- + tions, can be made by name as well as by number. + + Names consist of up to 32 alphanumeric characters and underscores. + Named capturing parentheses are still allocated numbers as well as names. The PCRE API provides function calls for extracting the name-to- - number translation table from a compiled pattern. There is also a con- - venience function for extracting a captured substring by name. For fur- - ther details see the pcreapi documentation. + number translation table from a compiled pattern. There is also a con- + venience function for extracting a captured substring by name. + + By default, a name must be unique within a pattern, but it is possible + to relax this constraint by setting the PCRE_DUPNAMES option at compile + time. This can be useful for patterns where only one instance of the + named parentheses can match. Suppose you want to match the name of a + weekday, either as a 3-letter abbreviation or as the full name, and in + both cases you want to extract the abbreviation. This pattern (ignoring + the line breaks) does the job: + + (?P<DN>Mon|Fri|Sun)(?:day)?| + (?P<DN>Tue)(?:sday)?| + (?P<DN>Wed)(?:nesday)?| + (?P<DN>Thu)(?:rsday)?| + (?P<DN>Sat)(?:urday)? + + There are five capturing substrings, but only one is ever set after a + match. The convenience function for extracting the data by name + returns the substring for the first, and in this example, the only, + subpattern of that name that matched. This saves searching to find + which numbered subpattern it was. If you make a reference to a non- + unique named subpattern from elsewhere in the pattern, the one that + corresponds to the lowest number is used. For further details of the + interfaces for handling named subpatterns, see the pcreapi documenta- + tion. REPETITION @@ -3353,8 +3531,10 @@ ATOMIC GROUPING AND POSSESSIVE QUANTIFIERS meaning or processing of a possessive quantifier and the equivalent atomic group. - The possessive quantifier syntax is an extension to the Perl syntax. It - originates in Sun's Java package. + The possessive quantifier syntax is an extension to the Perl syntax. + Jeffrey Friedl originated the idea (and the name) in the first edition + of his book. Mike McCloskey liked it, so implemented it when he built + Sun's Java package, and PCRE copied it from there. When a pattern contains an unlimited repeat inside a subpattern that can itself be repeated an unlimited number of times, the use of an @@ -3395,31 +3575,41 @@ BACK REFERENCES it is always taken as a back reference, and causes an error only if there are not that many capturing left parentheses in the entire pat- tern. In other words, the parentheses that are referenced need not be - to the left of the reference for numbers less than 10. See the subsec- - tion entitled "Non-printing characters" above for further details of - the handling of digits following a backslash. + to the left of the reference for numbers less than 10. A "forward back + reference" of this type can make sense when a repetition is involved + and the subpattern to the right has participated in an earlier itera- + tion. + + It is not possible to have a numerical "forward back reference" to sub- + pattern whose number is 10 or more. However, a back reference to any + subpattern is possible using named parentheses (see below). See also + the subsection entitled "Non-printing characters" above for further + details of the handling of digits following a backslash. - A back reference matches whatever actually matched the capturing sub- - pattern in the current subject string, rather than anything matching + A back reference matches whatever actually matched the capturing sub- + pattern in the current subject string, rather than anything matching the subpattern itself (see "Subpatterns as subroutines" below for a way of doing that). So the pattern (sens|respons)e and \1ibility - matches "sense and sensibility" and "response and responsibility", but - not "sense and responsibility". If caseful matching is in force at the - time of the back reference, the case of letters is relevant. For exam- + matches "sense and sensibility" and "response and responsibility", but + not "sense and responsibility". If caseful matching is in force at the + time of the back reference, the case of letters is relevant. For exam- ple, ((?i)rah)\s+\1 - matches "rah rah" and "RAH RAH", but not "RAH rah", even though the + matches "rah rah" and "RAH RAH", but not "RAH rah", even though the original capturing subpattern is matched caselessly. - Back references to named subpatterns use the Python syntax (?P=name). + Back references to named subpatterns use the Python syntax (?P=name). We could rewrite the above example as follows: - (?<p1>(?i)rah)\s+(?P=p1) + (?P<p1>(?i)rah)\s+(?P=p1) + + A subpattern that is referenced by name may appear in the pattern + before or after the reference. There may be more than one back reference to the same subpattern. If a subpattern has not actually been used in a particular match, any back @@ -3508,8 +3698,8 @@ ASSERTIONS does find an occurrence of "bar" that is not preceded by "foo". The contents of a lookbehind assertion are restricted such that all the strings it matches must have a fixed length. However, if there are sev- - eral alternatives, they do not all have to have the same fixed length. - Thus + eral top-level alternatives, they do not all have to have the same + fixed length. Thus (?<=bullock|donkey) @@ -3622,12 +3812,18 @@ CONDITIONAL SUBPATTERNS tives in the subpattern, a compile-time error occurs. There are three kinds of condition. If the text between the parentheses - consists of a sequence of digits, the condition is satisfied if the - capturing subpattern of that number has previously matched. The number - must be greater than zero. Consider the following pattern, which con- - tains non-significant white space to make it more readable (assume the - PCRE_EXTENDED option) and to divide it into three parts for ease of - discussion: + consists of a sequence of digits, or a sequence of alphanumeric charac- + ters and underscores, the condition is satisfied if the capturing sub- + pattern of that number or name has previously matched. There is a pos- + sible ambiguity here, because subpattern names may consist entirely of + digits. PCRE looks first for a named subpattern; if it cannot find one + and the text consists entirely of digits, it looks for a subpattern of + that number, which must be greater than zero. Using subpattern names + that consist entirely of digits is not recommended. + + Consider the following pattern, which contains non-significant white + space to make it more readable (assume the PCRE_EXTENDED option) and to + divide it into three parts for ease of discussion: ( \( )? [^()]+ (?(1) \) ) @@ -3640,12 +3836,16 @@ CONDITIONAL SUBPATTERNS tern is executed and a closing parenthesis is required. Otherwise, since no-pattern is not present, the subpattern matches nothing. In other words, this pattern matches a sequence of non-parentheses, - optionally enclosed in parentheses. + optionally enclosed in parentheses. Rewriting it to use a named subpat- + tern gives this: - If the condition is the string (R), it is satisfied if a recursive call - to the pattern or subpattern has been made. At "top level", the condi- - tion is false. This is a PCRE extension. Recursive patterns are - described in the next section. + (?P<OPEN> \( )? [^()]+ (?(OPEN) \) ) + + If the condition is the string (R), and there is no subpattern with the + name R, the condition is satisfied if a recursive call to the pattern + or subpattern has been made. At "top level", the condition is false. + This is a PCRE extension. Recursive patterns are described in the next + section. If the condition is not a sequence of digits or (R), it must be an assertion. This may be a positive or negative lookahead or lookbehind @@ -3672,8 +3872,8 @@ COMMENTS at all. If the PCRE_EXTENDED option is set, an unescaped # character outside a - character class introduces a comment that continues up to the next new- - line character in the pattern. + character class introduces a comment that continues to immediately + after the next newline in the pattern. RECURSIVE PATTERNS @@ -3796,50 +3996,51 @@ SUBPATTERNS AS SUBROUTINES (sens|respons)e and (?1)ibility is used, it does match "sense and responsibility" as well as the other - two strings. Such references must, however, follow the subpattern to - which they refer. + two strings. Such references, if given numerically, must follow the + subpattern to which they refer. However, named references can refer to + later subpatterns. Like recursive subpatterns, a "subroutine" call is always treated as an - atomic group. That is, once it has matched some of the subject string, - it is never re-entered, even if it contains untried alternatives and + atomic group. That is, once it has matched some of the subject string, + it is never re-entered, even if it contains untried alternatives and there is a subsequent matching failure. CALLOUTS Perl has a feature whereby using the sequence (?{...}) causes arbitrary - Perl code to be obeyed in the middle of matching a regular expression. + Perl code to be obeyed in the middle of matching a regular expression. This makes it possible, amongst other things, to extract different sub- strings that match the same pair of parentheses when there is a repeti- tion. PCRE provides a similar feature, but of course it cannot obey arbitrary Perl code. The feature is called "callout". The caller of PCRE provides - an external function by putting its entry point in the global variable - pcre_callout. By default, this variable contains NULL, which disables + an external function by putting its entry point in the global variable + pcre_callout. By default, this variable contains NULL, which disables all calling out. - Within a regular expression, (?C) indicates the points at which the - external function is to be called. If you want to identify different - callout points, you can put a number less than 256 after the letter C. - The default value is zero. For example, this pattern has two callout + Within a regular expression, (?C) indicates the points at which the + external function is to be called. If you want to identify different + callout points, you can put a number less than 256 after the letter C. + The default value is zero. For example, this pattern has two callout points: (?C1)abc(?C2)def If the PCRE_AUTO_CALLOUT flag is passed to pcre_compile(), callouts are - automatically installed before each item in the pattern. They are all + automatically installed before each item in the pattern. They are all numbered 255. During matching, when PCRE reaches a callout point (and pcre_callout is - set), the external function is called. It is provided with the number - of the callout, the position in the pattern, and, optionally, one item - of data originally supplied by the caller of pcre_exec(). The callout - function may cause matching to proceed, to backtrack, or to fail alto- + set), the external function is called. It is provided with the number + of the callout, the position in the pattern, and, optionally, one item + of data originally supplied by the caller of pcre_exec(). The callout + function may cause matching to proceed, to backtrack, or to fail alto- gether. A complete description of the interface to the callout function is given in the pcrecallout documentation. -Last updated: 24 January 2006 +Last updated: 06 June 2006 Copyright (c) 1997-2006 University of Cambridge. ------------------------------------------------------------------------------ @@ -4847,3 +5048,106 @@ PCRE SAMPLE PROGRAM Last updated: 09 September 2004 Copyright (c) 1997-2004 University of Cambridge. ------------------------------------------------------------------------------ +PCRESTACK(3) PCRESTACK(3) + + +NAME + PCRE - Perl-compatible regular expressions + + +PCRE DISCUSSION OF STACK USAGE + + When you call pcre_exec(), it makes use of an internal function called + match(). This calls itself recursively at branch points in the pattern, + in order to remember the state of the match so that it can back up and + try a different alternative if the first one fails. As matching pro- + ceeds deeper and deeper into the tree of possibilities, the recursion + depth increases. + + Not all calls of match() increase the recursion depth; for an item such + as a* it may be called several times at the same level, after matching + different numbers of a's. Furthermore, in a number of cases where the + result of the recursive call would immediately be passed back as the + result of the current call (a "tail recursion"), the function is just + restarted instead. + + The pcre_dfa_exec() function operates in an entirely different way, and + hardly uses recursion at all. The limit on its complexity is the amount + of workspace it is given. The comments that follow do NOT apply to + pcre_dfa_exec(); they are relevant only for pcre_exec(). + + You can set limits on the number of times that match() is called, both + in total and recursively. If the limit is exceeded, an error occurs. + For details, see the section on extra data for pcre_exec() in the + pcreapi documentation. + + Each time that match() is actually called recursively, it uses memory + from the process stack. For certain kinds of pattern and data, very + large amounts of stack may be needed, despite the recognition of "tail + recursion". You can often reduce the amount of recursion, and there- + fore the amount of stack used, by modifying the pattern that is being + matched. Consider, for example, this pattern: + + ([^<]|<(?!inet))+ + + It matches from wherever it starts until it encounters "<inet" or the + end of the data, and is the kind of pattern that might be used when + processing an XML file. Each iteration of the outer parentheses matches + either one character that is not "<" or a "<" that is not followed by + "inet". However, each time a parenthesis is processed, a recursion + occurs, so this formulation uses a stack frame for each matched charac- + ter. For a long string, a lot of stack is required. Consider now this + rewritten pattern, which matches exactly the same strings: + + ([^<]++|<(?!inet)) + + This uses very much less stack, because runs of characters that do not + contain "<" are "swallowed" in one item inside the parentheses. Recur- + sion happens only when a "<" character that is not followed by "inet" + is encountered (and we assume this is relatively rare). A possessive + quantifier is used to stop any backtracking into the runs of non-"<" + characters, but that is not related to stack usage. + + In environments where stack memory is constrained, you might want to + compile PCRE to use heap memory instead of stack for remembering back- + up points. This makes it run a lot more slowly, however. Details of how + to do this are given in the pcrebuild documentation. + + In Unix-like environments, there is not often a problem with the stack, + though the default limit on stack size varies from system to system. + Values from 8Mb to 64Mb are common. You can find your default limit by + running the command: + + ulimit -s + + The effect of running out of stack is often SIGSEGV, though sometimes + an error message is given. You can normally increase the limit on stack + size by code such as this: + + struct rlimit rlim; + getrlimit(RLIMIT_STACK, &rlim); + rlim.rlim_cur = 100*1024*1024; + setrlimit(RLIMIT_STACK, &rlim); + + This reads the current limits (soft and hard) using getrlimit(), then + attempts to increase the soft limit to 100Mb using setrlimit(). You + must do this before calling pcre_exec(). + + PCRE has an internal counter that can be used to limit the depth of + recursion, and thus cause pcre_exec() to give an error code before it + runs out of stack. By default, the limit is very large, and unlikely + ever to operate. It can be changed when PCRE is built, and it can also + be set when pcre_exec() is called. For details of these interfaces, see + the pcrebuild and pcreapi documentation. + + As a very rough rule of thumb, you should reckon on about 500 bytes per + recursion. Thus, if you want to limit your stack usage to 8Mb, you + should set the limit at 16000 recursions. A 64Mb stack, on the other + hand, can support around 128000 recursions. The pcretest test program + has a command line option (-S) that can be used to increase its stack. + +Last updated: 29 June 2006 +Copyright (c) 1997-2006 University of Cambridge. +------------------------------------------------------------------------------ + + |