Parent Directory
|
Revision Log
|
Patch
revision 454 by ph10, Tue Sep 22 09:42:11 2009 UTC | revision 461 by ph10, Mon Oct 5 10:59:35 2009 UTC | |
---|---|---|
# | Line 2 | Line 2 |
2 | This file contains a concatenation of the PCRE man pages, converted to plain | This file contains a concatenation of the PCRE man pages, converted to plain |
3 | text format for ease of searching with a text editor, or for use on systems | text format for ease of searching with a text editor, or for use on systems |
4 | that do not have a man page processor. The small individual files that give | that do not have a man page processor. The small individual files that give |
5 | synopses of each function in the library have not been included. Neither has | synopses of each function in the library have not been included. Neither has |
6 | the pcredemo program. There are separate text files for the pcregrep and | the pcredemo program. There are separate text files for the pcregrep and |
7 | pcretest commands. | pcretest commands. |
8 | ----------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
# | Line 19 INTRODUCTION | Line 19 INTRODUCTION |
19 | ||
20 | The PCRE library is a set of functions that implement regular expres- | The PCRE library is a set of functions that implement regular expres- |
21 | sion pattern matching using the same syntax and semantics as Perl, with | sion pattern matching using the same syntax and semantics as Perl, with |
22 | just a few differences. Certain features that appeared in Python and | just a few differences. Some features that appeared in Python and PCRE |
23 | PCRE before they appeared in Perl are also available using the Python | before they appeared in Perl are also available using the Python syn- |
24 | syntax. There is also some support for certain .NET and Oniguruma syn- | tax, there is some support for one or two .NET and Oniguruma syntax |
25 | tax items, and there is an option for requesting some minor changes | items, and there is an option for requesting some minor changes that |
26 | that give better JavaScript compatibility. | give better JavaScript compatibility. |
27 | ||
28 | The current implementation of PCRE (release 8.xx) corresponds approxi- | The current implementation of PCRE corresponds approximately with Perl |
29 | mately with Perl 5.10, including support for UTF-8 encoded strings and | 5.10, including support for UTF-8 encoded strings and Unicode general |
30 | Unicode general category properties. However, UTF-8 and Unicode support | category properties. However, UTF-8 and Unicode support has to be |
31 | has to be explicitly enabled; it is not the default. The Unicode tables | explicitly enabled; it is not the default. The Unicode tables corre- |
32 | correspond to Unicode release 5.1. | spond to Unicode release 5.1. |
33 | ||
34 | In addition to the Perl-compatible matching function, PCRE contains an | In addition to the Perl-compatible matching function, PCRE contains an |
35 | alternative matching function that matches the same compiled patterns | alternative function that matches the same compiled patterns in a dif- |
36 | in a different way. In certain circumstances, the alternative function | ferent way. In certain circumstances, the alternative function has some |
37 | has some advantages. For a discussion of the two matching algorithms, | advantages. For a discussion of the two matching algorithms, see the |
38 | see the pcrematching page. | pcrematching page. |
39 | ||
40 | PCRE is written in C and released as a C library. A number of people | PCRE is written in C and released as a C library. A number of people |
41 | have written wrappers and interfaces of various kinds. In particular, | have written wrappers and interfaces of various kinds. In particular, |
# | Line 55 INTRODUCTION | Line 55 INTRODUCTION |
55 | library is built. The pcre_config() function makes it possible for a | library is built. The pcre_config() function makes it possible for a |
56 | client to discover which features are available. The features them- | client to discover which features are available. The features them- |
57 | selves are described in the pcrebuild page. Documentation about build- | selves are described in the pcrebuild page. Documentation about build- |
58 | ing PCRE for various operating systems can be found in the README file | ing PCRE for various operating systems can be found in the README and |
59 | in the source distribution. | NON-UNIX-USE files in the source distribution. |
60 | ||
61 | The library contains a number of undocumented internal functions and | The library contains a number of undocumented internal functions and |
62 | data tables that are used by more than one of the exported external | data tables that are used by more than one of the exported external |
# | Line 89 USER DOCUMENTATION | Line 89 USER DOCUMENTATION |
89 | pcrepartial details of the partial matching facility | pcrepartial details of the partial matching facility |
90 | pcrepattern syntax and semantics of supported | pcrepattern syntax and semantics of supported |
91 | regular expressions | regular expressions |
pcresyntax quick syntax reference | ||
92 | pcreperform discussion of performance issues | pcreperform discussion of performance issues |
93 | pcreposix the POSIX-compatible C API | pcreposix the POSIX-compatible C API |
94 | pcreprecompile details of saving and re-using precompiled patterns | pcreprecompile details of saving and re-using precompiled patterns |
95 | pcresample discussion of the pcredemo program | pcresample discussion of the pcredemo program |
96 | pcrestack discussion of stack usage | pcrestack discussion of stack usage |
97 | pcresyntax quick syntax reference | |
98 | pcretest description of the pcretest testing command | pcretest description of the pcretest testing command |
99 | ||
100 | In addition, in the "man" and HTML formats, there is a short page for | In addition, in the "man" and HTML formats, there is a short page for |
# | Line 142 UTF-8 AND UNICODE PROPERTY SUPPORT | Line 142 UTF-8 AND UNICODE PROPERTY SUPPORT |
142 | with the PCRE_UTF8 option flag, or the pattern must start with the | with the PCRE_UTF8 option flag, or the pattern must start with the |
143 | sequence (*UTF8). When either of these is the case, both the pattern | sequence (*UTF8). When either of these is the case, both the pattern |
144 | and any subject strings that are matched against it are treated as | and any subject strings that are matched against it are treated as |
145 | UTF-8 strings instead of just strings of bytes. | UTF-8 strings instead of strings of 1-byte characters. |
146 | ||
147 | If you compile PCRE with UTF-8 support, but do not use it at run time, | If you compile PCRE with UTF-8 support, but do not use it at run time, |
148 | the library will be a bit bigger, but the additional run time overhead | the library will be a bit bigger, but the additional run time overhead |
# | Line 263 AUTHOR | Line 263 AUTHOR |
263 | ||
264 | REVISION | REVISION |
265 | ||
266 | Last updated: 01 September 2009 | Last updated: 28 September 2009 |
267 | Copyright (c) 1997-2009 University of Cambridge. | Copyright (c) 1997-2009 University of Cambridge. |
268 | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ |
269 | ||
270 | ||
271 | PCREBUILD(3) PCREBUILD(3) | PCREBUILD(3) PCREBUILD(3) |
272 | ||
273 | ||
# | Line 324 UTF-8 SUPPORT | Line 324 UTF-8 SUPPORT |
324 | to the configure command. Of itself, this does not make PCRE treat | to the configure command. Of itself, this does not make PCRE treat |
325 | strings as UTF-8. As well as compiling PCRE with this option, you also | strings as UTF-8. As well as compiling PCRE with this option, you also |
326 | have have to set the PCRE_UTF8 option when you call the pcre_compile() | have have to set the PCRE_UTF8 option when you call the pcre_compile() |
327 | function. | or pcre_compile2() functions. |
328 | ||
329 | If you set --enable-utf8 when compiling in an EBCDIC environment, PCRE | If you set --enable-utf8 when compiling in an EBCDIC environment, PCRE |
330 | expects its input to be either ASCII or UTF-8 (depending on the runtime | expects its input to be either ASCII or UTF-8 (depending on the runtime |
# | Line 432 HANDLING VERY LARGE PATTERNS | Line 432 HANDLING VERY LARGE PATTERNS |
432 | nation metacharacter). By default, two-byte values are used for these | nation metacharacter). By default, two-byte values are used for these |
433 | offsets, leading to a maximum size for a compiled pattern of around | offsets, leading to a maximum size for a compiled pattern of around |
434 | 64K. This is sufficient to handle all but the most gigantic patterns. | 64K. This is sufficient to handle all but the most gigantic patterns. |
435 | Nevertheless, some people do want to process enormous patterns, so it | Nevertheless, some people do want to process truyl enormous patterns, |
436 | is possible to compile PCRE to use three-byte or four-byte offsets by | so it is possible to compile PCRE to use three-byte or four-byte off- |
437 | adding a setting such as | sets by adding a setting such as |
438 | ||
439 | --with-link-size=3 | --with-link-size=3 |
440 | ||
# | Line 461 AVOIDING EXCESSIVE STACK USAGE | Line 461 AVOIDING EXCESSIVE STACK USAGE |
461 | to the configure command. With this configuration, PCRE will use the | to the configure command. With this configuration, PCRE will use the |
462 | pcre_stack_malloc and pcre_stack_free variables to call memory manage- | pcre_stack_malloc and pcre_stack_free variables to call memory manage- |
463 | ment functions. By default these point to malloc() and free(), but you | ment functions. By default these point to malloc() and free(), but you |
464 | can replace the pointers so that your own functions are used. | can replace the pointers so that your own functions are used instead. |
465 | ||
466 | Separate functions are provided rather than using pcre_malloc and | Separate functions are provided rather than using pcre_malloc and |
467 | pcre_free because the usage is very predictable: the block sizes | pcre_free because the usage is very predictable: the block sizes |
# | Line 469 AVOIDING EXCESSIVE STACK USAGE | Line 469 AVOIDING EXCESSIVE STACK USAGE |
469 | reverse order. A calling program might be able to implement optimized | reverse order. A calling program might be able to implement optimized |
470 | functions that perform better than malloc() and free(). PCRE runs | functions that perform better than malloc() and free(). PCRE runs |
471 | noticeably more slowly when built in this way. This option affects only | noticeably more slowly when built in this way. This option affects only |
472 | the pcre_exec() function; it is not relevant for the the | the pcre_exec() function; it is not relevant for pcre_dfa_exec(). |
pcre_dfa_exec() function. | ||
473 | ||
474 | ||
475 | LIMITING PCRE RESOURCE USAGE | LIMITING PCRE RESOURCE USAGE |
476 | ||
477 | Internally, PCRE has a function called match(), which it calls repeat- | Internally, PCRE has a function called match(), which it calls repeat- |
478 | edly (sometimes recursively) when matching a pattern with the | edly (sometimes recursively) when matching a pattern with the |
479 | pcre_exec() function. By controlling the maximum number of times this | pcre_exec() function. By controlling the maximum number of times this |
480 | function may be called during a single matching operation, a limit can | function may be called during a single matching operation, a limit can |
481 | be placed on the resources used by a single call to pcre_exec(). The | be placed on the resources used by a single call to pcre_exec(). The |
482 | limit can be changed at run time, as described in the pcreapi documen- | limit can be changed at run time, as described in the pcreapi documen- |
483 | tation. The default is 10 million, but this can be changed by adding a | tation. The default is 10 million, but this can be changed by adding a |
484 | setting such as | setting such as |
485 | ||
486 | --with-match-limit=500000 | --with-match-limit=500000 |
487 | ||
488 | to the configure command. This setting has no effect on the | to the configure command. This setting has no effect on the |
489 | pcre_dfa_exec() matching function. | pcre_dfa_exec() matching function. |
490 | ||
491 | In some environments it is desirable to limit the depth of recursive | In some environments it is desirable to limit the depth of recursive |
492 | calls of match() more strictly than the total number of calls, in order | calls of match() more strictly than the total number of calls, in order |
493 | to restrict the maximum amount of stack (or heap, if --disable-stack- | to restrict the maximum amount of stack (or heap, if --disable-stack- |
494 | for-recursion is specified) that is used. A second limit controls this; | for-recursion is specified) that is used. A second limit controls this; |
495 | it defaults to the value that is set for --with-match-limit, which | it defaults to the value that is set for --with-match-limit, which |
496 | imposes no additional constraints. However, you can set a lower limit | imposes no additional constraints. However, you can set a lower limit |
497 | by adding, for example, | by adding, for example, |
498 | ||
499 | --with-match-limit-recursion=10000 | --with-match-limit-recursion=10000 |
500 | ||
501 | to the configure command. This value can also be overridden at run | to the configure command. This value can also be overridden at run |
502 | time. | time. |
503 | ||
504 | ||
505 | CREATING CHARACTER TABLES AT BUILD TIME | CREATING CHARACTER TABLES AT BUILD TIME |
506 | ||
507 | PCRE uses fixed tables for processing characters whose code values are | PCRE uses fixed tables for processing characters whose code values are |
508 | less than 256. By default, PCRE is built with a set of tables that are | less than 256. By default, PCRE is built with a set of tables that are |
509 | distributed in the file pcre_chartables.c.dist. These tables are for | distributed in the file pcre_chartables.c.dist. These tables are for |
510 | ASCII codes only. If you add | ASCII codes only. If you add |
511 | ||
512 | --enable-rebuild-chartables | --enable-rebuild-chartables |
513 | ||
514 | to the configure command, the distributed tables are no longer used. | to the configure command, the distributed tables are no longer used. |
515 | Instead, a program called dftables is compiled and run. This outputs | Instead, a program called dftables is compiled and run. This outputs |
516 | the source for new set of tables, created in the default locale of your | the source for new set of tables, created in the default locale of your |
517 | C runtime system. (This method of replacing the tables does not work if | C runtime system. (This method of replacing the tables does not work if |
518 | you are cross compiling, because dftables is run on the local host. If | you are cross compiling, because dftables is run on the local host. If |
519 | you need to create alternative tables when cross compiling, you will | you need to create alternative tables when cross compiling, you will |
520 | have to do so "by hand".) | have to do so "by hand".) |
521 | ||
522 | ||
523 | USING EBCDIC CODE | USING EBCDIC CODE |
524 | ||
525 | PCRE assumes by default that it will run in an environment where the | PCRE assumes by default that it will run in an environment where the |
526 | character code is ASCII (or Unicode, which is a superset of ASCII). | character code is ASCII (or Unicode, which is a superset of ASCII). |
527 | This is the case for most computer operating systems. PCRE can, how- | This is the case for most computer operating systems. PCRE can, how- |
528 | ever, be compiled to run in an EBCDIC environment by adding | ever, be compiled to run in an EBCDIC environment by adding |
529 | ||
530 | --enable-ebcdic | --enable-ebcdic |
531 | ||
532 | to the configure command. This setting implies --enable-rebuild-charta- | to the configure command. This setting implies --enable-rebuild-charta- |
533 | bles. You should only use it if you know that you are in an EBCDIC | bles. You should only use it if you know that you are in an EBCDIC |
534 | environment (for example, an IBM mainframe operating system). The | environment (for example, an IBM mainframe operating system). The |
535 | --enable-ebcdic option is incompatible with --enable-utf8. | --enable-ebcdic option is incompatible with --enable-utf8. |
536 | ||
537 | ||
# | Line 546 PCREGREP OPTIONS FOR COMPRESSED FILE SUP | Line 545 PCREGREP OPTIONS FOR COMPRESSED FILE SUP |
545 | --enable-pcregrep-libbz2 | --enable-pcregrep-libbz2 |
546 | ||
547 | to the configure command. These options naturally require that the rel- | to the configure command. These options naturally require that the rel- |
548 | evant libraries are installed on your system. Configuration will fail | evant libraries are installed on your system. Configuration will fail |
549 | if they are not. | if they are not. |
550 | ||
551 | ||
# | Line 556 PCRETEST OPTION FOR LIBREADLINE SUPPORT | Line 555 PCRETEST OPTION FOR LIBREADLINE SUPPORT |
555 | ||
556 | --enable-pcretest-libreadline | --enable-pcretest-libreadline |
557 | ||
558 | to the configure command, pcretest is linked with the libreadline | to the configure command, pcretest is linked with the libreadline |
559 | library, and when its input is from a terminal, it reads it using the | library, and when its input is from a terminal, it reads it using the |
560 | readline() function. This provides line-editing and history facilities. | readline() function. This provides line-editing and history facilities. |
561 | Note that libreadline is GPL-licenced, so if you distribute a binary of | Note that libreadline is GPL-licensed, so if you distribute a binary of |
562 | pcretest linked in this way, there may be licensing issues. | pcretest linked in this way, there may be licensing issues. |
563 | ||
564 | Setting this option causes the -lreadline option to be added to the | Setting this option causes the -lreadline option to be added to the |
565 | pcretest build. In many operating environments with a sytem-installed | pcretest build. In many operating environments with a sytem-installed |
566 | libreadline this is sufficient. However, in some environments (e.g. if | libreadline this is sufficient. However, in some environments (e.g. if |
567 | an unmodified distribution version of readline is in use), some extra | an unmodified distribution version of readline is in use), some extra |
568 | configuration may be necessary. The INSTALL file for libreadline says | configuration may be necessary. The INSTALL file for libreadline says |
569 | this: | this: |
570 | ||
571 | "Readline uses the termcap functions, but does not link with the | "Readline uses the termcap functions, but does not link with the |
572 | termcap or curses library itself, allowing applications which link | termcap or curses library itself, allowing applications which link |
573 | with readline the to choose an appropriate library." | with readline the to choose an appropriate library." |
574 | ||
575 | If your environment has not been set up so that an appropriate library | If your environment has not been set up so that an appropriate library |
576 | is automatically included, you may need to add something like | is automatically included, you may need to add something like |
577 | ||
578 | LIBS="-ncurses" | LIBS="-ncurses" |
# | Line 595 AUTHOR | Line 594 AUTHOR |
594 | ||
595 | REVISION | REVISION |
596 | ||
597 | Last updated: 06 September 2009 | Last updated: 29 September 2009 |
598 | Copyright (c) 1997-2009 University of Cambridge. | Copyright (c) 1997-2009 University of Cambridge. |
599 | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ |
600 | ||
601 | ||
602 | PCREMATCHING(3) PCREMATCHING(3) | PCREMATCHING(3) PCREMATCHING(3) |
603 | ||
604 | ||
# | Line 683 THE ALTERNATIVE MATCHING ALGORITHM | Line 682 THE ALTERNATIVE MATCHING ALGORITHM |
682 | though it is not implemented as a traditional finite state machine (it | though it is not implemented as a traditional finite state machine (it |
683 | keeps multiple states active simultaneously). | keeps multiple states active simultaneously). |
684 | ||
685 | Although the general principle of this matching algorithm is that it | |
686 | scans the subject string only once, without backtracking, there is one | |
687 | exception: when a lookaround assertion is encountered, the characters | |
688 | following or preceding the current point have to be independently | |
689 | inspected. | |
690 | ||
691 | The scan continues until either the end of the subject is reached, or | The scan continues until either the end of the subject is reached, or |
692 | there are no more unterminated paths. At this point, terminated paths | there are no more unterminated paths. At this point, terminated paths |
693 | represent the different matching possibilities (if there are none, the | represent the different matching possibilities (if there are none, the |
694 | match has failed). Thus, if there is more than one possible match, | match has failed). Thus, if there is more than one possible match, |
695 | this algorithm finds all of them, and in particular, it finds the long- | this algorithm finds all of them, and in particular, it finds the long- |
696 | est. In PCRE, there is an option to stop the algorithm after the first | est. There is an option to stop the algorithm after the first match |
697 | match (which is necessarily the shortest) has been found. | (which is necessarily the shortest) is found. |
698 | ||
699 | Note that all the matches that are found start at the same point in the | Note that all the matches that are found start at the same point in the |
700 | subject. If the pattern | subject. If the pattern |
# | Line 701 THE ALTERNATIVE MATCHING ALGORITHM | Line 706 THE ALTERNATIVE MATCHING ALGORITHM |
706 | at the fourth character of the subject. The algorithm does not automat- | at the fourth character of the subject. The algorithm does not automat- |
707 | ically move on to find matches that start at later positions. | ically move on to find matches that start at later positions. |
708 | ||
Although the general principle of this matching algorithm is that it | ||
scans the subject string only once, without backtracking, there is one | ||
exception: when a lookbehind assertion is encountered, the preceding | ||
characters have to be re-inspected. | ||
709 | There are a number of features of PCRE regular expressions that are not | There are a number of features of PCRE regular expressions that are not |
710 | supported by the alternative matching algorithm. They are as follows: | supported by the alternative matching algorithm. They are as follows: |
711 | ||
712 | 1. Because the algorithm finds all possible matches, the greedy or | 1. Because the algorithm finds all possible matches, the greedy or |
713 | ungreedy nature of repetition quantifiers is not relevant. Greedy and | ungreedy nature of repetition quantifiers is not relevant. Greedy and |
714 | ungreedy quantifiers are treated in exactly the same way. However, pos- | ungreedy quantifiers are treated in exactly the same way. However, pos- |
715 | sessive quantifiers can make a difference when what follows could also | sessive quantifiers can make a difference when what follows could also |
716 | match what is quantified, for example in a pattern like this: | match what is quantified, for example in a pattern like this: |
717 | ||
718 | ^a++\w! | ^a++\w! |
719 | ||
720 | This pattern matches "aaab!" but not "aaa!", which would be matched by | This pattern matches "aaab!" but not "aaa!", which would be matched by |
721 | a non-possessive quantifier. Similarly, if an atomic group is present, | a non-possessive quantifier. Similarly, if an atomic group is present, |
722 | it is matched as if it were a standalone pattern at the current point, | it is matched as if it were a standalone pattern at the current point, |
723 | and the longest match is then "locked in" for the rest of the overall | and the longest match is then "locked in" for the rest of the overall |
724 | pattern. | pattern. |
725 | ||
726 | 2. When dealing with multiple paths through the tree simultaneously, it | 2. When dealing with multiple paths through the tree simultaneously, it |
727 | is not straightforward to keep track of captured substrings for the | is not straightforward to keep track of captured substrings for the |
728 | different matching possibilities, and PCRE's implementation of this | different matching possibilities, and PCRE's implementation of this |
729 | algorithm does not attempt to do this. This means that no captured sub- | algorithm does not attempt to do this. This means that no captured sub- |
730 | strings are available. | strings are available. |
731 | ||
732 | 3. Because no substrings are captured, back references within the pat- | 3. Because no substrings are captured, back references within the pat- |
733 | tern are not supported, and cause errors if encountered. | tern are not supported, and cause errors if encountered. |
734 | ||
735 | 4. For the same reason, conditional expressions that use a backrefer- | 4. For the same reason, conditional expressions that use a backrefer- |
736 | ence as the condition or test for a specific group recursion are not | ence as the condition or test for a specific group recursion are not |
737 | supported. | supported. |
738 | ||
739 | 5. Because many paths through the tree may be active, the \K escape | 5. Because many paths through the tree may be active, the \K escape |
740 | sequence, which resets the start of the match when encountered (but may | sequence, which resets the start of the match when encountered (but may |
741 | be on some paths and not on others), is not supported. It causes an | be on some paths and not on others), is not supported. It causes an |
742 | error if encountered. | error if encountered. |
743 | ||
744 | 6. Callouts are supported, but the value of the capture_top field is | 6. Callouts are supported, but the value of the capture_top field is |
745 | always 1, and the value of the capture_last field is always -1. | always 1, and the value of the capture_last field is always -1. |
746 | ||
747 | 7. The \C escape sequence, which (in the standard algorithm) matches a | 7. The \C escape sequence, which (in the standard algorithm) matches a |
748 | single byte, even in UTF-8 mode, is not supported because the alterna- | single byte, even in UTF-8 mode, is not supported because the alterna- |
749 | tive algorithm moves through the subject string one character at a | tive algorithm moves through the subject string one character at a |
750 | time, for all active paths through the tree. | time, for all active paths through the tree. |
751 | ||
752 | 8. Except for (*FAIL), the backtracking control verbs such as (*PRUNE) | 8. Except for (*FAIL), the backtracking control verbs such as (*PRUNE) |
753 | are not supported. (*FAIL) is supported, and behaves like a failing | are not supported. (*FAIL) is supported, and behaves like a failing |
754 | negative assertion. | negative assertion. |
755 | ||
756 | ||
757 | ADVANTAGES OF THE ALTERNATIVE ALGORITHM | ADVANTAGES OF THE ALTERNATIVE ALGORITHM |
758 | ||
759 | Using the alternative matching algorithm provides the following advan- | Using the alternative matching algorithm provides the following advan- |
760 | tages: | tages: |
761 | ||
762 | 1. All possible matches (at a single point in the subject) are automat- | 1. All possible matches (at a single point in the subject) are automat- |
763 | ically found, and in particular, the longest match is found. To find | ically found, and in particular, the longest match is found. To find |
764 | more than one match using the standard algorithm, you have to do kludgy | more than one match using the standard algorithm, you have to do kludgy |
765 | things with callouts. | things with callouts. |
766 | ||
767 | 2. Because the alternative algorithm scans the subject string just | 2. Because the alternative algorithm scans the subject string just |
768 | once, and never needs to backtrack, it is possible to pass very long | once, and never needs to backtrack, it is possible to pass very long |
769 | subject strings to the matching function in several pieces, checking | subject strings to the matching function in several pieces, checking |
770 | for partial matching each time. | for partial matching each time. The pcrepartial documentation gives |
771 | details of partial matching. | |
772 | ||
773 | ||
774 | DISADVANTAGES OF THE ALTERNATIVE ALGORITHM | DISADVANTAGES OF THE ALTERNATIVE ALGORITHM |
# | Line 793 AUTHOR | Line 794 AUTHOR |
794 | ||
795 | REVISION | REVISION |
796 | ||
797 | Last updated: 05 September 2009 | Last updated: 29 September 2009 |
798 | Copyright (c) 1997-2009 University of Cambridge. | Copyright (c) 1997-2009 University of Cambridge. |
799 | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ |
800 | ||
801 | ||
802 | PCREAPI(3) PCREAPI(3) | PCREAPI(3) PCREAPI(3) |
803 | ||
804 | ||
# | Line 1126 COMPILING A PATTERN | Line 1127 COMPILING A PATTERN |
1127 | Either of the functions pcre_compile() or pcre_compile2() can be called | Either of the functions pcre_compile() or pcre_compile2() can be called |
1128 | to compile a pattern into an internal form. The only difference between | to compile a pattern into an internal form. The only difference between |
1129 | the two interfaces is that pcre_compile2() has an additional argument, | the two interfaces is that pcre_compile2() has an additional argument, |
1130 | errorcodeptr, via which a numerical error code can be returned. | errorcodeptr, via which a numerical error code can be returned. To |
1131 | avoid too much repetition, we refer just to pcre_compile() below, but | |
1132 | the information applies equally to pcre_compile2(). | |
1133 | ||
1134 | The pattern is a C string terminated by a binary zero, and is passed in | The pattern is a C string terminated by a binary zero, and is passed in |
1135 | the pattern argument. A pointer to a single block of memory that is | the pattern argument. A pointer to a single block of memory that is |
# | Line 1144 COMPILING A PATTERN | Line 1147 COMPILING A PATTERN |
1147 | The options argument contains various bit settings that affect the com- | The options argument contains various bit settings that affect the com- |
1148 | pilation. It should be zero if no options are required. The available | pilation. It should be zero if no options are required. The available |
1149 | options are described below. Some of them (in particular, those that | options are described below. Some of them (in particular, those that |
1150 | are compatible with Perl, but also some others) can also be set and | are compatible with Perl, but some others as well) can also be set and |
1151 | unset from within the pattern (see the detailed description in the | unset from within the pattern (see the detailed description in the |
1152 | pcrepattern documentation). For those options that can be different in | pcrepattern documentation). For those options that can be different in |
1153 | different parts of the pattern, the contents of the options argument | different parts of the pattern, the contents of the options argument |
1154 | specifies their initial settings at the start of compilation and execu- | specifies their settings at the start of compilation and execution. The |
1155 | tion. The PCRE_ANCHORED and PCRE_NEWLINE_xxx options can be set at the | PCRE_ANCHORED, PCRE_BSR_xxx, and PCRE_NEWLINE_xxx options can be set at |
1156 | time of matching as well as at compile time. | the time of matching as well as at compile time. |
1157 | ||
1158 | If errptr is NULL, pcre_compile() returns NULL immediately. Otherwise, | If errptr is NULL, pcre_compile() returns NULL immediately. Otherwise, |
1159 | if compilation of a pattern fails, pcre_compile() returns NULL, and | if compilation of a pattern fails, pcre_compile() returns NULL, and |
1160 | sets the variable pointed to by errptr to point to a textual error mes- | sets the variable pointed to by errptr to point to a textual error mes- |
1161 | sage. This is a static string that is part of the library. You must not | sage. This is a static string that is part of the library. You must not |
1162 | try to free it. The byte offset from the start of the pattern to the | try to free it. The byte offset from the start of the pattern to the |
1163 | character that was being processes when the error was discovered is | character that was being processed when the error was discovered is |
1164 | placed in the variable pointed to by erroffset, which must not be NULL. | placed in the variable pointed to by erroffset, which must not be NULL. |
1165 | If it is, an immediate error is given. Some errors are not detected | If it is, an immediate error is given. Some errors are not detected |
1166 | until checks are carried out when the whole pattern has been scanned; | until checks are carried out when the whole pattern has been scanned; |
# | Line 1491 STUDYING A PATTERN | Line 1494 STUDYING A PATTERN |
1494 | the results of the study. | the results of the study. |
1495 | ||
1496 | The returned value from pcre_study() can be passed directly to | The returned value from pcre_study() can be passed directly to |
1497 | pcre_exec(). However, a pcre_extra block also contains other fields | pcre_exec() or pcre_dfa_exec(). However, a pcre_extra block also con- |
1498 | that can be set by the caller before the block is passed; these are | tains other fields that can be set by the caller before the block is |
1499 | described below in the section on matching a pattern. | passed; these are described below in the section on matching a pattern. |
1500 | ||
1501 | If studying the pattern does not produce any additional information | If studying the pattern does not produce any useful information, |
1502 | pcre_study() returns NULL. In that circumstance, if the calling program | pcre_study() returns NULL. In that circumstance, if the calling program |
1503 | 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() or |
1504 | its own pcre_extra block. | pcre_dfa_exec(), it must set up its own pcre_extra block. |
1505 | ||
1506 | The second argument of pcre_study() contains option bits. At present, | The second argument of pcre_study() contains option bits. At present, |
1507 | no options are defined, and this argument should always be zero. | no options are defined, and this argument should always be zero. |
# | Line 1518 STUDYING A PATTERN | Line 1521 STUDYING A PATTERN |
1521 | 0, /* no options exist */ | 0, /* no options exist */ |
1522 | &error); /* set to NULL or points to a message */ | &error); /* set to NULL or points to a message */ |
1523 | ||
1524 | At present, studying a pattern is useful only for non-anchored patterns | Studying a pattern does two things: first, a lower bound for the length |
1525 | that do not have a single fixed starting character. A bitmap of possi- | of subject string that is needed to match the pattern is computed. This |
1526 | ble starting bytes is created. | does not mean that there are any strings of that length that match, but |
1527 | it does guarantee that no shorter strings match. The value is used by | |
1528 | pcre_exec() and pcre_dfa_exec() to avoid wasting time by trying to | |
1529 | match strings that are shorter than the lower bound. You can find out | |
1530 | the value in a calling program via the pcre_fullinfo() function. | |
1531 | ||
1532 | Studying a pattern is also useful for non-anchored patterns that do not | |
1533 | have a single fixed starting character. A bitmap of possible starting | |
1534 | bytes is created. This speeds up finding a position in the subject at | |
1535 | which to start matching. | |
1536 | ||
1537 | ||
1538 | LOCALE SUPPORT | LOCALE SUPPORT |
1539 | ||
1540 | PCRE handles caseless matching, and determines whether characters are | PCRE handles caseless matching, and determines whether characters are |
1541 | letters, digits, or whatever, by reference to a set of tables, indexed | letters, digits, or whatever, by reference to a set of tables, indexed |
1542 | by character value. When running in UTF-8 mode, this applies only to | by character value. When running in UTF-8 mode, this applies only to |
1543 | characters with codes less than 128. Higher-valued codes never match | characters with codes less than 128. Higher-valued codes never match |
1544 | escapes such as \w or \d, but can be tested with \p if PCRE is built | escapes such as \w or \d, but can be tested with \p if PCRE is built |
1545 | with Unicode character property support. The use of locales with Uni- | with Unicode character property support. The use of locales with Uni- |
1546 | code is discouraged. If you are handling characters with codes greater | code is discouraged. If you are handling characters with codes greater |
1547 | than 128, you should either use UTF-8 and Unicode, or use locales, but | than 128, you should either use UTF-8 and Unicode, or use locales, but |
1548 | not try to mix the two. | not try to mix the two. |
1549 | ||
1550 | PCRE contains an internal set of tables that are used when the final | PCRE contains an internal set of tables that are used when the final |
1551 | argument of pcre_compile() is NULL. These are sufficient for many | argument of pcre_compile() is NULL. These are sufficient for many |
1552 | applications. Normally, the internal tables recognize only ASCII char- | applications. Normally, the internal tables recognize only ASCII char- |
1553 | acters. However, when PCRE is built, it is possible to cause the inter- | acters. However, when PCRE is built, it is possible to cause the inter- |
1554 | nal tables to be rebuilt in the default "C" locale of the local system, | nal tables to be rebuilt in the default "C" locale of the local system, |
1555 | which may cause them to be different. | which may cause them to be different. |
1556 | ||
1557 | The internal tables can always be overridden by tables supplied by the | The internal tables can always be overridden by tables supplied by the |
1558 | application that calls PCRE. These may be created in a different locale | application that calls PCRE. These may be created in a different locale |
1559 | from the default. As more and more applications change to using Uni- | from the default. As more and more applications change to using Uni- |
1560 | code, the need for this locale support is expected to die away. | code, the need for this locale support is expected to die away. |
1561 | ||
1562 | External tables are built by calling the pcre_maketables() function, | External tables are built by calling the pcre_maketables() function, |
1563 | which has no arguments, in the relevant locale. The result can then be | which has no arguments, in the relevant locale. The result can then be |
1564 | passed to pcre_compile() or pcre_exec() as often as necessary. For | passed to pcre_compile() or pcre_exec() as often as necessary. For |
1565 | example, to build and use tables that are appropriate for the French | example, to build and use tables that are appropriate for the French |
1566 | locale (where accented characters with values greater than 128 are | locale (where accented characters with values greater than 128 are |
1567 | treated as letters), the following code could be used: | treated as letters), the following code could be used: |
1568 | ||
1569 | setlocale(LC_CTYPE, "fr_FR"); | setlocale(LC_CTYPE, "fr_FR"); |
1570 | tables = pcre_maketables(); | tables = pcre_maketables(); |
1571 | re = pcre_compile(..., tables); | re = pcre_compile(..., tables); |
1572 | ||
1573 | The locale name "fr_FR" is used on Linux and other Unix-like systems; | The locale name "fr_FR" is used on Linux and other Unix-like systems; |
1574 | if you are using Windows, the name for the French locale is "french". | if you are using Windows, the name for the French locale is "french". |
1575 | ||
1576 | When pcre_maketables() runs, the tables are built in memory that is | When pcre_maketables() runs, the tables are built in memory that is |
1577 | obtained via pcre_malloc. It is the caller's responsibility to ensure | obtained via pcre_malloc. It is the caller's responsibility to ensure |
1578 | that the memory containing the tables remains available for as long as | that the memory containing the tables remains available for as long as |
1579 | it is needed. | it is needed. |
1580 | ||
1581 | The pointer that is passed to pcre_compile() is saved with the compiled | The pointer that is passed to pcre_compile() is saved with the compiled |
1582 | 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() |
1583 | and normally also by pcre_exec(). Thus, by default, for any single pat- | and normally also by pcre_exec(). Thus, by default, for any single pat- |
1584 | tern, compilation, studying and matching all happen in the same locale, | tern, compilation, studying and matching all happen in the same locale, |
1585 | but different patterns can be compiled in different locales. | but different patterns can be compiled in different locales. |
1586 | ||
1587 | It is possible to pass a table pointer or NULL (indicating the use of | It is possible to pass a table pointer or NULL (indicating the use of |
1588 | the internal tables) to pcre_exec(). Although not intended for this | the internal tables) to pcre_exec(). Although not intended for this |
1589 | purpose, this facility could be used to match a pattern in a different | purpose, this facility could be used to match a pattern in a different |
1590 | locale from the one in which it was compiled. Passing table pointers at | locale from the one in which it was compiled. Passing table pointers at |
1591 | run time is discussed below in the section on matching a pattern. | run time is discussed below in the section on matching a pattern. |
1592 | ||
# | Line 1584 INFORMATION ABOUT A PATTERN | Line 1596 INFORMATION ABOUT A PATTERN |
1596 | int pcre_fullinfo(const pcre *code, const pcre_extra *extra, | int pcre_fullinfo(const pcre *code, const pcre_extra *extra, |
1597 | int what, void *where); | int what, void *where); |
1598 | ||
1599 | The pcre_fullinfo() function returns information about a compiled pat- | The pcre_fullinfo() function returns information about a compiled pat- |
1600 | tern. It replaces the obsolete pcre_info() function, which is neverthe- | tern. It replaces the obsolete pcre_info() function, which is neverthe- |
1601 | less retained for backwards compability (and is documented below). | less retained for backwards compability (and is documented below). |
1602 | ||
1603 | The first argument for pcre_fullinfo() is a pointer to the compiled | The first argument for pcre_fullinfo() is a pointer to the compiled |
1604 | pattern. The second argument is the result of pcre_study(), or NULL if | pattern. The second argument is the result of pcre_study(), or NULL if |
1605 | the pattern was not studied. The third argument specifies which piece | the pattern was not studied. The third argument specifies which piece |
1606 | of information is required, and the fourth argument is a pointer to a | of information is required, and the fourth argument is a pointer to a |
1607 | variable to receive the data. The yield of the function is zero for | variable to receive the data. The yield of the function is zero for |
1608 | success, or one of the following negative numbers: | success, or one of the following negative numbers: |
1609 | ||
1610 | PCRE_ERROR_NULL the argument code was NULL | PCRE_ERROR_NULL the argument code was NULL |
# | Line 1600 INFORMATION ABOUT A PATTERN | Line 1612 INFORMATION ABOUT A PATTERN |
1612 | PCRE_ERROR_BADMAGIC the "magic number" was not found | PCRE_ERROR_BADMAGIC the "magic number" was not found |
1613 | PCRE_ERROR_BADOPTION the value of what was invalid | PCRE_ERROR_BADOPTION the value of what was invalid |
1614 | ||
1615 | The "magic number" is placed at the start of each compiled pattern as | The "magic number" is placed at the start of each compiled pattern as |
1616 | an simple check against passing an arbitrary memory pointer. Here is a | an simple check against passing an arbitrary memory pointer. Here is a |
1617 | typical call of pcre_fullinfo(), to obtain the length of the compiled | typical call of pcre_fullinfo(), to obtain the length of the compiled |
1618 | pattern: | pattern: |
1619 | ||
1620 | int rc; | int rc; |
# | Line 1613 INFORMATION ABOUT A PATTERN | Line 1625 INFORMATION ABOUT A PATTERN |
1625 | PCRE_INFO_SIZE, /* what is required */ | PCRE_INFO_SIZE, /* what is required */ |
1626 | &length); /* where to put the data */ | &length); /* where to put the data */ |
1627 | ||
1628 | 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 |
1629 | are as follows: | are as follows: |
1630 | ||
1631 | PCRE_INFO_BACKREFMAX | PCRE_INFO_BACKREFMAX |
1632 | ||
1633 | Return the number of the highest back reference in the pattern. The | Return the number of the highest back reference in the pattern. The |
1634 | fourth argument should point to an int variable. Zero is returned if | fourth argument should point to an int variable. Zero is returned if |
1635 | there are no back references. | there are no back references. |
1636 | ||
1637 | PCRE_INFO_CAPTURECOUNT | PCRE_INFO_CAPTURECOUNT |
1638 | ||
1639 | Return the number of capturing subpatterns in the pattern. The fourth | Return the number of capturing subpatterns in the pattern. The fourth |
1640 | argument should point to an int variable. | argument should point to an int variable. |
1641 | ||
1642 | PCRE_INFO_DEFAULT_TABLES | PCRE_INFO_DEFAULT_TABLES |
1643 | ||
1644 | Return a pointer to the internal default character tables within PCRE. | Return a pointer to the internal default character tables within PCRE. |
1645 | The fourth argument should point to an unsigned char * variable. This | The fourth argument should point to an unsigned char * variable. This |
1646 | information call is provided for internal use by the pcre_study() func- | information call is provided for internal use by the pcre_study() func- |
1647 | tion. External callers can cause PCRE to use its internal tables by | tion. External callers can cause PCRE to use its internal tables by |
1648 | passing a NULL table pointer. | passing a NULL table pointer. |
1649 | ||
1650 | PCRE_INFO_FIRSTBYTE | PCRE_INFO_FIRSTBYTE |
1651 | ||
1652 | Return information about the first byte of any matched string, for a | Return information about the first byte of any matched string, for a |
1653 | non-anchored pattern. The fourth argument should point to an int vari- | non-anchored pattern. The fourth argument should point to an int vari- |
1654 | able. (This option used to be called PCRE_INFO_FIRSTCHAR; the old name | able. (This option used to be called PCRE_INFO_FIRSTCHAR; the old name |
1655 | is still recognized for backwards compatibility.) | is still recognized for backwards compatibility.) |
1656 | ||
1657 | If there is a fixed first byte, for example, from a pattern such as | If there is a fixed first byte, for example, from a pattern such as |
1658 | (cat|cow|coyote), its value is returned. Otherwise, if either | (cat|cow|coyote), its value is returned. Otherwise, if either |
1659 | ||
1660 | (a) the pattern was compiled with the PCRE_MULTILINE option, and every | (a) the pattern was compiled with the PCRE_MULTILINE option, and every |
1661 | branch starts with "^", or | branch starts with "^", or |
1662 | ||
1663 | (b) every branch of the pattern starts with ".*" and PCRE_DOTALL is not | (b) every branch of the pattern starts with ".*" and PCRE_DOTALL is not |
1664 | set (if it were set, the pattern would be anchored), | set (if it were set, the pattern would be anchored), |
1665 | ||
1666 | -1 is returned, indicating that the pattern matches only at the start | -1 is returned, indicating that the pattern matches only at the start |
1667 | of a subject string or after any newline within the string. Otherwise | of a subject string or after any newline within the string. Otherwise |
1668 | -2 is returned. For anchored patterns, -2 is returned. | -2 is returned. For anchored patterns, -2 is returned. |
1669 | ||
1670 | PCRE_INFO_FIRSTTABLE | PCRE_INFO_FIRSTTABLE |
1671 | ||
1672 | If the pattern was studied, and this resulted in the construction of a | If the pattern was studied, and this resulted in the construction of a |
1673 | 256-bit table indicating a fixed set of bytes for the first byte in any | 256-bit table indicating a fixed set of bytes for the first byte in any |
1674 | matching string, a pointer to the table is returned. Otherwise NULL is | matching string, a pointer to the table is returned. Otherwise NULL is |
1675 | returned. The fourth argument should point to an unsigned char * vari- | returned. The fourth argument should point to an unsigned char * vari- |
1676 | able. | able. |
1677 | ||
1678 | PCRE_INFO_HASCRORLF | PCRE_INFO_HASCRORLF |
1679 | ||
1680 | Return 1 if the pattern contains any explicit matches for CR or LF | Return 1 if the pattern contains any explicit matches for CR or LF |
1681 | characters, otherwise 0. The fourth argument should point to an int | characters, otherwise 0. The fourth argument should point to an int |
1682 | variable. An explicit match is either a literal CR or LF character, or | variable. An explicit match is either a literal CR or LF character, or |
1683 | \r or \n. | \r or \n. |
1684 | ||
1685 | PCRE_INFO_JCHANGED | PCRE_INFO_JCHANGED |
1686 | ||
1687 | Return 1 if the (?J) or (?-J) option setting is used in the pattern, | Return 1 if the (?J) or (?-J) option setting is used in the pattern, |
1688 | otherwise 0. The fourth argument should point to an int variable. (?J) | otherwise 0. The fourth argument should point to an int variable. (?J) |
1689 | and (?-J) set and unset the local PCRE_DUPNAMES option, respectively. | and (?-J) set and unset the local PCRE_DUPNAMES option, respectively. |
1690 | ||
1691 | PCRE_INFO_LASTLITERAL | PCRE_INFO_LASTLITERAL |
1692 | ||
1693 | Return the value of the rightmost literal byte that must exist in any | Return the value of the rightmost literal byte that must exist in any |
1694 | matched string, other than at its start, if such a byte has been | matched string, other than at its start, if such a byte has been |
1695 | recorded. The fourth argument should point to an int variable. If there | recorded. The fourth argument should point to an int variable. If there |
1696 | is no such byte, -1 is returned. For anchored patterns, a last literal | is no such byte, -1 is returned. For anchored patterns, a last literal |
1697 | byte is recorded only if it follows something of variable length. For | byte is recorded only if it follows something of variable length. For |
1698 | example, for the pattern /^a\d+z\d+/ the returned value is "z", but for | example, for the pattern /^a\d+z\d+/ the returned value is "z", but for |
1699 | /^a\dz\d/ the returned value is -1. | /^a\dz\d/ the returned value is -1. |
1700 | ||
1701 | PCRE_INFO_MINLENGTH | |
1702 | ||
1703 | If the pattern was studied and a minimum length for matching subject | |
1704 | strings was computed, its value is returned. Otherwise the returned | |
1705 | value is -1. The value is a number of characters, not bytes (this may | |
1706 | be relevant in UTF-8 mode). The fourth argument should point to an int | |
1707 | variable. A non-negative value is a lower bound to the length of any | |
1708 | matching string. There may not be any strings of that length that do | |
1709 | actually match, but every string that does match is at least that long. | |
1710 | ||
1711 | PCRE_INFO_NAMECOUNT | PCRE_INFO_NAMECOUNT |
1712 | PCRE_INFO_NAMEENTRYSIZE | PCRE_INFO_NAMEENTRYSIZE |
1713 | PCRE_INFO_NAMETABLE | PCRE_INFO_NAMETABLE |
1714 | ||
1715 | PCRE supports the use of named as well as numbered capturing parenthe- | PCRE supports the use of named as well as numbered capturing parenthe- |
1716 | ses. The names are just an additional way of identifying the parenthe- | ses. The names are just an additional way of identifying the parenthe- |
1717 | ses, which still acquire numbers. Several convenience functions such as | ses, which still acquire numbers. Several convenience functions such as |
1718 | pcre_get_named_substring() are provided for extracting captured sub- | pcre_get_named_substring() are provided for extracting captured sub- |
1719 | strings by name. It is also possible to extract the data directly, by | strings by name. It is also possible to extract the data directly, by |
1720 | first converting the name to a number in order to access the correct | first converting the name to a number in order to access the correct |
1721 | pointers in the output vector (described with pcre_exec() below). To do | pointers in the output vector (described with pcre_exec() below). To do |
1722 | the conversion, you need to use the name-to-number map, which is | the conversion, you need to use the name-to-number map, which is |
1723 | described by these three values. | described by these three values. |
1724 | ||
1725 | The map consists of a number of fixed-size entries. PCRE_INFO_NAMECOUNT | The map consists of a number of fixed-size entries. PCRE_INFO_NAMECOUNT |
1726 | gives the number of entries, and PCRE_INFO_NAMEENTRYSIZE gives the size | gives the number of entries, and PCRE_INFO_NAMEENTRYSIZE gives the size |
1727 | of each entry; both of these return an int value. The entry size | of each entry; both of these return an int value. The entry size |
1728 | depends on the length of the longest name. PCRE_INFO_NAMETABLE returns | depends on the length of the longest name. PCRE_INFO_NAMETABLE returns |
1729 | a pointer to the first entry of the table (a pointer to char). The | a pointer to the first entry of the table (a pointer to char). The |
1730 | first two bytes of each entry are the number of the capturing parenthe- | first two bytes of each entry are the number of the capturing parenthe- |
1731 | sis, most significant byte first. The rest of the entry is the corre- | sis, most significant byte first. The rest of the entry is the corre- |
1732 | sponding name, zero terminated. The names are in alphabetical order. | sponding name, zero terminated. |
1733 | When PCRE_DUPNAMES is set, duplicate names are in order of their paren- | |
1734 | theses numbers. For example, consider the following pattern (assume | The names are in alphabetical order. Duplicate names may appear if (?| |
1735 | PCRE_EXTENDED is set, so white space - including newlines - is | is used to create multiple groups with the same number, as described in |
1736 | ignored): | the section on duplicate subpattern numbers in the pcrepattern page. |
1737 | Duplicate names for subpatterns with different numbers are permitted | |
1738 | only if PCRE_DUPNAMES is set. In all cases of duplicate names, they | |
1739 | appear in the table in the order in which they were found in the pat- | |
1740 | tern. In the absence of (?| this is the order of increasing number; | |
1741 | when (?| is used this is not necessarily the case because later subpat- | |
1742 | terns may have lower numbers. | |
1743 | ||
1744 | As a simple example of the name/number table, consider the following | |
1745 | pattern (assume PCRE_EXTENDED is set, so white space - including new- | |
1746 | lines - is ignored): | |
1747 | ||
1748 | (?<date> (?<year>(\d\d)?\d\d) - | (?<date> (?<year>(\d\d)?\d\d) - |
1749 | (?<month>\d\d) - (?<day>\d\d) ) | (?<month>\d\d) - (?<day>\d\d) ) |
1750 | ||
1751 | There are four named subpatterns, so the table has four entries, and | There are four named subpatterns, so the table has four entries, and |
1752 | each entry in the table is eight bytes long. The table is as follows, | each entry in the table is eight bytes long. The table is as follows, |
1753 | with non-printing bytes shows in hexadecimal, and undefined bytes shown | with non-printing bytes shows in hexadecimal, and undefined bytes shown |
1754 | as ??: | as ??: |
1755 | ||
# | Line 1726 INFORMATION ABOUT A PATTERN | Line 1758 INFORMATION ABOUT A PATTERN |
1758 | 00 04 m o n t h 00 | 00 04 m o n t h 00 |
1759 | 00 02 y e a r 00 ?? | 00 02 y e a r 00 ?? |
1760 | ||
1761 | When writing code to extract data from named subpatterns using the | When writing code to extract data from named subpatterns using the |
1762 | name-to-number map, remember that the length of the entries is likely | name-to-number map, remember that the length of the entries is likely |
1763 | to be different for each compiled pattern. | to be different for each compiled pattern. |
1764 | ||
1765 | PCRE_INFO_OKPARTIAL | PCRE_INFO_OKPARTIAL |
1766 | ||
1767 | Return 1 if the pattern can be used for partial matching with | Return 1 if the pattern can be used for partial matching with |
1768 | pcre_exec(), otherwise 0. The fourth argument should point to an int | pcre_exec(), otherwise 0. The fourth argument should point to an int |
1769 | variable. From release 8.00, this always returns 1, because the | variable. From release 8.00, this always returns 1, because the |
1770 | restrictions that previously applied to partial matching have been | restrictions that previously applied to partial matching have been |
1771 | lifted. The pcrepartial documentation gives details of partial match- | lifted. The pcrepartial documentation gives details of partial match- |
1772 | ing. | ing. |
1773 | ||
1774 | PCRE_INFO_OPTIONS | PCRE_INFO_OPTIONS |
1775 | ||
1776 | Return a copy of the options with which the pattern was compiled. The | Return a copy of the options with which the pattern was compiled. The |
1777 | fourth argument should point to an unsigned long int variable. These | fourth argument should point to an unsigned long int variable. These |
1778 | option bits are those specified in the call to pcre_compile(), modified | option bits are those specified in the call to pcre_compile(), modified |
1779 | by any top-level option settings at the start of the pattern itself. In | by any top-level option settings at the start of the pattern itself. In |
1780 | other words, they are the options that will be in force when matching | other words, they are the options that will be in force when matching |
1781 | starts. For example, if the pattern /(?im)abc(?-i)d/ is compiled with | starts. For example, if the pattern /(?im)abc(?-i)d/ is compiled with |
1782 | the PCRE_EXTENDED option, the result is PCRE_CASELESS, PCRE_MULTILINE, | the PCRE_EXTENDED option, the result is PCRE_CASELESS, PCRE_MULTILINE, |
1783 | and PCRE_EXTENDED. | and PCRE_EXTENDED. |
1784 | ||
1785 | A pattern is automatically anchored by PCRE if all of its top-level | A pattern is automatically anchored by PCRE if all of its top-level |
1786 | alternatives begin with one of the following: | alternatives begin with one of the following: |
1787 | ||
1788 | ^ unless PCRE_MULTILINE is set | ^ unless PCRE_MULTILINE is set |
# | Line 1764 INFORMATION ABOUT A PATTERN | Line 1796 INFORMATION ABOUT A PATTERN |
1796 | ||
1797 | PCRE_INFO_SIZE | PCRE_INFO_SIZE |
1798 | ||
1799 | Return the size of the compiled pattern, that is, the value that was | Return the size of the compiled pattern, that is, the value that was |
1800 | passed as the argument to pcre_malloc() when PCRE was getting memory in | passed as the argument to pcre_malloc() when PCRE was getting memory in |
1801 | which to place the compiled data. The fourth argument should point to a | which to place the compiled data. The fourth argument should point to a |
1802 | size_t variable. | size_t variable. |
# | Line 1772 INFORMATION ABOUT A PATTERN | Line 1804 INFORMATION ABOUT A PATTERN |
1804 | PCRE_INFO_STUDYSIZE | PCRE_INFO_STUDYSIZE |
1805 | ||
1806 | Return the size of the data block pointed to by the study_data field in | Return the size of the data block pointed to by the study_data field in |
1807 | a pcre_extra block. That is, it is the value that was passed to | a pcre_extra block. That is, it is the value that was passed to |
1808 | pcre_malloc() when PCRE was getting memory into which to place the data | pcre_malloc() when PCRE was getting memory into which to place the data |
1809 | created by pcre_study(). The fourth argument should point to a size_t | created by pcre_study(). If pcre_extra is NULL, or there is no study |
1810 | data, zero is returned. The fourth argument should point to a size_t | |
1811 | variable. | variable. |
1812 | ||
1813 | ||
# | Line 1830 MATCHING A PATTERN: THE TRADITIONAL FUNC | Line 1863 MATCHING A PATTERN: THE TRADITIONAL FUNC |
1863 | ||
1864 | The function pcre_exec() is called to match a subject string against a | The function pcre_exec() is called to match a subject string against a |
1865 | compiled pattern, which is passed in the code argument. If the pattern | compiled pattern, which is passed in the code argument. If the pattern |
1866 | has been studied, the result of the study should be passed in the extra | was studied, the result of the study should be passed in the extra |
1867 | argument. This function is the main matching facility of the library, | argument. This function is the main matching facility of the library, |
1868 | and it operates in a Perl-like manner. For specialist use there is also | and it operates in a Perl-like manner. For specialist use there is also |
1869 | an alternative matching function, which is described below in the sec- | an alternative matching function, which is described below in the sec- |
# | Line 1889 MATCHING A PATTERN: THE TRADITIONAL FUNC | Line 1922 MATCHING A PATTERN: THE TRADITIONAL FUNC |
1922 | The match_limit field provides a means of preventing PCRE from using up | The match_limit field provides a means of preventing PCRE from using up |
1923 | a vast amount of resources when running patterns that are not going to | a vast amount of resources when running patterns that are not going to |
1924 | match, but which have a very large number of possibilities in their | match, but which have a very large number of possibilities in their |
1925 | search trees. The classic example is the use of nested unlimited | search trees. The classic example is a pattern that uses nested unlim- |
1926 | repeats. | ited repeats. |
1927 | ||
1928 | Internally, PCRE uses a function called match() which it calls repeat- | Internally, PCRE uses a function called match() which it calls repeat- |
1929 | edly (sometimes recursively). The limit set by match_limit is imposed | edly (sometimes recursively). The limit set by match_limit is imposed |
# | Line 2177 MATCHING A PATTERN: THE TRADITIONAL FUNC | Line 2210 MATCHING A PATTERN: THE TRADITIONAL FUNC |
2210 | has to get additional memory for use during matching. Thus it is usu- | has to get additional memory for use during matching. Thus it is usu- |
2211 | ally advisable to supply an ovector. | ally advisable to supply an ovector. |
2212 | ||
2213 | The pcre_info() function can be used to find out how many capturing | The pcre_fullinfo() function can be used to find out how many capturing |
2214 | subpatterns there are in a compiled pattern. The smallest size for | subpatterns there are in a compiled pattern. The smallest size for |
2215 | ovector that will allow for n captured substrings, in addition to the | ovector that will allow for n captured substrings, in addition to the |
2216 | offsets of the substring matched by the whole pattern, is (n+1)*3. | offsets of the substring matched by the whole pattern, is (n+1)*3. |
# | Line 2438 EXTRACTING CAPTURED SUBSTRINGS BY NAME | Line 2471 EXTRACTING CAPTURED SUBSTRINGS BY NAME |
2471 | ate. NOTE: If PCRE_DUPNAMES is set and there are duplicate names, the | ate. NOTE: If PCRE_DUPNAMES is set and there are duplicate names, the |
2472 | behaviour may not be what you want (see the next section). | behaviour may not be what you want (see the next section). |
2473 | ||
2474 | Warning: If the pattern uses the "(?|" feature to set up multiple sub- | Warning: If the pattern uses the (?| feature to set up multiple subpat- |
2475 | patterns with the same number, you cannot use names to distinguish | terns with the same number, as described in the section on duplicate |
2476 | them, because names are not included in the compiled code. The matching | subpattern numbers in the pcrepattern page, you cannot use names to |
2477 | process uses only numbers. | distinguish the different subpatterns, because names are not included |
2478 | in the compiled code. The matching process uses only numbers. For this | |
2479 | reason, the use of different names for subpatterns of the same number | |
2480 | causes an error at compile time. | |
2481 | ||
2482 | ||
2483 | DUPLICATE SUBPATTERN NAMES | DUPLICATE SUBPATTERN NAMES |
# | Line 2449 DUPLICATE SUBPATTERN NAMES | Line 2485 DUPLICATE SUBPATTERN NAMES |
2485 | int pcre_get_stringtable_entries(const pcre *code, | int pcre_get_stringtable_entries(const pcre *code, |
2486 | const char *name, char **first, char **last); | const char *name, char **first, char **last); |
2487 | ||
2488 | When a pattern is compiled with the PCRE_DUPNAMES option, names for | When a pattern is compiled with the PCRE_DUPNAMES option, names for |
2489 | subpatterns are not required to be unique. Normally, patterns with | subpatterns are not required to be unique. (Duplicate names are always |
2490 | duplicate names are such that in any one match, only one of the named | allowed for subpatterns with the same number, created by using the (?| |
2491 | subpatterns participates. An example is shown in the pcrepattern docu- | feature. Indeed, if such subpatterns are named, they are required to |
2492 | mentation. | use the same names.) |
2493 | ||
2494 | Normally, patterns with duplicate names are such that in any one match, | |
2495 | only one of the named subpatterns participates. An example is shown in | |
2496 | the pcrepattern documentation. | |
2497 | ||
2498 | When duplicates are present, pcre_copy_named_substring() and | When duplicates are present, pcre_copy_named_substring() and |
2499 | pcre_get_named_substring() return the first substring corresponding to | pcre_get_named_substring() return the first substring corresponding to |
2500 | the given name that is set. If none are set, PCRE_ERROR_NOSUBSTRING | the given name that is set. If none are set, PCRE_ERROR_NOSUBSTRING |
2501 | (-7) is returned; no data is returned. The pcre_get_stringnumber() | (-7) is returned; no data is returned. The pcre_get_stringnumber() |
2502 | function returns one of the numbers that are associated with the name, | function returns one of the numbers that are associated with the name, |
2503 | but it is not defined which it is. | but it is not defined which it is. |
2504 | ||
2505 | If you want to get full details of all captured substrings for a given | If you want to get full details of all captured substrings for a given |
2506 | name, you must use the pcre_get_stringtable_entries() function. The | name, you must use the pcre_get_stringtable_entries() function. The |
2507 | first argument is the compiled pattern, and the second is the name. The | first argument is the compiled pattern, and the second is the name. The |
2508 | third and fourth are pointers to variables which are updated by the | third and fourth are pointers to variables which are updated by the |
2509 | function. After it has run, they point to the first and last entries in | function. After it has run, they point to the first and last entries in |
2510 | the name-to-number table for the given name. The function itself | the name-to-number table for the given name. The function itself |
2511 | returns the length of each entry, or PCRE_ERROR_NOSUBSTRING (-7) if | returns the length of each entry, or PCRE_ERROR_NOSUBSTRING (-7) if |
2512 | there are none. The format of the table is described above in the sec- | there are none. The format of the table is described above in the sec- |
2513 | tion entitled Information about a pattern. Given all the relevant | tion entitled Information about a pattern. Given all the relevant |
2514 | entries for the name, you can extract each of their numbers, and hence | entries for the name, you can extract each of their numbers, and hence |
2515 | the captured data, if any. | the captured data, if any. |
2516 | ||
2517 | ||
2518 | FINDING ALL POSSIBLE MATCHES | FINDING ALL POSSIBLE MATCHES |
2519 | ||
2520 | The traditional matching function uses a similar algorithm to Perl, | The traditional matching function uses a similar algorithm to Perl, |
2521 | which stops when it finds the first match, starting at a given point in | which stops when it finds the first match, starting at a given point in |
2522 | the subject. If you want to find all possible matches, or the longest | the subject. If you want to find all possible matches, or the longest |
2523 | possible match, consider using the alternative matching function (see | possible match, consider using the alternative matching function (see |
2524 | below) instead. If you cannot use the alternative function, but still | below) instead. If you cannot use the alternative function, but still |
2525 | need to find all possible matches, you can kludge it up by making use | need to find all possible matches, you can kludge it up by making use |
2526 | of the callout facility, which is described in the pcrecallout documen- | of the callout facility, which is described in the pcrecallout documen- |
2527 | tation. | tation. |
2528 | ||
2529 | What you have to do is to insert a callout right at the end of the pat- | What you have to do is to insert a callout right at the end of the pat- |
2530 | tern. When your callout function is called, extract and save the cur- | tern. When your callout function is called, extract and save the cur- |
2531 | rent matched substring. Then return 1, which forces pcre_exec() to | rent matched substring. Then return 1, which forces pcre_exec() to |
2532 | backtrack and try other alternatives. Ultimately, when it runs out of | backtrack and try other alternatives. Ultimately, when it runs out of |
2533 | matches, pcre_exec() will yield PCRE_ERROR_NOMATCH. | matches, pcre_exec() will yield PCRE_ERROR_NOMATCH. |
2534 | ||
2535 | ||
# | Line 2500 MATCHING A PATTERN: THE ALTERNATIVE FUNC | Line 2540 MATCHING A PATTERN: THE ALTERNATIVE FUNC |
2540 | int options, int *ovector, int ovecsize, | int options, int *ovector, int ovecsize, |
2541 | int *workspace, int wscount); | int *workspace, int wscount); |
2542 | ||
2543 | The function pcre_dfa_exec() is called to match a subject string | The function pcre_dfa_exec() is called to match a subject string |
2544 | against a compiled pattern, using a matching algorithm that scans the | against a compiled pattern, using a matching algorithm that scans the |
2545 | subject string just once, and does not backtrack. This has different | subject string just once, and does not backtrack. This has different |
2546 | characteristics to the normal algorithm, and is not compatible with | characteristics to the normal algorithm, and is not compatible with |
2547 | Perl. Some of the features of PCRE patterns are not supported. Never- | Perl. Some of the features of PCRE patterns are not supported. Never- |
2548 | theless, there are times when this kind of matching can be useful. For | theless, there are times when this kind of matching can be useful. For |
2549 | a discussion of the two matching algorithms, and a list of features | a discussion of the two matching algorithms, and a list of features |
2550 | that pcre_dfa_exec() does not support, see the pcrematching documenta- | that pcre_dfa_exec() does not support, see the pcrematching documenta- |
2551 | tion. | tion. |
2552 | ||
2553 | 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 |
2554 | pcre_exec(), plus two extras. The ovector argument is used in a differ- | pcre_exec(), plus two extras. The ovector argument is used in a differ- |
2555 | ent way, and this is described below. The other common arguments are | ent way, and this is described below. The other common arguments are |
2556 | used in the same way as for pcre_exec(), so their description is not | used in the same way as for pcre_exec(), so their description is not |
2557 | repeated here. | repeated here. |
2558 | ||
2559 | The two additional arguments provide workspace for the function. The | The two additional arguments provide workspace for the function. The |
2560 | workspace vector should contain at least 20 elements. It is used for | workspace vector should contain at least 20 elements. It is used for |
2561 | keeping track of multiple paths through the pattern tree. More | keeping track of multiple paths through the pattern tree. More |
2562 | workspace will be needed for patterns and subjects where there are a | workspace will be needed for patterns and subjects where there are a |
2563 | lot of potential matches. | lot of potential matches. |
2564 | ||
2565 | Here is an example of a simple call to pcre_dfa_exec(): | Here is an example of a simple call to pcre_dfa_exec(): |
# | Line 2541 MATCHING A PATTERN: THE ALTERNATIVE FUNC | Line 2581 MATCHING A PATTERN: THE ALTERNATIVE FUNC |
2581 | ||
2582 | Option bits for pcre_dfa_exec() | Option bits for pcre_dfa_exec() |
2583 | ||
2584 | The unused bits of the options argument for pcre_dfa_exec() must be | The unused bits of the options argument for pcre_dfa_exec() must be |
2585 | zero. The only bits that may be set are PCRE_ANCHORED, PCRE_NEW- | zero. The only bits that may be set are PCRE_ANCHORED, PCRE_NEW- |
2586 | LINE_xxx, PCRE_NOTBOL, PCRE_NOTEOL, PCRE_NOTEMPTY, | LINE_xxx, PCRE_NOTBOL, PCRE_NOTEOL, PCRE_NOTEMPTY, |
2587 | PCRE_NOTEMPTY_ATSTART, PCRE_NO_UTF8_CHECK, PCRE_PARTIAL_HARD, PCRE_PAR- | PCRE_NOTEMPTY_ATSTART, PCRE_NO_UTF8_CHECK, PCRE_PARTIAL_HARD, PCRE_PAR- |
2588 | TIAL_SOFT, PCRE_DFA_SHORTEST, and PCRE_DFA_RESTART. All but the last | TIAL_SOFT, PCRE_DFA_SHORTEST, and PCRE_DFA_RESTART. All but the last |
2589 | four of these are exactly the same as for pcre_exec(), so their | four of these are exactly the same as for pcre_exec(), so their |
2590 | description is not repeated here. | description is not repeated here. |
2591 | ||
2592 | PCRE_PARTIAL_HARD | PCRE_PARTIAL_HARD |
2593 | PCRE_PARTIAL_SOFT | PCRE_PARTIAL_SOFT |
2594 | ||
2595 | These have the same general effect as they do for pcre_exec(), but the | These have the same general effect as they do for pcre_exec(), but the |
2596 | details are slightly different. When PCRE_PARTIAL_HARD is set for | details are slightly different. When PCRE_PARTIAL_HARD is set for |
2597 | pcre_dfa_exec(), it returns PCRE_ERROR_PARTIAL if the end of the sub- | pcre_dfa_exec(), it returns PCRE_ERROR_PARTIAL if the end of the sub- |
2598 | ject is reached and there is still at least one matching possibility | ject is reached and there is still at least one matching possibility |
2599 | that requires additional characters. This happens even if some complete | that requires additional characters. This happens even if some complete |
2600 | matches have also been found. When PCRE_PARTIAL_SOFT is set, the return | matches have also been found. When PCRE_PARTIAL_SOFT is set, the return |
2601 | code PCRE_ERROR_NOMATCH is converted into PCRE_ERROR_PARTIAL if the end | code PCRE_ERROR_NOMATCH is converted into PCRE_ERROR_PARTIAL if the end |
2602 | of the subject is reached, there have been no complete matches, but | of the subject is reached, there have been no complete matches, but |
2603 | there is still at least one matching possibility. The portion of the | there is still at least one matching possibility. The portion of the |
2604 | string that was inspected when the longest partial match was found is | string that was inspected when the longest partial match was found is |
2605 | set as the first matching string in both cases. | set as the first matching string in both cases. |
2606 | ||
2607 | PCRE_DFA_SHORTEST | PCRE_DFA_SHORTEST |
2608 | ||
2609 | Setting the PCRE_DFA_SHORTEST option causes the matching algorithm to | Setting the PCRE_DFA_SHORTEST option causes the matching algorithm to |
2610 | stop as soon as it has found one match. Because of the way the alterna- | stop as soon as it has found one match. Because of the way the alterna- |
2611 | tive algorithm works, this is necessarily the shortest possible match | tive algorithm works, this is necessarily the shortest possible match |
2612 | at the first possible matching point in the subject string. | at the first possible matching point in the subject string. |
2613 | ||
2614 | PCRE_DFA_RESTART | PCRE_DFA_RESTART |
2615 | ||
2616 | When pcre_dfa_exec() returns a partial match, it is possible to call it | When pcre_dfa_exec() returns a partial match, it is possible to call it |
2617 | again, with additional subject characters, and have it continue with | again, with additional subject characters, and have it continue with |
2618 | the same match. The PCRE_DFA_RESTART option requests this action; when | the same match. The PCRE_DFA_RESTART option requests this action; when |
2619 | it is set, the workspace and wscount options must reference the same | it is set, the workspace and wscount options must reference the same |
2620 | vector as before because data about the match so far is left in them | vector as before because data about the match so far is left in them |
2621 | after a partial match. There is more discussion of this facility in the | after a partial match. There is more discussion of this facility in the |
2622 | pcrepartial documentation. | pcrepartial documentation. |
2623 | ||
2624 | Successful returns from pcre_dfa_exec() | Successful returns from pcre_dfa_exec() |
2625 | ||
2626 | 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- |
2627 | string in the subject. Note, however, that all the matches from one run | string in the subject. Note, however, that all the matches from one run |
2628 | of the function start at the same point in the subject. The shorter | of the function start at the same point in the subject. The shorter |
2629 | matches are all initial substrings of the longer matches. For example, | matches are all initial substrings of the longer matches. For example, |
2630 | if the pattern | if the pattern |
2631 | ||
2632 | <.*> | <.*> |
# | Line 2601 MATCHING A PATTERN: THE ALTERNATIVE FUNC | Line 2641 MATCHING A PATTERN: THE ALTERNATIVE FUNC |
2641 | <something> <something else> | <something> <something else> |
2642 | <something> <something else> <something further> | <something> <something else> <something further> |
2643 | ||
2644 | On success, the yield of the function is a number greater than zero, | On success, the yield of the function is a number greater than zero, |
2645 | which is the number of matched substrings. The substrings themselves | which is the number of matched substrings. The substrings themselves |
2646 | are returned in ovector. Each string uses two elements; the first is | are returned in ovector. Each string uses two elements; the first is |
2647 | the offset to the start, and the second is the offset to the end. In | the offset to the start, and the second is the offset to the end. In |
2648 | fact, all the strings have the same start offset. (Space could have | fact, all the strings have the same start offset. (Space could have |
2649 | been saved by giving this only once, but it was decided to retain some | been saved by giving this only once, but it was decided to retain some |
2650 | compatibility with the way pcre_exec() returns data, even though the | compatibility with the way pcre_exec() returns data, even though the |
2651 | meaning of the strings is different.) | meaning of the strings is different.) |
2652 | ||
2653 | The strings are returned in reverse order of length; that is, the long- | The strings are returned in reverse order of length; that is, the long- |
2654 | est matching string is given first. If there were too many matches to | est matching string is given first. If there were too many matches to |
2655 | fit into ovector, the yield of the function is zero, and the vector is | fit into ovector, the yield of the function is zero, and the vector is |
2656 | filled with the longest matches. | filled with the longest matches. |
2657 | ||
2658 | Error returns from pcre_dfa_exec() | Error returns from pcre_dfa_exec() |
2659 | ||
2660 | The pcre_dfa_exec() function returns a negative number when it fails. | The pcre_dfa_exec() function returns a negative number when it fails. |
2661 | Many of the errors are the same as for pcre_exec(), and these are | Many of the errors are the same as for pcre_exec(), and these are |
2662 | described above. There are in addition the following errors that are | described above. There are in addition the following errors that are |
2663 | specific to pcre_dfa_exec(): | specific to pcre_dfa_exec(): |
2664 | ||
2665 | PCRE_ERROR_DFA_UITEM (-16) | PCRE_ERROR_DFA_UITEM (-16) |
2666 | ||
2667 | This return is given if pcre_dfa_exec() encounters an item in the pat- | This return is given if pcre_dfa_exec() encounters an item in the pat- |
2668 | tern that it does not support, for instance, the use of \C or a back | tern that it does not support, for instance, the use of \C or a back |
2669 | reference. | reference. |
2670 | ||
2671 | PCRE_ERROR_DFA_UCOND (-17) | PCRE_ERROR_DFA_UCOND (-17) |
2672 | ||
2673 | This return is given if pcre_dfa_exec() encounters a condition item | This return is given if pcre_dfa_exec() encounters a condition item |
2674 | that uses a back reference for the condition, or a test for recursion | that uses a back reference for the condition, or a test for recursion |
2675 | in a specific group. These are not supported. | in a specific group. These are not supported. |
2676 | ||
2677 | PCRE_ERROR_DFA_UMLIMIT (-18) | PCRE_ERROR_DFA_UMLIMIT (-18) |
2678 | ||
2679 | 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 |
2680 | that contains a setting of the match_limit field. This is not supported | that contains a setting of the match_limit field. This is not supported |
2681 | (it is meaningless). | (it is meaningless). |
2682 | ||
2683 | PCRE_ERROR_DFA_WSSIZE (-19) | PCRE_ERROR_DFA_WSSIZE (-19) |
2684 | ||
2685 | 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 |
2686 | workspace vector. | workspace vector. |
2687 | ||
2688 | PCRE_ERROR_DFA_RECURSE (-20) | PCRE_ERROR_DFA_RECURSE (-20) |
2689 | ||
2690 | When a recursive subpattern is processed, the matching function calls | When a recursive subpattern is processed, the matching function calls |
2691 | itself recursively, using private vectors for ovector and workspace. | itself recursively, using private vectors for ovector and workspace. |
2692 | This error is given if the output vector is not large enough. This | This error is given if the output vector is not large enough. This |
2693 | should be extremely rare, as a vector of size 1000 is used. | should be extremely rare, as a vector of size 1000 is used. |
2694 | ||
2695 | ||
2696 | SEE ALSO | SEE ALSO |
2697 | ||
2698 | pcrebuild(3), pcrecallout(3), pcrecpp(3)(3), pcrematching(3), pcrepar- | pcrebuild(3), pcrecallout(3), pcrecpp(3)(3), pcrematching(3), pcrepar- |
2699 | tial(3), pcreposix(3), pcreprecompile(3), pcresample(3), pcrestack(3). | tial(3), pcreposix(3), pcreprecompile(3), pcresample(3), pcrestack(3). |
2700 | ||
2701 | ||
# | Line 2668 AUTHOR | Line 2708 AUTHOR |
2708 | ||
2709 | REVISION | REVISION |
2710 | ||
2711 | Last updated: 22 September 2009 | Last updated: 03 October 2009 |
2712 | Copyright (c) 1997-2009 University of Cambridge. | Copyright (c) 1997-2009 University of Cambridge. |
2713 | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ |
2714 | ||
2715 | ||
2716 | PCRECALLOUT(3) PCRECALLOUT(3) | PCRECALLOUT(3) PCRECALLOUT(3) |
2717 | ||
2718 | ||
# | Line 2698 PCRE CALLOUTS | Line 2738 PCRE CALLOUTS |
2738 | ||
2739 | (?C1)abc(?C2)def | (?C1)abc(?C2)def |
2740 | ||
2741 | If the PCRE_AUTO_CALLOUT option bit is set when pcre_compile() is | If the PCRE_AUTO_CALLOUT option bit is set when pcre_compile() or |
2742 | called, PCRE automatically inserts callouts, all with number 255, | pcre_compile2() is called, PCRE automatically inserts callouts, all |
2743 | before each item in the pattern. For example, if PCRE_AUTO_CALLOUT is | with number 255, before each item in the pattern. For example, if |
2744 | used with the pattern | PCRE_AUTO_CALLOUT is used with the pattern |
2745 | ||
2746 | A(\d{2}|--) | A(\d{2}|--) |
2747 | ||
# | Line 2730 MISSING CALLOUTS | Line 2770 MISSING CALLOUTS |
2770 | ever start, and the callout is never reached. However, with "abyd", | ever start, and the callout is never reached. However, with "abyd", |
2771 | though the result is still no match, the callout is obeyed. | though the result is still no match, the callout is obeyed. |
2772 | ||
2773 | You can disable these optimizations by passing the PCRE_NO_START_OPTI- | If the pattern is studied, PCRE knows the minimum length of a matching |
2774 | MIZE option to pcre_exec() or pcre_dfa_exec(). This slows down the | string, and will immediately give a "no match" return without actually |
2775 | matching process, but does ensure that callouts such as the example | running a match if the subject is not long enough, or, for unanchored |
2776 | patterns, if it has been scanned far enough. | |
2777 | ||
2778 | You can disable these optimizations by passing the PCRE_NO_START_OPTI- | |
2779 | MIZE option to pcre_exec() or pcre_dfa_exec(). This slows down the | |
2780 | matching process, but does ensure that callouts such as the example | |
2781 | above are obeyed. | above are obeyed. |
2782 | ||
2783 | ||
2784 | THE CALLOUT INTERFACE | THE CALLOUT INTERFACE |
2785 | ||
2786 | During matching, when PCRE reaches a callout point, the external func- | During matching, when PCRE reaches a callout point, the external func- |
2787 | tion defined by pcre_callout is called (if it is set). This applies to | tion defined by pcre_callout is called (if it is set). This applies to |
2788 | both the pcre_exec() and the pcre_dfa_exec() matching functions. The | both the pcre_exec() and the pcre_dfa_exec() matching functions. The |
2789 | only argument to the callout function is a pointer to a pcre_callout | only argument to the callout function is a pointer to a pcre_callout |
2790 | block. This structure contains the following fields: | block. This structure contains the following fields: |
2791 | ||
2792 | int version; | int version; |
# | Line 2757 THE CALLOUT INTERFACE | Line 2802 THE CALLOUT INTERFACE |
2802 | int pattern_position; | int pattern_position; |
2803 | int next_item_length; | int next_item_length; |
2804 | ||
2805 | The version field is an integer containing the version number of the | The version field is an integer containing the version number of the |
2806 | block format. The initial version was 0; the current version is 1. The | block format. The initial version was 0; the current version is 1. The |
2807 | version number will change again in future if additional fields are | version number will change again in future if additional fields are |
2808 | added, but the intention is never to remove any of the existing fields. | added, but the intention is never to remove any of the existing fields. |
2809 | ||
2810 | The callout_number field contains the number of the callout, as com- | The callout_number field contains the number of the callout, as com- |
2811 | piled into the pattern (that is, the number after ?C for manual call- | piled into the pattern (that is, the number after ?C for manual call- |
2812 | outs, and 255 for automatically generated callouts). | outs, and 255 for automatically generated callouts). |
2813 | ||
2814 | The offset_vector field is a pointer to the vector of offsets that was | The offset_vector field is a pointer to the vector of offsets that was |
2815 | passed by the caller to pcre_exec() or pcre_dfa_exec(). When | passed by the caller to pcre_exec() or pcre_dfa_exec(). When |
2816 | pcre_exec() is used, the contents can be inspected in order to extract | pcre_exec() is used, the contents can be inspected in order to extract |
2817 | substrings that have been matched so far, in the same way as for | substrings that have been matched so far, in the same way as for |
2818 | extracting substrings after a match has completed. For pcre_dfa_exec() | extracting substrings after a match has completed. For pcre_dfa_exec() |
2819 | this field is not useful. | this field is not useful. |
2820 | ||
2821 | The subject and subject_length fields contain copies of the values that | The subject and subject_length fields contain copies of the values that |
2822 | were passed to pcre_exec(). | were passed to pcre_exec(). |
2823 | ||
2824 | The start_match field normally contains the offset within the subject | The start_match field normally contains the offset within the subject |
2825 | at which the current match attempt started. However, if the escape | at which the current match attempt started. However, if the escape |
2826 | sequence \K has been encountered, this value is changed to reflect the | sequence \K has been encountered, this value is changed to reflect the |
2827 | modified starting point. If the pattern is not anchored, the callout | modified starting point. If the pattern is not anchored, the callout |
2828 | function may be called several times from the same point in the pattern | function may be called several times from the same point in the pattern |
2829 | for different starting points in the subject. | for different starting points in the subject. |
2830 | ||
2831 | The current_position field contains the offset within the subject of | The current_position field contains the offset within the subject of |
2832 | the current match pointer. | the current match pointer. |
2833 | ||
2834 | When the pcre_exec() function is used, the capture_top field contains | When the pcre_exec() function is used, the capture_top field contains |
2835 | one more than the number of the highest numbered captured substring so | one more than the number of the highest numbered captured substring so |
2836 | far. If no substrings have been captured, the value of capture_top is | far. If no substrings have been captured, the value of capture_top is |
2837 | one. This is always the case when pcre_dfa_exec() is used, because it | one. This is always the case when pcre_dfa_exec() is used, because it |
2838 | does not support captured substrings. | does not support captured substrings. |
2839 | ||
2840 | The capture_last field contains the number of the most recently cap- | The capture_last field contains the number of the most recently cap- |
2841 | tured substring. If no substrings have been captured, its value is -1. | tured substring. If no substrings have been captured, its value is -1. |
2842 | This is always the case when pcre_dfa_exec() is used. | This is always the case when pcre_dfa_exec() is used. |
2843 | ||
2844 | The callout_data field contains a value that is passed to pcre_exec() | The callout_data field contains a value that is passed to pcre_exec() |
2845 | or pcre_dfa_exec() specifically so that it can be passed back in call- | or pcre_dfa_exec() specifically so that it can be passed back in call- |
2846 | outs. It is passed in the pcre_callout field of the pcre_extra data | outs. It is passed in the pcre_callout field of the pcre_extra data |
2847 | structure. If no such data was passed, the value of callout_data in a | structure. If no such data was passed, the value of callout_data in a |
2848 | pcre_callout block is NULL. There is a description of the pcre_extra | pcre_callout block is NULL. There is a description of the pcre_extra |
2849 | structure in the pcreapi documentation. | structure in the pcreapi documentation. |
2850 | ||
2851 | The pattern_position field is present from version 1 of the pcre_call- | The pattern_position field is present from version 1 of the pcre_call- |
2852 | out structure. It contains the offset to the next item to be matched in | out structure. It contains the offset to the next item to be matched in |
2853 | the pattern string. | the pattern string. |
2854 | ||
2855 | The next_item_length field is present from version 1 of the pcre_call- | The next_item_length field is present from version 1 of the pcre_call- |
2856 | out structure. It contains the length of the next item to be matched in | out structure. It contains the length of the next item to be matched in |
2857 | the pattern string. When the callout immediately precedes an alterna- | the pattern string. When the callout immediately precedes an alterna- |
2858 | tion bar, a closing parenthesis, or the end of the pattern, the length | tion bar, a closing parenthesis, or the end of the pattern, the length |
2859 | is zero. When the callout precedes an opening parenthesis, the length | is zero. When the callout precedes an opening parenthesis, the length |
2860 | is that of the entire subpattern. | is that of the entire subpattern. |
2861 | ||
2862 | The pattern_position and next_item_length fields are intended to help | The pattern_position and next_item_length fields are intended to help |
2863 | in distinguishing between different automatic callouts, which all have | in distinguishing between different automatic callouts, which all have |
2864 | the same callout number. However, they are set for all callouts. | the same callout number. However, they are set for all callouts. |
2865 | ||
2866 | ||
2867 | RETURN VALUES | RETURN VALUES |
2868 | ||
2869 | The external callout function returns an integer to PCRE. If the value | The external callout function returns an integer to PCRE. If the value |
2870 | is zero, matching proceeds as normal. If the value is greater than | is zero, matching proceeds as normal. If the value is greater than |
2871 | zero, matching fails at the current point, but the testing of other | zero, matching fails at the current point, but the testing of other |
2872 | matching possibilities goes ahead, just as if a lookahead assertion had | matching possibilities goes ahead, just as if a lookahead assertion had |
2873 | failed. If the value is less than zero, the match is abandoned, and | failed. If the value is less than zero, the match is abandoned, and |
2874 | pcre_exec() (or pcre_dfa_exec()) returns the negative value. | pcre_exec() or pcre_dfa_exec() returns the negative value. |
2875 | ||
2876 | Negative values should normally be chosen from the set of | Negative values should normally be chosen from the set of |
2877 | PCRE_ERROR_xxx values. In particular, PCRE_ERROR_NOMATCH forces a stan- | PCRE_ERROR_xxx values. In particular, PCRE_ERROR_NOMATCH forces a stan- |
2878 | dard "no match" failure. The error number PCRE_ERROR_CALLOUT is | dard "no match" failure. The error number PCRE_ERROR_CALLOUT is |
2879 | reserved for use by callout functions; it will never be used by PCRE | reserved for use by callout functions; it will never be used by PCRE |
2880 | itself. | itself. |
2881 | ||
2882 | ||
# | Line 2844 AUTHOR | Line 2889 AUTHOR |
2889 | ||
2890 | REVISION | REVISION |
2891 | ||
2892 | Last updated: 15 March 2009 | Last updated: 29 September 2009 |
2893 | Copyright (c) 1997-2009 University of Cambridge. | Copyright (c) 1997-2009 University of Cambridge. |
2894 | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ |
2895 | ||
2896 | ||
2897 | PCRECOMPAT(3) PCRECOMPAT(3) | PCRECOMPAT(3) PCRECOMPAT(3) |
2898 | ||
2899 | ||
# | Line 2859 NAME | Line 2904 NAME |
2904 | DIFFERENCES BETWEEN PCRE AND PERL | DIFFERENCES BETWEEN PCRE AND PERL |
2905 | ||
2906 | This document describes the differences in the ways that PCRE and Perl | This document describes the differences in the ways that PCRE and Perl |
2907 | handle regular expressions. The differences described here are mainly | handle regular expressions. The differences described here are with |
2908 | with respect to Perl 5.8, though PCRE versions 7.0 and later contain | respect to Perl 5.10. |
some features that are in Perl 5.10. | ||
2909 | ||
2910 | 1. PCRE has only a subset of Perl's UTF-8 and Unicode support. Details | 1. PCRE has only a subset of Perl's UTF-8 and Unicode support. Details |
2911 | of what it does have are given in the section on UTF-8 support in the | of what it does have are given in the section on UTF-8 support in the |
2912 | main pcre page. | main pcre page. |
2913 | ||
2914 | 2. PCRE does not allow repeat quantifiers on lookahead assertions. Perl | 2. PCRE does not allow repeat quantifiers on lookahead assertions. Perl |
2915 | permits them, but they do not mean what you might think. For example, | permits them, but they do not mean what you might think. For example, |
2916 | (?!a){3} does not assert that the next three characters are not "a". It | (?!a){3} does not assert that the next three characters are not "a". It |
2917 | just asserts that the next character is not "a" three times. | just asserts that the next character is not "a" three times. |
2918 | ||
2919 | 3. Capturing subpatterns that occur inside negative lookahead asser- | 3. Capturing subpatterns that occur inside negative lookahead asser- |
2920 | tions are counted, but their entries in the offsets vector are never | tions are counted, but their entries in the offsets vector are never |
2921 | set. Perl sets its numerical variables from any such patterns that are | set. Perl sets its numerical variables from any such patterns that are |
2922 | matched before the assertion fails to match something (thereby succeed- | matched before the assertion fails to match something (thereby succeed- |
2923 | ing), but only if the negative lookahead assertion contains just one | ing), but only if the negative lookahead assertion contains just one |
2924 | branch. | branch. |
2925 | ||
2926 | 4. Though binary zero characters are supported in the subject string, | 4. Though binary zero characters are supported in the subject string, |
2927 | they are not allowed in a pattern string because it is passed as a nor- | they are not allowed in a pattern string because it is passed as a nor- |
2928 | mal C string, terminated by zero. The escape sequence \0 can be used in | mal C string, terminated by zero. The escape sequence \0 can be used in |
2929 | the pattern to represent a binary zero. | the pattern to represent a binary zero. |
2930 | ||
2931 | 5. The following Perl escape sequences are not supported: \l, \u, \L, | 5. The following Perl escape sequences are not supported: \l, \u, \L, |
2932 | \U, and \N. In fact these are implemented by Perl's general string-han- | \U, and \N. In fact these are implemented by Perl's general string-han- |
2933 | dling and are not part of its pattern matching engine. If any of these | dling and are not part of its pattern matching engine. If any of these |
2934 | are encountered by PCRE, an error is generated. | are encountered by PCRE, an error is generated. |
2935 | ||
2936 | 6. The Perl escape sequences \p, \P, and \X are supported only if PCRE | 6. The Perl escape sequences \p, \P, and \X are supported only if PCRE |
2937 | is built with Unicode character property support. The properties that | is built with Unicode character property support. The properties that |
2938 | can be tested with \p and \P are limited to the general category prop- | can be tested with \p and \P are limited to the general category prop- |
2939 | erties such as Lu and Nd, script names such as Greek or Han, and the | erties such as Lu and Nd, script names such as Greek or Han, and the |
2940 | derived properties Any and L&. PCRE does support the Cs (surrogate) | derived properties Any and L&. PCRE does support the Cs (surrogate) |
2941 | property, which Perl does not; the Perl documentation says "Because | property, which Perl does not; the Perl documentation says "Because |
2942 | Perl hides the need for the user to understand the internal representa- | Perl hides the need for the user to understand the internal representa- |
2943 | tion of Unicode characters, there is no need to implement the somewhat | tion of Unicode characters, there is no need to implement the somewhat |
2944 | messy concept of surrogates." | messy concept of surrogates." |
2945 | ||
2946 | 7. PCRE does support the \Q...\E escape for quoting substrings. Charac- | 7. PCRE does support the \Q...\E escape for quoting substrings. Charac- |
2947 | ters in between are treated as literals. This is slightly different | ters in between are treated as literals. This is slightly different |
2948 | from Perl in that $ and @ are also handled as literals inside the | from Perl in that $ and @ are also handled as literals inside the |
2949 | quotes. In Perl, they cause variable interpolation (but of course PCRE | quotes. In Perl, they cause variable interpolation (but of course PCRE |
2950 | does not have variables). Note the following examples: | does not have variables). Note the following examples: |
2951 | ||
2952 | Pattern PCRE matches Perl matches | Pattern PCRE matches Perl matches |
# | Line 2912 DIFFERENCES BETWEEN PCRE AND PERL | Line 2956 DIFFERENCES BETWEEN PCRE AND PERL |
2956 | \Qabc\$xyz\E abc\$xyz abc\$xyz | \Qabc\$xyz\E abc\$xyz abc\$xyz |
2957 | \Qabc\E\$\Qxyz\E abc$xyz abc$xyz | \Qabc\E\$\Qxyz\E abc$xyz abc$xyz |
2958 | ||
2959 | The \Q...\E sequence is recognized both inside and outside character | The \Q...\E sequence is recognized both inside and outside character |
2960 | classes. | classes. |
2961 | ||
2962 | 8. Fairly obviously, PCRE does not support the (?{code}) and (??{code}) | 8. Fairly obviously, PCRE does not support the (?{code}) and (??{code}) |
2963 | constructions. However, there is support for recursive patterns. This | constructions. However, there is support for recursive patterns. This |
2964 | is not available in Perl 5.8, but it is in Perl 5.10. Also, the PCRE | is not available in Perl 5.8, but it is in Perl 5.10. Also, the PCRE |
2965 | "callout" feature allows an external function to be called during pat- | "callout" feature allows an external function to be called during pat- |
2966 | tern matching. See the pcrecallout documentation for details. | tern matching. See the pcrecallout documentation for details. |
2967 | ||
2968 | 9. Subpatterns that are called recursively or as "subroutines" are | 9. Subpatterns that are called recursively or as "subroutines" are |
2969 | always treated as atomic groups in PCRE. This is like Python, but | always treated as atomic groups in PCRE. This is like Python, but |
2970 | unlike Perl. There is a discussion of an example that explains this in | unlike Perl. There is a discussion of an example that explains this in |
2971 | more detail in the section on recursion differences from Perl in the | more detail in the section on recursion differences from Perl in the |
2972 | pcrecompat page. | pcrepattern page. |
2973 | ||
2974 | 10. There are some differences that are concerned with the settings of | 10. There are some differences that are concerned with the settings of |
2975 | captured strings when part of a pattern is repeated. For example, | captured strings when part of a pattern is repeated. For example, |
2976 | matching "aba" against the pattern /^(a(b)?)+$/ in Perl leaves $2 | matching "aba" against the pattern /^(a(b)?)+$/ in Perl leaves $2 |
2977 | unset, but in PCRE it is set to "b". | unset, but in PCRE it is set to "b". |
2978 | ||
2979 | 11. PCRE does support Perl 5.10's backtracking verbs (*ACCEPT), | 11. PCRE does support Perl 5.10's backtracking verbs (*ACCEPT), |
2980 | (*FAIL), (*F), (*COMMIT), (*PRUNE), (*SKIP), and (*THEN), but only in | (*FAIL), (*F), (*COMMIT), (*PRUNE), (*SKIP), and (*THEN), but only in |
2981 | the forms without an argument. PCRE does not support (*MARK). | the forms without an argument. PCRE does not support (*MARK). |
2982 | ||
2983 | 12. PCRE provides some extensions to the Perl regular expression facil- | 12. PCRE's handling of duplicate subpattern numbers and duplicate sub- |
2984 | ities. Perl 5.10 will include new features that are not in earlier | pattern names is not as general as Perl's. This is a consequence of the |
2985 | versions, some of which (such as named parentheses) have been in PCRE | fact the PCRE works internally just with numbers, using an external ta- |
2986 | for some time. This list is with respect to Perl 5.10: | ble to translate between numbers and names. In particular, a pattern |
2987 | such as (?|(?<a>A)|(?<b)B), where the two capturing parentheses have | |
2988 | (a) Although lookbehind assertions must match fixed length strings, | the same number but different names, is not supported, and causes an |
2989 | each alternative branch of a lookbehind assertion can match a different | error at compile time. If it were allowed, it would not be possible to |
2990 | length of string. Perl requires them all to have the same length. | distinguish which parentheses matched, because both names map to cap- |
2991 | turing subpattern number 1. To avoid this confusing situation, an error | |
2992 | is given at compile time. | |
2993 | ||
2994 | 13. PCRE provides some extensions to the Perl regular expression facil- | |
2995 | ities. Perl 5.10 includes new features that are not in earlier ver- | |
2996 | sions of Perl, some of which (such as named parentheses) have been in | |
2997 | PCRE for some time. This list is with respect to Perl 5.10: | |
2998 | ||
2999 | (a) Although lookbehind assertions in PCRE must match fixed length | |
3000 | strings, each alternative branch of a lookbehind assertion can match a | |
3001 | different length of string. Perl requires them all to have the same | |
3002 | length. | |
3003 | ||
3004 | (b) If PCRE_DOLLAR_ENDONLY is set and PCRE_MULTILINE is not set, the $ | (b) If PCRE_DOLLAR_ENDONLY is set and PCRE_MULTILINE is not set, the $ |
3005 | meta-character matches only at the very end of the string. | meta-character matches only at the very end of the string. |
3006 | ||
3007 | (c) If PCRE_EXTRA is set, a backslash followed by a letter with no spe- | (c) If PCRE_EXTRA is set, a backslash followed by a letter with no spe- |
3008 | cial meaning is faulted. Otherwise, like Perl, the backslash is quietly | cial meaning is faulted. Otherwise, like Perl, the backslash is quietly |
3009 | ignored. (Perl can be made to issue a warning.) | ignored. (Perl can be made to issue a warning.) |
3010 | ||
3011 | (d) If PCRE_UNGREEDY is set, the greediness of the repetition quanti- | (d) If PCRE_UNGREEDY is set, the greediness of the repetition quanti- |
3012 | fiers is inverted, that is, by default they are not greedy, but if fol- | fiers is inverted, that is, by default they are not greedy, but if fol- |
3013 | lowed by a question mark they are. | lowed by a question mark they are. |
3014 | ||
# | Line 2960 DIFFERENCES BETWEEN PCRE AND PERL | Line 3016 DIFFERENCES BETWEEN PCRE AND PERL |
3016 | tried only at the first matching position in the subject string. | tried only at the first matching position in the subject string. |
3017 | ||
3018 | (f) The PCRE_NOTBOL, PCRE_NOTEOL, PCRE_NOTEMPTY, PCRE_NOTEMPTY_ATSTART, | (f) The PCRE_NOTBOL, PCRE_NOTEOL, PCRE_NOTEMPTY, PCRE_NOTEMPTY_ATSTART, |
3019 | and PCRE_NO_AUTO_CAPTURE options for pcre_exec() have no Perl equiva- | and PCRE_NO_AUTO_CAPTURE options for pcre_exec() have no Perl equiva- |
3020 | lents. | lents. |
3021 | ||
3022 | (g) The \R escape sequence can be restricted to match only CR, LF, or | (g) The \R escape sequence can be restricted to match only CR, LF, or |
3023 | CRLF by the PCRE_BSR_ANYCRLF option. | CRLF by the PCRE_BSR_ANYCRLF option. |
3024 | ||
3025 | (h) The callout facility is PCRE-specific. | (h) The callout facility is PCRE-specific. |
# | Line 2973 DIFFERENCES BETWEEN PCRE AND PERL | Line 3029 DIFFERENCES BETWEEN PCRE AND PERL |
3029 | (j) Patterns compiled by PCRE can be saved and re-used at a later time, | (j) Patterns compiled by PCRE can be saved and re-used at a later time, |
3030 | even on different hosts that have the other endianness. | even on different hosts that have the other endianness. |
3031 | ||
3032 | (k) The alternative matching function (pcre_dfa_exec()) matches in a | (k) The alternative matching function (pcre_dfa_exec()) matches in a |
3033 | different way and is not Perl-compatible. | different way and is not Perl-compatible. |
3034 | ||
3035 | (l) PCRE recognizes some special sequences such as (*CR) at the start | (l) PCRE recognizes some special sequences such as (*CR) at the start |
3036 | of a pattern that set overall options that cannot be changed within the | of a pattern that set overall options that cannot be changed within the |
3037 | pattern. | pattern. |
3038 | ||
# | Line 2990 AUTHOR | Line 3046 AUTHOR |
3046 | ||
3047 | REVISION | REVISION |
3048 | ||
3049 | Last updated: 18 September 2009 | Last updated: 04 October 2009 |
3050 | Copyright (c) 1997-2009 University of Cambridge. | Copyright (c) 1997-2009 University of Cambridge. |
3051 | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ |
3052 | ||
3053 | ||
3054 | PCREPATTERN(3) PCREPATTERN(3) | PCREPATTERN(3) PCREPATTERN(3) |
3055 | ||
3056 | ||
# | Line 3021 PCRE REGULAR EXPRESSION DETAILS | Line 3077 PCRE REGULAR EXPRESSION DETAILS |
3077 | ||
3078 | The original operation of PCRE was on strings of one-byte characters. | The original operation of PCRE was on strings of one-byte characters. |
3079 | However, there is now also support for UTF-8 character strings. To use | However, there is now also support for UTF-8 character strings. To use |
3080 | this, you must build PCRE to include UTF-8 support, and then call | this, PCRE must be built to include UTF-8 support, and you must call |
3081 | pcre_compile() with the PCRE_UTF8 option. There is also a special | pcre_compile() or pcre_compile2() with the PCRE_UTF8 option. There is |
3082 | sequence that can be given at the start of a pattern: | also a special sequence that can be given at the start of a pattern: |
3083 | ||
3084 | (*UTF8) | (*UTF8) |
3085 | ||
# | Line 3061 NEWLINE CONVENTIONS | Line 3117 NEWLINE CONVENTIONS |
3117 | (*ANYCRLF) any of the three above | (*ANYCRLF) any of the three above |
3118 | (*ANY) all Unicode newline sequences | (*ANY) all Unicode newline sequences |
3119 | ||
3120 | These override the default and the options given to pcre_compile(). For | These override the default and the options given to pcre_compile() or |
3121 | example, on a Unix system where LF is the default newline sequence, the | pcre_compile2(). For example, on a Unix system where LF is the default |
3122 | pattern | newline sequence, the pattern |
3123 | ||
3124 | (*CR)a.b | (*CR)a.b |
3125 | ||
# | Line 3180 BACKSLASH | Line 3236 BACKSLASH |
3236 | acters in patterns in a visible manner. There is no restriction on the | acters in patterns in a visible manner. There is no restriction on the |
3237 | appearance of non-printing characters, apart from the binary zero that | appearance of non-printing characters, apart from the binary zero that |
3238 | terminates a pattern, but when a pattern is being prepared by text | terminates a pattern, but when a pattern is being prepared by text |
3239 | editing, it is usually easier to use one of the following escape | editing, it is often easier to use one of the following escape |
3240 | sequences than the binary character it represents: | sequences than the binary character it represents: |
3241 | ||
3242 | \a alarm, that is, the BEL character (hex 07) | \a alarm, that is, the BEL character (hex 07) |
# | Line 3392 BACKSLASH | Line 3448 BACKSLASH |
3448 | (*BSR_ANYCRLF) CR, LF, or CRLF only | (*BSR_ANYCRLF) CR, LF, or CRLF only |
3449 | (*BSR_UNICODE) any Unicode newline sequence | (*BSR_UNICODE) any Unicode newline sequence |
3450 | ||
3451 | These override the default and the options given to pcre_compile(), but | These override the default and the options given to pcre_compile() or |
3452 | they can be overridden by options given to pcre_exec(). Note that these | pcre_compile2(), but they can be overridden by options given to |
3453 | special settings, which are not Perl-compatible, are recognized only at | pcre_exec() or pcre_dfa_exec(). Note that these special settings, which |
3454 | the very start of a pattern, and that they must be in upper case. If | are not Perl-compatible, are recognized only at the very start of a |
3455 | more than one of them is present, the last one is used. They can be | pattern, and that they must be in upper case. If more than one of them |
3456 | combined with a change of newline convention, for example, a pattern | is present, the last one is used. They can be combined with a change of |
3457 | can start with: | newline convention, for example, a pattern can start with: |
3458 | ||
3459 | (*ANY)(*BSR_ANYCRLF) | (*ANY)(*BSR_ANYCRLF) |
3460 | ||
# | Line 3581 BACKSLASH | Line 3637 BACKSLASH |
3637 | A word boundary is a position in the subject string where the current | A word boundary is a position in the subject string where the current |
3638 | character and the previous character do not both match \w or \W (i.e. | character and the previous character do not both match \w or \W (i.e. |
3639 | one matches \w and the other matches \W), or the start or end of the | one matches \w and the other matches \W), or the start or end of the |
3640 | string if the first or last character matches \w, respectively. | string if the first or last character matches \w, respectively. Neither |
3641 | PCRE nor Perl has a separte "start of word" or "end of word" metase- | |
3642 | quence. However, whatever follows \b normally determines which it is. | |
3643 | For example, the fragment \ba matches "a" at the start of a word. | |
3644 | ||
3645 | The \A, \Z, and \z assertions differ from the traditional circumflex | The \A, \Z, and \z assertions differ from the traditional circumflex |
3646 | and dollar (described in the next section) in that they only ever match | and dollar (described in the next section) in that they only ever match |
3647 | at the very start and end of the subject string, whatever options are | at the very start and end of the subject string, whatever options are |
3648 | set. Thus, they are independent of multiline mode. These three asser- | set. Thus, they are independent of multiline mode. These three asser- |
3649 | tions are not affected by the PCRE_NOTBOL or PCRE_NOTEOL options, which | tions are not affected by the PCRE_NOTBOL or PCRE_NOTEOL options, which |
3650 | affect only the behaviour of the circumflex and dollar metacharacters. | affect only the behaviour of the circumflex and dollar metacharacters. |
3651 | However, if the startoffset argument of pcre_exec() is non-zero, indi- | However, if the startoffset argument of pcre_exec() is non-zero, indi- |
3652 | cating that matching is to start at a point other than the beginning of | cating that matching is to start at a point other than the beginning of |
3653 | the subject, \A can never match. The difference between \Z and \z is | the subject, \A can never match. The difference between \Z and \z is |
3654 | that \Z matches before a newline at the end of the string as well as at | that \Z matches before a newline at the end of the string as well as at |
3655 | the very end, whereas \z matches only at the end. | the very end, whereas \z matches only at the end. |
3656 | ||
3657 | The \G assertion is true only when the current matching position is at | The \G assertion is true only when the current matching position is at |
3658 | the start point of the match, as specified by the startoffset argument | the start point of the match, as specified by the startoffset argument |
3659 | of pcre_exec(). It differs from \A when the value of startoffset is | of pcre_exec(). It differs from \A when the value of startoffset is |
3660 | non-zero. By calling pcre_exec() multiple times with appropriate argu- | non-zero. By calling pcre_exec() multiple times with appropriate argu- |
3661 | ments, you can mimic Perl's /g option, and it is in this kind of imple- | ments, you can mimic Perl's /g option, and it is in this kind of imple- |
3662 | mentation where \G can be useful. | mentation where \G can be useful. |
3663 | ||
3664 | 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 |
3665 | current match, is subtly different from Perl's, which defines it as the | current match, is subtly different from Perl's, which defines it as the |
3666 | end of the previous match. In Perl, these can be different when the | end of the previous match. In Perl, these can be different when the |
3667 | previously matched string was empty. Because PCRE does just one match | previously matched string was empty. Because PCRE does just one match |
3668 | at a time, it cannot reproduce this behaviour. | at a time, it cannot reproduce this behaviour. |
3669 | ||
3670 | 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 |
3671 | anchored to the starting match position, and the "anchored" flag is set | anchored to the starting match position, and the "anchored" flag is set |
3672 | in the compiled regular expression. | in the compiled regular expression. |
3673 | ||
# | Line 3616 BACKSLASH | Line 3675 BACKSLASH |
3675 | CIRCUMFLEX AND DOLLAR | CIRCUMFLEX AND DOLLAR |
3676 | ||
3677 | Outside a character class, in the default matching mode, the circumflex | Outside a character class, in the default matching mode, the circumflex |
3678 | character is an assertion that is true only if the current matching | character is an assertion that is true only if the current matching |
3679 | point is at the start of the subject string. If the startoffset argu- | point is at the start of the subject string. If the startoffset argu- |
3680 | ment of pcre_exec() is non-zero, circumflex can never match if the | ment of pcre_exec() is non-zero, circumflex can never match if the |
3681 | PCRE_MULTILINE option is unset. Inside a character class, circumflex | PCRE_MULTILINE option is unset. Inside a character class, circumflex |
3682 | has an entirely different meaning (see below). | has an entirely different meaning (see below). |
3683 | ||
3684 | Circumflex need not be the first character of the pattern if a number | Circumflex need not be the first character of the pattern if a number |
3685 | of alternatives are involved, but it should be the first thing in each | of alternatives are involved, but it should be the first thing in each |
3686 | alternative in which it appears if the pattern is ever to match that | alternative in which it appears if the pattern is ever to match that |
3687 | branch. If all possible alternatives start with a circumflex, that is, | branch. If all possible alternatives start with a circumflex, that is, |
3688 | if the pattern is constrained to match only at the start of the sub- | if the pattern is constrained to match only at the start of the sub- |
3689 | ject, it is said to be an "anchored" pattern. (There are also other | ject, it is said to be an "anchored" pattern. (There are also other |
3690 | constructs that can cause a pattern to be anchored.) | constructs that can cause a pattern to be anchored.) |
3691 | ||
3692 | A dollar character is an assertion that is true only if the current | A dollar character is an assertion that is true only if the current |
3693 | matching point is at the end of the subject string, or immediately | matching point is at the end of the subject string, or immediately |
3694 | before a newline at the end of the string (by default). Dollar need not | before a newline at the end of the string (by default). Dollar need not |
3695 | be the last character of the pattern if a number of alternatives are | be the last character of the pattern if a number of alternatives are |
3696 | involved, but it should be the last item in any branch in which it | involved, but it should be the last item in any branch in which it |
3697 | appears. Dollar has no special meaning in a character class. | appears. Dollar has no special meaning in a character class. |
3698 | ||
3699 | The meaning of dollar can be changed so that it matches only at the | The meaning of dollar can be changed so that it matches only at the |
3700 | very end of the string, by setting the PCRE_DOLLAR_ENDONLY option at | very end of the string, by setting the PCRE_DOLLAR_ENDONLY option at |
3701 | compile time. This does not affect the \Z assertion. | compile time. This does not affect the \Z assertion. |
3702 | ||
3703 | The meanings of the circumflex and dollar characters are changed if the | The meanings of the circumflex and dollar characters are changed if the |
3704 | PCRE_MULTILINE option is set. When this is the case, a circumflex | PCRE_MULTILINE option is set. When this is the case, a circumflex |
3705 | matches immediately after internal newlines as well as at the start of | matches immediately after internal newlines as well as at the start of |
3706 | the subject string. It does not match after a newline that ends the | the subject string. It does not match after a newline that ends the |
3707 | string. A dollar matches before any newlines in the string, as well as | string. A dollar matches before any newlines in the string, as well as |
3708 | at the very end, when PCRE_MULTILINE is set. When newline is specified | at the very end, when PCRE_MULTILINE is set. When newline is specified |
3709 | as the two-character sequence CRLF, isolated CR and LF characters do | as the two-character sequence CRLF, isolated CR and LF characters do |
3710 | not indicate newlines. | not indicate newlines. |
3711 | ||
3712 | For example, the pattern /^abc$/ matches the subject string "def\nabc" | For example, the pattern /^abc$/ matches the subject string "def\nabc" |
3713 | (where \n represents a newline) in multiline mode, but not otherwise. | (where \n represents a newline) in multiline mode, but not otherwise. |
3714 | Consequently, patterns that are anchored in single line mode because | Consequently, patterns that are anchored in single line mode because |
3715 | all branches start with ^ are not anchored in multiline mode, and a | all branches start with ^ are not anchored in multiline mode, and a |
3716 | match for circumflex is possible when the startoffset argument of | match for circumflex is possible when the startoffset argument of |
3717 | pcre_exec() is non-zero. The PCRE_DOLLAR_ENDONLY option is ignored if | pcre_exec() is non-zero. The PCRE_DOLLAR_ENDONLY option is ignored if |
3718 | PCRE_MULTILINE is set. | PCRE_MULTILINE is set. |
3719 | ||
3720 | Note that the sequences \A, \Z, and \z can be used to match the start | Note that the sequences \A, \Z, and \z can be used to match the start |
3721 | and end of the subject in both modes, and if all branches of a pattern | and end of the subject in both modes, and if all branches of a pattern |
3722 | start with \A it is always anchored, whether or not PCRE_MULTILINE is | start with \A it is always anchored, whether or not PCRE_MULTILINE is |
3723 | set. | set. |
3724 | ||
3725 | ||
3726 | FULL STOP (PERIOD, DOT) | FULL STOP (PERIOD, DOT) |
3727 | ||
3728 | Outside a character class, a dot in the pattern matches any one charac- | Outside a character class, a dot in the pattern matches any one charac- |
3729 | ter in the subject string except (by default) a character that signi- | ter in the subject string except (by default) a character that signi- |
3730 | fies the end of a line. In UTF-8 mode, the matched character may be | fies the end of a line. In UTF-8 mode, the matched character may be |
3731 | more than one byte long. | more than one byte long. |
3732 | ||
3733 | When a line ending is defined as a single character, dot never matches | When a line ending is defined as a single character, dot never matches |
3734 | that character; when the two-character sequence CRLF is used, dot does | that character; when the two-character sequence CRLF is used, dot does |
3735 | not match CR if it is immediately followed by LF, but otherwise it | not match CR if it is immediately followed by LF, but otherwise it |
3736 | matches all characters (including isolated CRs and LFs). When any Uni- | matches all characters (including isolated CRs and LFs). When any Uni- |
3737 | code line endings are being recognized, dot does not match CR or LF or | code line endings are being recognized, dot does not match CR or LF or |
3738 | any of the other line ending characters. | any of the other line ending characters. |
3739 | ||
3740 | The behaviour of dot with regard to newlines can be changed. If the | The behaviour of dot with regard to newlines can be changed. If the |
3741 | PCRE_DOTALL option is set, a dot matches any one character, without | PCRE_DOTALL option is set, a dot matches any one character, without |
3742 | exception. If the two-character sequence CRLF is present in the subject | exception. If the two-character sequence CRLF is present in the subject |
3743 | string, it takes two dots to match it. | string, it takes two dots to match it. |
3744 | ||
3745 | The handling of dot is entirely independent of the handling of circum- | The handling of dot is entirely independent of the handling of circum- |
3746 | flex and dollar, the only relationship being that they both involve | flex and dollar, the only relationship being that they both involve |
3747 | newlines. Dot has no special meaning in a character class. | newlines. Dot has no special meaning in a character class. |
3748 | ||
3749 | ||
3750 | MATCHING A SINGLE BYTE | MATCHING A SINGLE BYTE |
3751 | ||
3752 | Outside a character class, the escape sequence \C matches any one byte, | Outside a character class, the escape sequence \C matches any one byte, |
3753 | both in and out of UTF-8 mode. Unlike a dot, it always matches any | both in and out of UTF-8 mode. Unlike a dot, it always matches any |
3754 | line-ending characters. The feature is provided in Perl in order to | line-ending characters. The feature is provided in Perl in order to |
3755 | match individual bytes in UTF-8 mode. Because it breaks up UTF-8 char- | match individual bytes in UTF-8 mode. Because it breaks up UTF-8 char- |
3756 | acters into individual bytes, what remains in the string may be a mal- | acters into individual bytes, what remains in the string may be a mal- |
3757 | formed UTF-8 string. For this reason, the \C escape sequence is best | formed UTF-8 string. For this reason, the \C escape sequence is best |
3758 | avoided. | avoided. |
3759 | ||
3760 | PCRE does not allow \C to appear in lookbehind assertions (described | PCRE does not allow \C to appear in lookbehind assertions (described |
3761 | below), because in UTF-8 mode this would make it impossible to calcu- | below), because in UTF-8 mode this would make it impossible to calcu- |
3762 | late the length of the lookbehind. | late the length of the lookbehind. |
3763 | ||
3764 | ||
# | Line 3707 SQUARE BRACKETS AND CHARACTER CLASSES | Line 3766 SQUARE BRACKETS AND CHARACTER CLASSES |
3766 | ||
3767 | An opening square bracket introduces a character class, terminated by a | An opening square bracket introduces a character class, terminated by a |
3768 | closing square bracket. A closing square bracket on its own is not spe- | closing square bracket. A closing square bracket on its own is not spe- |
3769 | cial. If a closing square bracket is required as a member of the class, | cial by default. However, if the PCRE_JAVASCRIPT_COMPAT option is set, |
3770 | it should be the first data character in the class (after an initial | a lone closing square bracket causes a compile-time error. If a closing |
3771 | circumflex, if present) or escaped with a backslash. | square bracket is required as a member of the class, it should be the |
3772 | first data character in the class (after an initial circumflex, if | |
3773 | present) or escaped with a backslash. | |
3774 | ||
3775 | A character class matches a single character in the subject. In UTF-8 | A character class matches a single character in the subject. In UTF-8 |
3776 | mode, the character may occupy more than one byte. A matched character | mode, the character may be more than one byte long. A matched character |
3777 | must be in the set of characters defined by the class, unless the first | must be in the set of characters defined by the class, unless the first |
3778 | character in the class definition is a circumflex, in which case the | character in the class definition is a circumflex, in which case the |
3779 | subject character must not be in the set defined by the class. If a | subject character must not be in the set defined by the class. If a |
3780 | circumflex is actually required as a member of the class, ensure it is | circumflex is actually required as a member of the class, ensure it is |
3781 | not the first character, or escape it with a backslash. | not the first character, or escape it with a backslash. |
3782 | ||
3783 | For example, the character class [aeiou] matches any lower case vowel, | For example, the character class [aeiou] matches any lower case vowel, |
3784 | while [^aeiou] matches any character that is not a lower case vowel. | while [^aeiou] matches any character that is not a lower case vowel. |
3785 | Note that a circumflex is just a convenient notation for specifying the | Note that a circumflex is just a convenient notation for specifying the |
3786 | characters that are in the class by enumerating those that are not. A | characters that are in the class by enumerating those that are not. A |
3787 | class that starts with a circumflex is not an assertion: it still con- | class that starts with a circumflex is not an assertion; it still con- |
3788 | sumes a character from the subject string, and therefore it fails if | sumes a character from the subject string, and therefore it fails if |
3789 | the current pointer is at the end of the string. | the current pointer is at the end of the string. |
3790 | ||
3791 | In UTF-8 mode, characters with values greater than 255 can be included | In UTF-8 mode, characters with values greater than 255 can be included |
3792 | in a class as a literal string of bytes, or by using the \x{ escaping | in a class as a literal string of bytes, or by using the \x{ escaping |
3793 | mechanism. | mechanism. |
3794 | ||
3795 | When caseless matching is set, any letters in a class represent both | When caseless matching is set, any letters in a class represent both |
3796 | their upper case and lower case versions, so for example, a caseless | their upper case and lower case versions, so for example, a caseless |
3797 | [aeiou] matches "A" as well as "a", and a caseless [^aeiou] does not | [aeiou] matches "A" as well as "a", and a caseless [^aeiou] does not |
3798 | match "A", whereas a caseful version would. In UTF-8 mode, PCRE always | match "A", whereas a caseful version would. In UTF-8 mode, PCRE always |
3799 | understands the concept of case for characters whose values are less | understands the concept of case for characters whose values are less |
3800 | than 128, so caseless matching is always possible. For characters with | than 128, so caseless matching is always possible. For characters with |
3801 | higher values, the concept of case is supported if PCRE is compiled | higher values, the concept of case is supported if PCRE is compiled |
3802 | with Unicode property support, but not otherwise. If you want to use | with Unicode property support, but not otherwise. If you want to use |
3803 | caseless matching for characters 128 and above, you must ensure that | caseless matching in UTF8-mode for characters 128 and above, you must |
3804 | PCRE is compiled with Unicode property support as well as with UTF-8 | ensure that PCRE is compiled with Unicode property support as well as |
3805 | support. | with UTF-8 support. |
3806 | ||
3807 | Characters that might indicate line breaks are never treated in any | Characters that might indicate line breaks are never treated in any |
3808 | special way when matching character classes, whatever line-ending | special way when matching character classes, whatever line-ending |
3809 | sequence is in use, and whatever setting of the PCRE_DOTALL and | sequence is in use, and whatever setting of the PCRE_DOTALL and |
3810 | PCRE_MULTILINE options is used. A class such as [^a] always matches one | PCRE_MULTILINE options is used. A class such as [^a] always matches one |
3811 | of these characters. | of these characters. |
3812 | ||
3813 | The minus (hyphen) character can be used to specify a range of charac- | The minus (hyphen) character can be used to specify a range of charac- |
3814 | ters in a character class. For example, [d-m] matches any letter | ters in a character class. For example, [d-m] matches any letter |
3815 | between d and m, inclusive. If a minus character is required in a | between d and m, inclusive. If a minus character is required in a |
3816 | class, it must be escaped with a backslash or appear in a position | class, it must be escaped with a backslash or appear in a position |
3817 | where it cannot be interpreted as indicating a range, typically as the | where it cannot be interpreted as indicating a range, typically as the |
3818 | first or last character in the class. | first or last character in the class. |
3819 | ||
3820 | It is not possible to have the literal character "]" as the end charac- | It is not possible to have the literal character "]" as the end charac- |
3821 | ter of a range. A pattern such as [W-]46] is interpreted as a class of | ter of a range. A pattern such as [W-]46] is interpreted as a class of |
3822 | two characters ("W" and "-") followed by a literal string "46]", so it | two characters ("W" and "-") followed by a literal string "46]", so it |
3823 | would match "W46]" or "-46]". However, if the "]" is escaped with a | would match "W46]" or "-46]". However, if the "]" is escaped with a |
3824 | backslash it is interpreted as the end of range, so [W-\]46] is inter- | backslash it is interpreted as the end of range, so [W-\]46] is inter- |
3825 | preted as a class containing a range followed by two other characters. | preted as a class containing a range followed by two other characters. |
3826 | The octal or hexadecimal representation of "]" can also be used to end | The octal or hexadecimal representation of "]" can also be used to end |
3827 | a range. | a range. |
3828 | ||
3829 | Ranges operate in the collating sequence of character values. They can | Ranges operate in the collating sequence of character values. They can |
3830 | also be used for characters specified numerically, for example | also be used for characters specified numerically, for example |
3831 | [\000-\037]. In UTF-8 mode, ranges can include characters whose values | [\000-\037]. In UTF-8 mode, ranges can include characters whose values |
3832 | are greater than 255, for example [\x{100}-\x{2ff}]. | are greater than 255, for example [\x{100}-\x{2ff}]. |
3833 | ||
3834 | If a range that includes letters is used when caseless matching is set, | If a range that includes letters is used when caseless matching is set, |
3835 | it matches the letters in either case. For example, [W-c] is equivalent | it matches the letters in either case. For example, [W-c] is equivalent |
3836 | to [][\\^_`wxyzabc], matched caselessly, and in non-UTF-8 mode, if | to [][\\^_`wxyzabc], matched caselessly, and in non-UTF-8 mode, if |
3837 | character tables for a French locale are in use, [\xc8-\xcb] matches | character tables for a French locale are in use, [\xc8-\xcb] matches |
3838 | accented E characters in both cases. In UTF-8 mode, PCRE supports the | accented E characters in both cases. In UTF-8 mode, PCRE supports the |
3839 | concept of case for characters with values greater than 128 only when | concept of case for characters with values greater than 128 only when |
3840 | it is compiled with Unicode property support. | it is compiled with Unicode property support. |
3841 | ||
3842 | The character types \d, \D, \p, \P, \s, \S, \w, and \W may also appear | The character types \d, \D, \p, \P, \s, \S, \w, and \W may also appear |
3843 | in a character class, and add the characters that they match to the | in a character class, and add the characters that they match to the |
3844 | class. For example, [\dABCDEF] matches any hexadecimal digit. A circum- | class. For example, [\dABCDEF] matches any hexadecimal digit. A circum- |
3845 | flex can conveniently be used with the upper case character types to | flex can conveniently be used with the upper case character types to |
3846 | specify a more restricted set of characters than the matching lower | specify a more restricted set of characters than the matching lower |
3847 | case type. For example, the class [^\W_] matches any letter or digit, | case type. For example, the class [^\W_] matches any letter or digit, |
3848 | but not underscore. | but not underscore. |
3849 | ||
3850 | The only metacharacters that are recognized in character classes are | The only metacharacters that are recognized in character classes are |
3851 | backslash, hyphen (only where it can be interpreted as specifying a | backslash, hyphen (only where it can be interpreted as specifying a |
3852 | range), circumflex (only at the start), opening square bracket (only | range), circumflex (only at the start), opening square bracket (only |
3853 | when it can be interpreted as introducing a POSIX class name - see the | when it can be interpreted as introducing a POSIX class name - see the |
3854 | next section), and the terminating closing square bracket. However, | next section), and the terminating closing square bracket. However, |
3855 | escaping other non-alphanumeric characters does no harm. | escaping other non-alphanumeric characters does no harm. |
3856 | ||
3857 | ||
3858 | POSIX CHARACTER CLASSES | POSIX CHARACTER CLASSES |
3859 | ||
3860 | Perl supports the POSIX notation for character classes. This uses names | Perl supports the POSIX notation for character classes. This uses names |
3861 | enclosed by [: and :] within the enclosing square brackets. PCRE also | enclosed by [: and :] within the enclosing square brackets. PCRE also |
3862 | supports this notation. For example, | supports this notation. For example, |
3863 | ||
3864 | [01[:alpha:]%] | [01[:alpha:]%] |
# | Line 3820 POSIX CHARACTER CLASSES | Line 3881 POSIX CHARACTER CLASSES |
3881 | word "word" characters (same as \w) | word "word" characters (same as \w) |
3882 | xdigit hexadecimal digits | xdigit hexadecimal digits |
3883 | ||
3884 | The "space" characters are HT (9), LF (10), VT (11), FF (12), CR (13), | The "space" characters are HT (9), LF (10), VT (11), FF (12), CR (13), |
3885 | and space (32). Notice that this list includes the VT character (code | and space (32). Notice that this list includes the VT character (code |
3886 | 11). This makes "space" different to \s, which does not include VT (for | 11). This makes "space" different to \s, which does not include VT (for |
3887 | Perl compatibility). | Perl compatibility). |
3888 | ||
3889 | The name "word" is a Perl extension, and "blank" is a GNU extension | The name "word" is a Perl extension, and "blank" is a GNU extension |
3890 | from Perl 5.8. Another Perl extension is negation, which is indicated | from Perl 5.8. Another Perl extension is negation, which is indicated |
3891 | by a ^ character after the colon. For example, | by a ^ character after the colon. For example, |
3892 | ||
3893 | [12[:^digit:]] | [12[:^digit:]] |
3894 | ||
3895 | matches "1", "2", or any non-digit. PCRE (and Perl) also recognize the | matches "1", "2", or any non-digit. PCRE (and Perl) also recognize the |
3896 | POSIX syntax [.ch.] and [=ch=] where "ch" is a "collating element", but | POSIX syntax [.ch.] and [=ch=] where "ch" is a "collating element", but |
3897 | these are not supported, and an error is given if they are encountered. | these are not supported, and an error is given if they are encountered. |
3898 | ||
# | Line 3841 POSIX CHARACTER CLASSES | Line 3902 POSIX CHARACTER CLASSES |
3902 | ||
3903 | VERTICAL BAR | VERTICAL BAR |
3904 | ||
3905 | Vertical bar characters are used to separate alternative patterns. For | Vertical bar characters are used to separate alternative patterns. For |
3906 | example, the pattern | example, the pattern |
3907 | ||
3908 | gilbert|sullivan | gilbert|sullivan |
3909 | ||
3910 | matches either "gilbert" or "sullivan". Any number of alternatives may | matches either "gilbert" or "sullivan". Any number of alternatives may |
3911 | appear, and an empty alternative is permitted (matching the empty | appear, and an empty alternative is permitted (matching the empty |
3912 | string). The matching process tries each alternative in turn, from left | string). The matching process tries each alternative in turn, from left |
3913 | to right, and the first one that succeeds is used. If the alternatives | to right, and the first one that succeeds is used. If the alternatives |
3914 | are within a subpattern (defined below), "succeeds" means matching the | are within a subpattern (defined below), "succeeds" means matching the |
3915 | rest of the main pattern as well as the alternative in the subpattern. | rest of the main pattern as well as the alternative in the subpattern. |
3916 | ||
3917 | ||
3918 | INTERNAL OPTION SETTING | INTERNAL OPTION SETTING |
3919 | ||
3920 | The settings of the PCRE_CASELESS, PCRE_MULTILINE, PCRE_DOTALL, and | The settings of the PCRE_CASELESS, PCRE_MULTILINE, PCRE_DOTALL, and |
3921 | PCRE_EXTENDED options (which are Perl-compatible) can be changed from | PCRE_EXTENDED options (which are Perl-compatible) can be changed from |
3922 | within the pattern by a sequence of Perl option letters enclosed | within the pattern by a sequence of Perl option letters enclosed |
3923 | between "(?" and ")". The option letters are | between "(?" and ")". The option letters are |
3924 | ||
3925 | i for PCRE_CASELESS | i for PCRE_CASELESS |
# | Line 3868 INTERNAL OPTION SETTING | Line 3929 INTERNAL OPTION SETTING |
3929 | ||
3930 | For example, (?im) sets caseless, multiline matching. It is also possi- | For example, (?im) sets caseless, multiline matching. It is also possi- |
3931 | ble to unset these options by preceding the letter with a hyphen, and a | ble to unset these options by preceding the letter with a hyphen, and a |
3932 | combined setting and unsetting such as (?im-sx), which sets PCRE_CASE- | combined setting and unsetting such as (?im-sx), which sets PCRE_CASE- |
3933 | LESS and PCRE_MULTILINE while unsetting PCRE_DOTALL and PCRE_EXTENDED, | LESS and PCRE_MULTILINE while unsetting PCRE_DOTALL and PCRE_EXTENDED, |
3934 | is also permitted. If a letter appears both before and after the | is also permitted. If a letter appears both before and after the |
3935 | hyphen, the option is unset. | hyphen, the option is unset. |
3936 | ||
3937 | The PCRE-specific options PCRE_DUPNAMES, PCRE_UNGREEDY, and PCRE_EXTRA | The PCRE-specific options PCRE_DUPNAMES, PCRE_UNGREEDY, and PCRE_EXTRA |
3938 | can be changed in the same way as the Perl-compatible options by using | can be changed in the same way as the Perl-compatible options by using |
3939 | the characters J, U and X respectively. | the characters J, U and X respectively. |
3940 | ||
3941 | When one of these option changes occurs at top level (that is, not | When one of these option changes occurs at top level (that is, not |
3942 | inside subpattern parentheses), the change applies to the remainder of | inside subpattern parentheses), the change applies to the remainder of |
3943 | the pattern that follows. If the change is placed right at the start of | the pattern that follows. If the change is placed right at the start of |
3944 | a pattern, PCRE extracts it into the global options (and it will there- | a pattern, PCRE extracts it into the global options (and it will there- |
3945 | fore show up in data extracted by the pcre_fullinfo() function). | fore show up in data extracted by the pcre_fullinfo() function). |
3946 | ||
3947 | An option change within a subpattern (see below for a description of | An option change within a subpattern (see below for a description of |
3948 | subpatterns) affects only that part of the current pattern that follows | subpatterns) affects only that part of the current pattern that follows |
3949 | it, so | it, so |
3950 | ||
3951 | (a(?i)b)c | (a(?i)b)c |
3952 | ||
3953 | matches abc and aBc and no other strings (assuming PCRE_CASELESS is not | matches abc and aBc and no other strings (assuming PCRE_CASELESS is not |
3954 | used). By this means, options can be made to have different settings | used). By this means, options can be made to have different settings |
3955 | in different parts of the pattern. Any changes made in one alternative | in different parts of the pattern. Any changes made in one alternative |
3956 | do carry on into subsequent branches within the same subpattern. For | do carry on into subsequent branches within the same subpattern. For |
3957 | example, | example, |
3958 | ||
3959 | (a(?i)b|c) | (a(?i)b|c) |
3960 | ||
3961 | matches "ab", "aB", "c", and "C", even though when matching "C" the | matches "ab", "aB", "c", and "C", even though when matching "C" the |
3962 | first branch is abandoned before the option setting. This is because | first branch is abandoned before the option setting. This is because |
3963 | the effects of option settings happen at compile time. There would be | the effects of option settings happen at compile time. There would be |
3964 | some very weird behaviour otherwise. | some very weird behaviour otherwise. |
3965 | ||
3966 | Note: There are other PCRE-specific options that can be set by the | Note: There are other PCRE-specific options that can be set by the |
3967 | application when the compile or match functions are called. In some | application when the compile or match functions are called. In some |
3968 | cases the pattern can contain special leading sequences such as (*CRLF) | cases the pattern can contain special leading sequences such as (*CRLF) |
3969 | to override what the application has set or what has been defaulted. | to override what the application has set or what has been defaulted. |
3970 | Details are given in the section entitled "Newline sequences" above. | Details are given in the section entitled "Newline sequences" above. |
3971 | There is also the (*UTF8) leading sequence that can be used to set | There is also the (*UTF8) leading sequence that can be used to set |
3972 | UTF-8 mode; this is equivalent to setting the PCRE_UTF8 option. | UTF-8 mode; this is equivalent to setting the PCRE_UTF8 option. |
3973 | ||
3974 | ||
# | Line 3920 SUBPATTERNS | Line 3981 SUBPATTERNS |
3981 | ||
3982 | cat(aract|erpillar|) | cat(aract|erpillar|) |
3983 | ||
3984 | matches one of the words "cat", "cataract", or "caterpillar". Without | matches one of the words "cat", "cataract", or "caterpillar". Without |
3985 | the parentheses, it would match "cataract", "erpillar" or an empty | the parentheses, it would match "cataract", "erpillar" or an empty |
3986 | string. | string. |
3987 | ||
3988 | 2. It sets up the subpattern as a capturing subpattern. This means | 2. It sets up the subpattern as a capturing subpattern. This means |
3989 | that, when the whole pattern matches, that portion of the subject | that, when the whole pattern matches, that portion of the subject |
3990 | string that matched the subpattern is passed back to the caller via the | string that matched the subpattern is passed back to the caller via the |
3991 | ovector argument of pcre_exec(). Opening parentheses are counted from | ovector argument of pcre_exec(). Opening parentheses are counted from |
3992 | left to right (starting from 1) to obtain numbers for the capturing | left to right (starting from 1) to obtain numbers for the capturing |
3993 | subpatterns. | subpatterns. |
3994 | ||
3995 | 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- |
3996 | tern | tern |
3997 | ||
3998 | the ((red|white) (king|queen)) | the ((red|white) (king|queen)) |
# | Line 3939 SUBPATTERNS | Line 4000 SUBPATTERNS |
4000 | the captured substrings are "red king", "red", and "king", and are num- | the captured substrings are "red king", "red", and "king", and are num- |
4001 | bered 1, 2, and 3, respectively. | bered 1, 2, and 3, respectively. |
4002 | ||
4003 | The fact that plain parentheses fulfil two functions is not always | The fact that plain parentheses fulfil two functions is not always |
4004 | helpful. There are often times when a grouping subpattern is required | helpful. There are often times when a grouping subpattern is required |
4005 | without a capturing requirement. If an opening parenthesis is followed | without a capturing requirement. If an opening parenthesis is followed |
4006 | by a question mark and a colon, the subpattern does not do any captur- | by a question mark and a colon, the subpattern does not do any captur- |
4007 | ing, and is not counted when computing the number of any subsequent | ing, and is not counted when computing the number of any subsequent |
4008 | capturing subpatterns. For example, if the string "the white queen" is | capturing subpatterns. For example, if the string "the white queen" is |
4009 | matched against the pattern | matched against the pattern |
4010 | ||
4011 | the ((?:red|white) (king|queen)) | the ((?:red|white) (king|queen)) |
# | Line 3952 SUBPATTERNS | Line 4013 SUBPATTERNS |
4013 | the captured substrings are "white queen" and "queen", and are numbered | the captured substrings are "white queen" and "queen", and are numbered |
4014 | 1 and 2. The maximum number of capturing subpatterns is 65535. | 1 and 2. The maximum number of capturing subpatterns is 65535. |
4015 | ||
4016 | As a convenient shorthand, if any option settings are required at the | As a convenient shorthand, if any option settings are required at the |
4017 | start of a non-capturing subpattern, the option letters may appear | start of a non-capturing subpattern, the option letters may appear |
4018 | between the "?" and the ":". Thus the two patterns | between the "?" and the ":". Thus the two patterns |
4019 | ||
4020 | (?i:saturday|sunday) | (?i:saturday|sunday) |
4021 | (?:(?i)saturday|sunday) | (?:(?i)saturday|sunday) |
4022 | ||
4023 | match exactly the same set of strings. Because alternative branches are | match exactly the same set of strings. Because alternative branches are |
4024 | tried from left to right, and options are not reset until the end of | tried from left to right, and options are not reset until the end of |
4025 | the subpattern is reached, an option setting in one branch does affect | the subpattern is reached, an option setting in one branch does affect |
4026 | subsequent branches, so the above patterns match "SUNDAY" as well as | subsequent branches, so the above patterns match "SUNDAY" as well as |
4027 | "Saturday". | "Saturday". |
4028 | ||
4029 | ||
4030 | DUPLICATE SUBPATTERN NUMBERS | DUPLICATE SUBPATTERN NUMBERS |
4031 | ||
4032 | Perl 5.10 introduced a feature whereby each alternative in a subpattern | Perl 5.10 introduced a feature whereby each alternative in a subpattern |
4033 | uses the same numbers for its capturing parentheses. Such a subpattern | uses the same numbers for its capturing parentheses. Such a subpattern |
4034 | starts with (?| and is itself a non-capturing subpattern. For example, | starts with (?| and is itself a non-capturing subpattern. For example, |
4035 | consider this pattern: | consider this pattern: |
4036 | ||
4037 | (?|(Sat)ur|(Sun))day | (?|(Sat)ur|(Sun))day |
4038 | ||
4039 | Because the two alternatives are inside a (?| group, both sets of cap- | Because the two alternatives are inside a (?| group, both sets of cap- |
4040 | turing parentheses are numbered one. Thus, when the pattern matches, | turing parentheses are numbered one. Thus, when the pattern matches, |
4041 | you can look at captured substring number one, whichever alternative | you can look at captured substring number one, whichever alternative |
4042 | matched. This construct is useful when you want to capture part, but | matched. This construct is useful when you want to capture part, but |
4043 | not all, of one of a number of alternatives. Inside a (?| group, paren- | not all, of one of a number of alternatives. Inside a (?| group, paren- |
4044 | theses are numbered as usual, but the number is reset at the start of | theses are numbered as usual, but the number is reset at the start of |
4045 | each branch. The numbers of any capturing buffers that follow the sub- | each branch. The numbers of any capturing buffers that follow the sub- |
4046 | pattern start after the highest number used in any branch. The follow- | pattern start after the highest number used in any branch. The follow- |
4047 | ing example is taken from the Perl documentation. The numbers under- | ing example is taken from the Perl documentation. The numbers under- |
4048 | neath show in which buffer the captured content will be stored. | neath show in which buffer the captured content will be stored. |
4049 | ||
4050 | # before ---------------branch-reset----------- after | # before ---------------branch-reset----------- after |
4051 | / ( a ) (?| x ( y ) z | (p (q) r) | (t) u (v) ) ( z ) /x | / ( a ) (?| x ( y ) z | (p (q) r) | (t) u (v) ) ( z ) /x |
4052 | # 1 2 2 3 2 3 4 | # 1 2 2 3 2 3 4 |
4053 | ||
4054 | A backreference or a recursive call to a numbered subpattern always | A backreference to a numbered subpattern uses the most recent value |
4055 | refers to the first one in the pattern with the given number. | that is set for that number by any subpattern. The following pattern |
4056 | matches "abcabc" or "defdef": | |
4057 | ||
4058 | /(?|(abc)|(def))\1/ | |
4059 | ||
4060 | In contrast, a recursive or "subroutine" call to a numbered subpattern | |
4061 | always refers to the first one in the pattern with the given number. | |
4062 | The following pattern matches "abcabc" or "defabc": | |
4063 | ||
4064 | /(?|(abc)|(def))(?1)/ | |
4065 | ||
4066 | If a condition test for a subpattern's having matched refers to a non- | |
4067 | unique number, the test is true if any of the subpatterns of that num- | |
4068 | ber have matched. | |
4069 | ||
4070 | An alternative approach to using this "branch reset" feature is to use | An alternative approach to using this "branch reset" feature is to use |
4071 | duplicate named subpatterns, as described in the next section. | duplicate named subpatterns, as described in the next section. |
# | Line 4006 NAMED SUBPATTERNS | Line 4080 NAMED SUBPATTERNS |
4080 | patterns. This feature was not added to Perl until release 5.10. Python | patterns. This feature was not added to Perl until release 5.10. Python |
4081 | had the feature earlier, and PCRE introduced it at release 4.0, using | had the feature earlier, and PCRE introduced it at release 4.0, using |
4082 | the Python syntax. PCRE now supports both the Perl and the Python syn- | the Python syntax. PCRE now supports both the Perl and the Python syn- |
4083 | tax. | tax. Perl allows identically numbered subpatterns to have different |
4084 | names, but PCRE does not. | |
4085 | ||
4086 | In PCRE, a subpattern can be named in one of three ways: (?<name>...) | In PCRE, a subpattern can be named in one of three ways: (?<name>...) |
4087 | or (?'name'...) as in Perl, or (?P<name>...) as in Python. References | or (?'name'...) as in Perl, or (?P<name>...) as in Python. References |
4088 | to capturing parentheses from other parts of the pattern, such as back- | to capturing parentheses from other parts of the pattern, such as back- |
4089 | references, recursion, and conditions, can be made by name as well as | references, recursion, and conditions, can be made by name as well as |
4090 | by number. | by number. |
4091 | ||
4092 | Names consist of up to 32 alphanumeric characters and underscores. | Names consist of up to 32 alphanumeric characters and underscores. |
4093 | Named capturing parentheses are still allocated numbers as well as | Named capturing parentheses are still allocated numbers as well as |
4094 | names, exactly as if the names were not present. The PCRE API provides | names, exactly as if the names were not present. The PCRE API provides |
4095 | function calls for extracting the name-to-number translation table from | function calls for extracting the name-to-number translation table from |
4096 | a compiled pattern. There is also a convenience function for extracting | a compiled pattern. There is also a convenience function for extracting |
4097 | a captured substring by name. | a captured substring by name. |
4098 | ||
4099 | By default, a name must be unique within a pattern, but it is possible | By default, a name must be unique within a pattern, but it is possible |
4100 | to relax this constraint by setting the PCRE_DUPNAMES option at compile | to relax this constraint by setting the PCRE_DUPNAMES option at compile |
4101 | time. This can be useful for patterns where only one instance of the | time. (Duplicate names are also always permitted for subpatterns with |
4102 | named parentheses can match. Suppose you want to match the name of a | the same number, set up as described in the previous section.) Dupli- |
4103 | weekday, either as a 3-letter abbreviation or as the full name, and in | cate names can be useful for patterns where only one instance of the |
4104 | named parentheses can match. Suppose you want to match the name of a | |
4105 | weekday, either as a 3-letter abbreviation or as the full name, and in | |
4106 | both cases you want to extract the abbreviation. This pattern (ignoring | both cases you want to extract the abbreviation. This pattern (ignoring |
4107 | the line breaks) does the job: | the line breaks) does the job: |
4108 | ||
# | Line 4035 NAMED SUBPATTERNS | Line 4112 NAMED SUBPATTERNS |
4112 | (?<DN>Thu)(?:rsday)?| | (?<DN>Thu)(?:rsday)?| |
4113 | (?<DN>Sat)(?:urday)? | (?<DN>Sat)(?:urday)? |
4114 | ||
4115 | There are five capturing substrings, but only one is ever set after a | There are five capturing substrings, but only one is ever set after a |
4116 | match. (An alternative way of solving this problem is to use a "branch | match. (An alternative way of solving this problem is to use a "branch |
4117 | reset" subpattern, as described in the previous section.) | reset" subpattern, as described in the previous section.) |
4118 | ||
4119 | The convenience function for extracting the data by name returns the | The convenience function for extracting the data by name returns the |
4120 | substring for the first (and in this example, the only) subpattern of | substring for the first (and in this example, the only) subpattern of |
4121 | that name that matched. This saves searching to find which numbered | that name that matched. This saves searching to find which numbered |
4122 | subpattern it was. If you make a reference to a non-unique named sub- | subpattern it was. |
4123 | pattern from elsewhere in the pattern, the one that corresponds to the | |
4124 | lowest number is used. For further details of the interfaces for han- | If you make a backreference to a non-unique named subpattern from else- |
4125 | dling named subpatterns, see the pcreapi documentation. | where in the pattern, the one that corresponds to the first occurrence |
4126 | of the name is used. In the absence of duplicate numbers (see the pre- | |
4127 | vious section) this is the one with the lowest number. If you use a | |
4128 | named reference in a condition test (see the section about conditions | |
4129 | below), either to check whether a subpattern has matched, or to check | |
4130 | for recursion, all subpatterns with the same name are tested. If the | |
4131 | condition is true for any one of them, the overall condition is true. | |
4132 | This is the same behaviour as testing by number. For further details of | |
4133 | the interfaces for handling named subpatterns, see the pcreapi documen- | |
4134 | tation. | |
4135 | ||
4136 | Warning: You cannot use different names to distinguish between two sub- | Warning: You cannot use different names to distinguish between two sub- |
4137 | patterns with the same number (see the previous section) because PCRE | patterns with the same number because PCRE uses only the numbers when |
4138 | uses only the numbers when matching. | matching. For this reason, an error is given at compile time if differ- |
4139 | ent names are given to subpatterns with the same number. However, you | |
4140 | can give the same name to subpatterns with the same number, even when | |
4141 | PCRE_DUPNAMES is not set. | |
4142 | ||
4143 | ||
4144 | REPETITION | REPETITION |
4145 | ||
4146 | Repetition is specified by quantifiers, which can follow any of the | Repetition is specified by quantifiers, which can follow any of the |
4147 | following items: | following items: |
4148 | ||
4149 | a literal data character | a literal data character |
# | Line 4066 REPETITION | Line 4155 REPETITION |
4155 | a character class | a character class |
4156 | a back reference (see next section) | a back reference (see next section) |
4157 | a parenthesized subpattern (unless it is an assertion) | a parenthesized subpattern (unless it is an assertion) |
4158 | a recursive or "subroutine" call to a subpattern | |
4159 | ||
4160 | The general repetition quantifier specifies a minimum and maximum num- | The general repetition quantifier specifies a minimum and maximum num- |
4161 | ber of permitted matches, by giving the two numbers in curly brackets | ber of permitted matches, by giving the two numbers in curly brackets |
4162 | (braces), separated by a comma. The numbers must be less than 65536, | (braces), separated by a comma. The numbers must be less than 65536, |
4163 | and the first must be less than or equal to the second. For example: | and the first must be less than or equal to the second. For example: |
4164 | ||
4165 | z{2,4} | z{2,4} |
4166 | ||
4167 | matches "zz", "zzz", or "zzzz". A closing brace on its own is not a | matches "zz", "zzz", or "zzzz". A closing brace on its own is not a |
4168 | special character. If the second number is omitted, but the comma is | special character. If the second number is omitted, but the comma is |
4169 | present, there is no upper limit; if the second number and the comma | present, there is no upper limit; if the second number and the comma |
4170 | are both omitted, the quantifier specifies an exact number of required | are both omitted, the quantifier specifies an exact number of required |
4171 | matches. Thus | matches. Thus |
4172 | ||
4173 | [aeiou]{3,} | [aeiou]{3,} |
# | Line 4086 REPETITION | Line 4176 REPETITION |
4176 | ||
4177 | \d{8} | \d{8} |
4178 | ||
4179 | matches exactly 8 digits. An opening curly bracket that appears in a | matches exactly 8 digits. An opening curly bracket that appears in a |
4180 | position where a quantifier is not allowed, or one that does not match | position where a quantifier is not allowed, or one that does not match |
4181 | the syntax of a quantifier, is taken as a literal character. For exam- | the syntax of a quantifier, is taken as a literal character. For exam- |
4182 | ple, {,6} is not a quantifier, but a literal string of four characters. | ple, {,6} is not a quantifier, but a literal string of four characters. |
4183 | ||
4184 | In UTF-8 mode, quantifiers apply to UTF-8 characters rather than to | In UTF-8 mode, quantifiers apply to UTF-8 characters rather than to |
4185 | individual bytes. Thus, for example, \x{100}{2} matches two UTF-8 char- | individual bytes. Thus, for example, \x{100}{2} matches two UTF-8 char- |
4186 | acters, each of which is represented by a two-byte sequence. Similarly, | acters, each of which is represented by a two-byte sequence. Similarly, |
4187 | when Unicode property support is available, \X{3} matches three Unicode | when Unicode property support is available, \X{3} matches three Unicode |
4188 | extended sequences, each of which may be several bytes long (and they | extended sequences, each of which may be several bytes long (and they |
4189 | may be of different lengths). | may be of different lengths). |
4190 | ||
4191 | The quantifier {0} is permitted, causing the expression to behave as if | The quantifier {0} is permitted, causing the expression to behave as if |
4192 | the previous item and the quantifier were not present. This may be use- | the previous item and the quantifier were not present. This may be use- |
4193 | ful for subpatterns that are referenced as subroutines from elsewhere | ful for subpatterns that are referenced as subroutines from elsewhere |
4194 | in the pattern. Items other than subpatterns that have a {0} quantifier | in the pattern. Items other than subpatterns that have a {0} quantifier |
4195 | are omitted from the compiled pattern. | are omitted from the compiled pattern. |
4196 | ||
4197 | For convenience, the three most common quantifiers have single-charac- | For convenience, the three most common quantifiers have single-charac- |
4198 | ter abbreviations: | ter abbreviations: |
4199 | ||
4200 | * is equivalent to {0,} | * is equivalent to {0,} |
4201 | + is equivalent to {1,} | + is equivalent to {1,} |
4202 | ? is equivalent to {0,1} | ? is equivalent to {0,1} |
4203 | ||
4204 | It is possible to construct infinite loops by following a subpattern | It is possible to construct infinite loops by following a subpattern |
4205 | that can match no characters with a quantifier that has no upper limit, | that can match no characters with a quantifier that has no upper limit, |
4206 | for example: | for example: |
4207 | ||
4208 | (a?)* | (a?)* |
4209 | ||
4210 | Earlier versions of Perl and PCRE used to give an error at compile time | Earlier versions of Perl and PCRE used to give an error at compile time |
4211 | for such patterns. However, because there are cases where this can be | for such patterns. However, because there are cases where this can be |
4212 | useful, such patterns are now accepted, but if any repetition of the | useful, such patterns are now accepted, but if any repetition of the |
4213 | subpattern does in fact match no characters, the loop is forcibly bro- | subpattern does in fact match no characters, the loop is forcibly bro- |
4214 | ken. | ken. |
4215 | ||
4216 | By default, the quantifiers are "greedy", that is, they match as much | By default, the quantifiers are "greedy", that is, they match as much |
4217 | as possible (up to the maximum number of permitted times), without | as possible (up to the maximum number of permitted times), without |
4218 | causing the rest of the pattern to fail. The classic example of where | causing the rest of the pattern to fail. The classic example of where |
4219 | this gives problems is in trying to match comments in C programs. These | this gives problems is in trying to match comments in C programs. These |
4220 | appear between /* and */ and within the comment, individual * and / | appear between /* and */ and within the comment, individual * and / |
4221 | characters may appear. An attempt to match C comments by applying the | characters may appear. An attempt to match C comments by applying the |
4222 | pattern | pattern |
4223 | ||
4224 | /\*.*\*/ | /\*.*\*/ |
# | Line 4137 REPETITION | Line 4227 REPETITION |
4227 | ||
4228 | /* first comment */ not comment /* second comment */ | /* first comment */ not comment /* second comment */ |
4229 | ||
4230 | fails, because it matches the entire string owing to the greediness of | fails, because it matches the entire string owing to the greediness of |
4231 | the .* item. | the .* item. |
4232 | ||
4233 | However, if a quantifier is followed by a question mark, it ceases to | However, if a quantifier is followed by a question mark, it ceases to |
4234 | be greedy, and instead matches the minimum number of times possible, so | be greedy, and instead matches the minimum number of times possible, so |
4235 | the pattern | the pattern |
4236 | ||
4237 | /\*.*?\*/ | /\*.*?\*/ |
4238 | ||
4239 | does the right thing with the C comments. The meaning of the various | does the right thing with the C comments. The meaning of the various |
4240 | quantifiers is not otherwise changed, just the preferred number of | quantifiers is not otherwise changed, just the preferred number of |
4241 | matches. Do not confuse this use of question mark with its use as a | matches. Do not confuse this use of question mark with its use as a |
4242 | quantifier in its own right. Because it has two uses, it can sometimes | quantifier in its own right. Because it has two uses, it can sometimes |
4243 | appear doubled, as in | appear doubled, as in |
4244 | ||
4245 | \d??\d | \d??\d |
# | Line 4157 REPETITION | Line 4247 REPETITION |
4247 | which matches one digit by preference, but can match two if that is the | which matches one digit by preference, but can match two if that is the |
4248 | only way the rest of the pattern matches. | only way the rest of the pattern matches. |
4249 | ||
4250 | If the PCRE_UNGREEDY option is set (an option that is not available in | If the PCRE_UNGREEDY option is set (an option that is not available in |
4251 | Perl), the quantifiers are not greedy by default, but individual ones | Perl), the quantifiers are not greedy by default, but individual ones |
4252 | can be made greedy by following them with a question mark. In other | can be made greedy by following them with a question mark. In other |
4253 | words, it inverts the default behaviour. | words, it inverts the default behaviour. |
4254 | ||
4255 | When a parenthesized subpattern is quantified with a minimum repeat | When a parenthesized subpattern is quantified with a minimum repeat |
4256 | count that is greater than 1 or with a limited maximum, more memory is | count that is greater than 1 or with a limited maximum, more memory is |
4257 | required for the compiled pattern, in proportion to the size of the | required for the compiled pattern, in proportion to the size of the |
4258 | minimum or maximum. | minimum or maximum. |
4259 | ||
4260 | If a pattern starts with .* or .{0,} and the PCRE_DOTALL option (equiv- | If a pattern starts with .* or .{0,} and the PCRE_DOTALL option (equiv- |
4261 | alent to Perl's /s) is set, thus allowing the dot to match newlines, | alent to Perl's /s) is set, thus allowing the dot to match newlines, |
4262 | the pattern is implicitly anchored, because whatever follows will be | the pattern is implicitly anchored, because whatever follows will be |
4263 | tried against every character position in the subject string, so there | tried against every character position in the subject string, so there |
4264 | is no point in retrying the overall match at any position after the | is no point in retrying the overall match at any position after the |
4265 | first. PCRE normally treats such a pattern as though it were preceded | first. PCRE normally treats such a pattern as though it were preceded |
4266 | by \A. | by \A. |
4267 | ||
4268 | In cases where it is known that the subject string contains no new- | In cases where it is known that the subject string contains no new- |
4269 | lines, it is worth setting PCRE_DOTALL in order to obtain this opti- | lines, it is worth setting PCRE_DOTALL in order to obtain this opti- |
4270 | mization, or alternatively using ^ to indicate anchoring explicitly. | mization, or alternatively using ^ to indicate anchoring explicitly. |
4271 | ||
4272 | However, there is one situation where the optimization cannot be used. | However, there is one situation where the optimization cannot be used. |
4273 | When .* is inside capturing parentheses that are the subject of a | When .* is inside capturing parentheses that are the subject of a |
4274 | backreference elsewhere in the pattern, a match at the start may fail | backreference elsewhere in the pattern, a match at the start may fail |
4275 | where a later one succeeds. Consider, for example: | where a later one succeeds. Consider, for example: |
4276 | ||
4277 | (.*)abc\1 | (.*)abc\1 |
4278 | ||
4279 | If the subject is "xyz123abc123" the match point is the fourth charac- | If the subject is "xyz123abc123" the match point is the fourth charac- |
4280 | ter. For this reason, such a pattern is not implicitly anchored. | ter. For this reason, such a pattern is not implicitly anchored. |
4281 | ||
4282 | When a capturing subpattern is repeated, the value captured is the sub- | When a capturing subpattern is repeated, the value captured is the sub- |
# | Line 4195 REPETITION | Line 4285 REPETITION |
4285 | (tweedle[dume]{3}\s*)+ | (tweedle[dume]{3}\s*)+ |
4286 | ||
4287 | has matched "tweedledum tweedledee" the value of the captured substring | has matched "tweedledum tweedledee" the value of the captured substring |
4288 | is "tweedledee". However, if there are nested capturing subpatterns, | is "tweedledee". However, if there are nested capturing subpatterns, |
4289 | the corresponding captured values may have been set in previous itera- | the corresponding captured values may have been set in previous itera- |
4290 | tions. For example, after | tions. For example, after |
4291 | ||
4292 | /(a|(b))+/ | /(a|(b))+/ |
# | Line 4206 REPETITION | Line 4296 REPETITION |
4296 | ||
4297 | ATOMIC GROUPING AND POSSESSIVE QUANTIFIERS | ATOMIC GROUPING AND POSSESSIVE QUANTIFIERS |
4298 | ||
4299 | With both maximizing ("greedy") and minimizing ("ungreedy" or "lazy") | With both maximizing ("greedy") and minimizing ("ungreedy" or "lazy") |
4300 | repetition, failure of what follows normally causes the repeated item | repetition, failure of what follows normally causes the repeated item |
4301 | to be re-evaluated to see if a different number of repeats allows the | to be re-evaluated to see if a different number of repeats allows the |
4302 | rest of the pattern to match. Sometimes it is useful to prevent this, | rest of the pattern to match. Sometimes it is useful to prevent this, |
4303 | either to change the nature of the match, or to cause it fail earlier | either to change the nature of the match, or to cause it fail earlier |
4304 | than it otherwise might, when the author of the pattern knows there is | than it otherwise might, when the author of the pattern knows there is |
4305 | no point in carrying on. | no point in carrying on. |
4306 | ||
4307 | Consider, for example, the pattern \d+foo when applied to the subject | Consider, for example, the pattern \d+foo when applied to the subject |
4308 | line | line |
4309 | ||
4310 | 123456bar | 123456bar |
4311 | ||
4312 | After matching all 6 digits and then failing to match "foo", the normal | After matching all 6 digits and then failing to match "foo", the normal |
4313 | action of the matcher is to try again with only 5 digits matching the | action of the matcher is to try again with only 5 digits matching the |
4314 | \d+ item, and then with 4, and so on, before ultimately failing. | \d+ item, and then with 4, and so on, before ultimately failing. |
4315 | "Atomic grouping" (a term taken from Jeffrey Friedl's book) provides | "Atomic grouping" (a term taken from Jeffrey Friedl's book) provides |
4316 | the means for specifying that once a subpattern has matched, it is not | the means for specifying that once a subpattern has matched, it is not |
4317 | to be re-evaluated in this way. | to be re-evaluated in this way. |
4318 | ||
4319 | If we use atomic grouping for the previous example, the matcher gives | If we use atomic grouping for the previous example, the matcher gives |
4320 | up immediately on failing to match "foo" the first time. The notation | up immediately on failing to match "foo" the first time. The notation |
4321 | is a kind of special parenthesis, starting with (?> as in this example: | is a kind of special parenthesis, starting with (?> as in this example: |
4322 | ||
4323 | (?>\d+)foo | (?>\d+)foo |
4324 | ||
4325 | This kind of parenthesis "locks up" the part of the pattern it con- | This kind of parenthesis "locks up" the part of the pattern it con- |
4326 | tains once it has matched, and a failure further into the pattern is | tains once it has matched, and a failure further into the pattern is |
4327 | prevented from backtracking into it. Backtracking past it to previous | prevented from backtracking into it. Backtracking past it to previous |
4328 | items, however, works as normal. | items, however, works as normal. |
4329 | ||
4330 | An alternative description is that a subpattern of this type matches | An alternative description is that a subpattern of this type matches |
4331 | the string of characters that an identical standalone pattern would | the string of characters that an identical standalone pattern would |
4332 | match, if anchored at the current point in the subject string. | match, if anchored at the current point in the subject string. |
4333 | ||
4334 | Atomic grouping subpatterns are not capturing subpatterns. Simple cases | Atomic grouping subpatterns are not capturing subpatterns. Simple cases |
4335 | such as the above example can be thought of as a maximizing repeat that | such as the above example can be thought of as a maximizing repeat that |
4336 | must swallow everything it can. So, while both \d+ and \d+? are pre- | must swallow everything it can. So, while both \d+ and \d+? are pre- |
4337 | pared to adjust the number of digits they match in order to make the | pared to adjust the number of digits they match in order to make the |
4338 | rest of the pattern match, (?>\d+) can only match an entire sequence of | rest of the pattern match, (?>\d+) can only match an entire sequence of |
4339 | digits. | digits. |
4340 | ||
4341 | Atomic groups in general can of course contain arbitrarily complicated | Atomic groups in general can of course contain arbitrarily complicated |
4342 | subpatterns, and can be nested. However, when the subpattern for an | subpatterns, and can be nested. However, when the subpattern for an |
4343 | atomic group is just a single repeated item, as in the example above, a | atomic group is just a single repeated item, as in the example above, a |
4344 | simpler notation, called a "possessive quantifier" can be used. This | simpler notation, called a "possessive quantifier" can be used. This |
4345 | consists of an additional + character following a quantifier. Using | consists of an additional + character following a quantifier. Using |
4346 | this notation, the previous example can be rewritten as | this notation, the previous example can be rewritten as |
4347 | ||
4348 | \d++foo | \d++foo |
# | Line 4262 ATOMIC GROUPING AND POSSESSIVE QUANTIFIE | Line 4352 ATOMIC GROUPING AND POSSESSIVE QUANTIFIE |
4352 | ||
4353 | (abc|xyz){2,3}+ | (abc|xyz){2,3}+ |
4354 | ||
4355 | Possessive quantifiers are always greedy; the setting of the | Possessive quantifiers are always greedy; the setting of the |
4356 | PCRE_UNGREEDY option is ignored. They are a convenient notation for the | PCRE_UNGREEDY option is ignored. They are a convenient notation for the |
4357 | simpler forms of atomic group. However, there is no difference in the | simpler forms of atomic group. However, there is no difference in the |
4358 | meaning of a possessive quantifier and the equivalent atomic group, | meaning of a possessive quantifier and the equivalent atomic group, |
4359 | though there may be a performance difference; possessive quantifiers | though there may be a performance difference; possessive quantifiers |
4360 | should be slightly faster. | should be slightly faster. |
4361 | ||
4362 | The possessive quantifier syntax is an extension to the Perl 5.8 syn- | The possessive quantifier syntax is an extension to the Perl 5.8 syn- |
4363 | tax. Jeffrey Friedl originated the idea (and the name) in the first | tax. Jeffrey Friedl originated the idea (and the name) in the first |
4364 | edition of his book. Mike McCloskey liked it, so implemented it when he | edition of his book. Mike McCloskey liked it, so implemented it when he |
4365 | built Sun's Java package, and PCRE copied it from there. It ultimately | built Sun's Java package, and PCRE copied it from there. It ultimately |
4366 | found its way into Perl at release 5.10. | found its way into Perl at release 5.10. |
4367 | ||
4368 | PCRE has an optimization that automatically "possessifies" certain sim- | PCRE has an optimization that automatically "possessifies" certain sim- |
4369 | ple pattern constructs. For example, the sequence A+B is treated as | ple pattern constructs. For example, the sequence A+B is treated as |
4370 | A++B because there is no point in backtracking into a sequence of A's | A++B because there is no point in backtracking into a sequence of A's |
4371 | when B must follow. | when B must follow. |
4372 | ||
4373 | When a pattern contains an unlimited repeat inside a subpattern that | When a pattern contains an unlimited repeat inside a subpattern that |
4374 | can itself be repeated an unlimited number of times, the use of an | can itself be repeated an unlimited number of times, the use of an |
4375 | atomic group is the only way to avoid some failing matches taking a | atomic group is the only way to avoid some failing matches taking a |
4376 | very long time indeed. The pattern | very long time indeed. The pattern |
4377 | ||
4378 | (\D+|<\d+>)*[!?] | (\D+|<\d+>)*[!?] |
4379 | ||
4380 | matches an unlimited number of substrings that either consist of non- | matches an unlimited number of substrings that either consist of non- |
4381 | digits, or digits enclosed in <>, followed by either ! or ?. When it | digits, or digits enclosed in <>, followed by either ! or ?. When it |
4382 | matches, it runs quickly. However, if it is applied to | matches, it runs quickly. However, if it is applied to |
4383 | ||
4384 | aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa | aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa |
4385 | ||
4386 | it takes a long time before reporting failure. This is because the | it takes a long time before reporting failure. This is because the |
4387 | string can be divided between the internal \D+ repeat and the external | string can be divided between the internal \D+ repeat and the external |
4388 | * repeat in a large number of ways, and all have to be tried. (The | * repeat in a large number of ways, and all have to be tried. (The |
4389 | example uses [!?] rather than a single character at the end, because | example uses [!?] rather than a single character at the end, because |
4390 | both PCRE and Perl have an optimization that allows for fast failure | both PCRE and Perl have an optimization that allows for fast failure |
4391 | when a single character is used. They remember the last single charac- | when a single character is used. They remember the last single charac- |
4392 | ter that is required for a match, and fail early if it is not present | ter that is required for a match, and fail early if it is not present |
4393 | in the string.) If the pattern is changed so that it uses an atomic | in the string.) If the pattern is changed so that it uses an atomic |
4394 | group, like this: | group, like this: |
4395 | ||
4396 | ((?>\D+)|<\d+>)*[!?] | ((?>\D+)|<\d+>)*[!?] |
# | Line 4312 BACK REFERENCES | Line 4402 BACK REFERENCES |
4402 | ||
4403 | Outside a character class, a backslash followed by a digit greater than | Outside a character class, a backslash followed by a digit greater than |
4404 | 0 (and possibly further digits) is a back reference to a capturing sub- | 0 (and possibly further digits) is a back reference to a capturing sub- |
4405 | pattern earlier (that is, to its left) in the pattern, provided there | pattern earlier (that is, to its left) in the pattern, provided there |
4406 | have been that many previous capturing left parentheses. | have been that many previous capturing left parentheses. |
4407 | ||
4408 | However, if the decimal number following the backslash is less than 10, | However, if the decimal number following the backslash is less than 10, |
4409 | it is always taken as a back reference, and causes an error only if | it is always taken as a back reference, and causes an error only if |
4410 | there are not that many capturing left parentheses in the entire pat- | there are not that many capturing left parentheses in the entire pat- |
4411 | tern. In other words, the parentheses that are referenced need not be | tern. In other words, the parentheses that are referenced need not be |
4412 | to the left of the reference for numbers less than 10. A "forward back | to the left of the reference for numbers less than 10. A "forward back |
4413 | reference" of this type can make sense when a repetition is involved | reference" of this type can make sense when a repetition is involved |
4414 | and the subpattern to the right has participated in an earlier itera- | and the subpattern to the right has participated in an earlier itera- |
4415 | tion. | tion. |
4416 | ||
4417 | It is not possible to have a numerical "forward back reference" to a | It is not possible to have a numerical "forward back reference" to a |
4418 | subpattern whose number is 10 or more using this syntax because a | subpattern whose number is 10 or more using this syntax because a |
4419 | sequence such as \50 is interpreted as a character defined in octal. | sequence such as \50 is interpreted as a character defined in octal. |
4420 | See the subsection entitled "Non-printing characters" above for further | See the subsection entitled "Non-printing characters" above for further |
4421 | details of the handling of digits following a backslash. There is no | details of the handling of digits following a backslash. There is no |
4422 | such problem when named parentheses are used. A back reference to any | such problem when named parentheses are used. A back reference to any |
4423 | subpattern is possible using named parentheses (see below). | subpattern is possible using named parentheses (see below). |
4424 | ||
4425 | Another way of avoiding the ambiguity inherent in the use of digits | Another way of avoiding the ambiguity inherent in the use of digits |
4426 | following a backslash is to use the \g escape sequence, which is a fea- | following a backslash is to use the \g escape sequence, which is a fea- |
4427 | ture introduced in Perl 5.10. This escape must be followed by an | ture introduced in Perl 5.10. This escape must be followed by an |
4428 | unsigned number or a negative number, optionally enclosed in braces. | unsigned number or a negative number, optionally enclosed in braces. |
4429 | These examples are all identical: | These examples are all identical: |
4430 | ||
4431 | (ring), \1 | (ring), \1 |
4432 | (ring), \g1 | (ring), \g1 |
4433 | (ring), \g{1} | (ring), \g{1} |
4434 | ||
4435 | An unsigned number specifies an absolute reference without the ambigu- | An unsigned number specifies an absolute reference without the ambigu- |
4436 | ity that is present in the older syntax. It is also useful when literal | ity that is present in the older syntax. It is also useful when literal |
4437 | digits follow the reference. A negative number is a relative reference. | digits follow the reference. A negative number is a relative reference. |
4438 | Consider this example: | Consider this example: |
# | Line 4350 BACK REFERENCES | Line 4440 BACK REFERENCES |
4440 | (abc(def)ghi)\g{-1} | (abc(def)ghi)\g{-1} |
4441 | ||
4442 | The sequence \g{-1} is a reference to the most recently started captur- | The sequence \g{-1} is a reference to the most recently started captur- |
4443 | ing subpattern before \g, that is, is it equivalent to \2. Similarly, | ing subpattern before \g, that is, is it equivalent to \2. Similarly, |
4444 | \g{-2} would be equivalent to \1. The use of relative references can be | \g{-2} would be equivalent to \1. The use of relative references can be |
4445 | helpful in long patterns, and also in patterns that are created by | helpful in long patterns, and also in patterns that are created by |
4446 | joining together fragments that contain references within themselves. | joining together fragments that contain references within themselves. |
4447 | ||
4448 | A back reference matches whatever actually matched the capturing sub- | A back reference matches whatever actually matched the capturing sub- |
4449 | pattern in the current subject string, rather than anything matching | pattern in the current subject string, rather than anything matching |
4450 | the subpattern itself (see "Subpatterns as subroutines" below for a way | the subpattern itself (see "Subpatterns as subroutines" below for a way |
4451 | of doing that). So the pattern | of doing that). So the pattern |
4452 | ||
4453 | (sens|respons)e and \1ibility | (sens|respons)e and \1ibility |
4454 | ||
4455 | matches "sense and sensibility" and "response and responsibility", but | matches "sense and sensibility" and "response and responsibility", but |
4456 | not "sense and responsibility". If caseful matching is in force at the | not "sense and responsibility". If caseful matching is in force at the |
4457 | time of the back reference, the case of letters is relevant. For exam- | time of the back reference, the case of letters is relevant. For exam- |
4458 | ple, | ple, |
4459 | ||
4460 | ((?i)rah)\s+\1 | ((?i)rah)\s+\1 |
4461 | ||
4462 | 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 |
4463 | original capturing subpattern is matched caselessly. | original capturing subpattern is matched caselessly. |
4464 | ||
4465 | There are several different ways of writing back references to named | There are several different ways of writing back references to named |
4466 | subpatterns. The .NET syntax \k{name} and the Perl syntax \k<name> or | subpatterns. The .NET syntax \k{name} and the Perl syntax \k<name> or |
4467 | \k'name' are supported, as is the Python syntax (?P=name). Perl 5.10's | \k'name' are supported, as is the Python syntax (?P=name). Perl 5.10's |
4468 | unified back reference syntax, in which \g can be used for both numeric | unified back reference syntax, in which \g can be used for both numeric |
4469 | and named references, is also supported. We could rewrite the above | and named references, is also supported. We could rewrite the above |
4470 | example in any of the following ways: | example in any of the following ways: |
4471 | ||
4472 | (?<p1>(?i)rah)\s+\k<p1> | (?<p1>(?i)rah)\s+\k<p1> |
# | Line 4384 BACK REFERENCES | Line 4474 BACK REFERENCES |
4474 | (?P<p1>(?i)rah)\s+(?P=p1) | (?P<p1>(?i)rah)\s+(?P=p1) |
4475 | (?<p1>(?i)rah)\s+\g{p1} | (?<p1>(?i)rah)\s+\g{p1} |
4476 | ||
4477 | A subpattern that is referenced by name may appear in the pattern | A subpattern that is referenced by name may appear in the pattern |
4478 | before or after the reference. | before or after the reference. |
4479 | ||
4480 | There may be more than one back reference to the same subpattern. If a | There may be more than one back reference to the same subpattern. If a |
4481 | subpattern has not actually been used in a particular match, any back | subpattern has not actually been used in a particular match, any back |
4482 | references to it always fail. For example, the pattern | references to it always fail by default. For example, the pattern |
4483 | ||
4484 | (a|(bc))\2 | (a|(bc))\2 |
4485 | ||
4486 | always fails if it starts to match "a" rather than "bc". Because there | always fails if it starts to match "a" rather than "bc". However, if |
4487 | may be many capturing parentheses in a pattern, all digits following | the PCRE_JAVASCRIPT_COMPAT option is set at compile time, a back refer- |
4488 | the backslash are taken as part of a potential back reference number. | ence to an unset value matches an empty string. |
4489 | If the pattern continues with a digit character, some delimiter must be | |
4490 | used to terminate the back reference. If the PCRE_EXTENDED option is | Because there may be many capturing parentheses in a pattern, all dig- |
4491 | set, this can be whitespace. Otherwise an empty comment (see "Com- | its following a backslash are taken as part of a potential back refer- |
4492 | ments" below) can be used. | ence number. If the pattern continues with a digit character, some |
4493 | delimiter must be used to terminate the back reference. If the | |
4494 | PCRE_EXTENDED option is set, this can be whitespace. Otherwise, the \g{ | |
4495 | syntax or an empty comment (see "Comments" below) can be used. | |
4496 | ||
4497 | A back reference that occurs inside the parentheses to which it refers | A back reference that occurs inside the parentheses to which it refers |
4498 | fails when the subpattern is first used, so, for example, (a\1) never | fails when the subpattern is first used, so, for example, (a\1) never |
# | Line 4462 ASSERTIONS | Line 4555 ASSERTIONS |
4555 | If you want to force a matching failure at some point in a pattern, the | If you want to force a matching failure at some point in a pattern, the |
4556 | most convenient way to do it is with (?!) because an empty string | most convenient way to do it is with (?!) because an empty string |
4557 | always matches, so an assertion that requires there not to be an empty | always matches, so an assertion that requires there not to be an empty |
4558 | string must always fail. | string must always fail. The Perl 5.10 backtracking control verb |
4559 | (*FAIL) or (*F) is essentially a synonym for (?!). | |
4560 | ||
4561 | Lookbehind assertions | Lookbehind assertions |
4562 | ||
4563 | Lookbehind assertions start with (?<= for positive assertions and (?<! | Lookbehind assertions start with (?<= for positive assertions and (?<! |
4564 | for negative assertions. For example, | for negative assertions. For example, |
4565 | ||
4566 | (?<!foo)bar | (?<!foo)bar |
4567 | ||
4568 | does find an occurrence of "bar" that is not preceded by "foo". The | does find an occurrence of "bar" that is not preceded by "foo". The |
4569 | contents of a lookbehind assertion are restricted such that all the | contents of a lookbehind assertion are restricted such that all the |
4570 | strings it matches must have a fixed length. However, if there are sev- | strings it matches must have a fixed length. However, if there are sev- |
4571 | eral top-level alternatives, they do not all have to have the same | eral top-level alternatives, they do not all have to have the same |
4572 | fixed length. Thus | fixed length. Thus |
4573 | ||
4574 | (?<=bullock|donkey) | (?<=bullock|donkey) |
# | Line 4483 ASSERTIONS | Line 4577 ASSERTIONS |
4577 | ||
4578 | (?<!dogs?|cats?) | (?<!dogs?|cats?) |
4579 | ||
4580 | causes an error at compile time. Branches that match different length | causes an error at compile time. Branches that match different length |
4581 | strings are permitted only at the top level of a lookbehind assertion. | strings are permitted only at the top level of a lookbehind assertion. |
4582 | This is an extension compared with Perl (5.8 and 5.10), which requires | This is an extension compared with Perl (5.8 and 5.10), which requires |
4583 | all branches to match the same length of string. An assertion such as | all branches to match the same length of string. An assertion such as |
4584 | ||
4585 | (?<=ab(c|de)) | (?<=ab(c|de)) |
4586 | ||
4587 | is not permitted, because its single top-level branch can match two | is not permitted, because its single top-level branch can match two |
4588 | different lengths, but it is acceptable to PCRE if rewritten to use two | different lengths, but it is acceptable to PCRE if rewritten to use two |
4589 | top-level branches: | top-level branches: |
4590 | ||
4591 | (?<=abc|abde) | (?<=abc|abde) |
4592 | ||
4593 | In some cases, the Perl 5.10 escape sequence \K (see above) can be used | In some cases, the Perl 5.10 escape sequence \K (see above) can be used |
4594 | instead of a lookbehind assertion to get round the fixed-length | instead of a lookbehind assertion to get round the fixed-length |
4595 | restriction. | restriction. |
4596 | ||
4597 | The implementation of lookbehind assertions is, for each alternative, | The implementation of lookbehind assertions is, for each alternative, |
4598 | to temporarily move the current position back by the fixed length and | to temporarily move the current position back by the fixed length and |
4599 | then try to match. If there are insufficient characters before the cur- | then try to match. If there are insufficient characters before the cur- |
4600 | rent position, the assertion fails. | rent position, the assertion fails. |
4601 | ||
4602 | PCRE does not allow the \C escape (which matches a single byte in UTF-8 | PCRE does not allow the \C escape (which matches a single byte in UTF-8 |
4603 | mode) to appear in lookbehind assertions, because it makes it impossi- | mode) to appear in lookbehind assertions, because it makes it impossi- |
4604 | ble to calculate the length of the lookbehind. The \X and \R escapes, | ble to calculate the length of the lookbehind. The \X and \R escapes, |
4605 | which can match different numbers of bytes, are also not permitted. | which can match different numbers of bytes, are also not permitted. |
4606 | ||
4607 | "Subroutine" calls (see below) such as (?2) or (?&X) are permitted in | "Subroutine" calls (see below) such as (?2) or (?&X) are permitted in |
4608 | lookbehinds, as long as the subpattern matches a fixed-length string. | lookbehinds, as long as the subpattern matches a fixed-length string. |
4609 | Recursion, however, is not supported. | Recursion, however, is not supported. |
4610 | ||
4611 | Possessive quantifiers can be used in conjunction with lookbehind | Possessive quantifiers can be used in conjunction with lookbehind |
4612 | assertions to specify efficient matching at the end of the subject | assertions to specify efficient matching of fixed-length strings at the |
4613 | string. Consider a simple pattern such as | end of subject strings. Consider a simple pattern such as |
4614 | ||
4615 | abcd$ | abcd$ |
4616 | ||
4617 | when applied to a long string that does not match. Because matching | when applied to a long string that does not match. Because matching |
4618 | proceeds from left to right, PCRE will look for each "a" in the subject | proceeds from left to right, PCRE will look for each "a" in the subject |
4619 | and then see if what follows matches the rest of the pattern. If the | and then see if what follows matches the rest of the pattern. If the |
4620 | pattern is specified as | pattern is specified as |
4621 | ||
4622 | ^.*abcd$ | ^.*abcd$ |
4623 | ||
4624 | the initial .* matches the entire string at first, but when this fails | the initial .* matches the entire string at first, but when this fails |
4625 | (because there is no following "a"), it backtracks to match all but the | (because there is no following "a"), it backtracks to match all but the |
4626 | last character, then all but the last two characters, and so on. Once | last character, then all but the last two characters, and so on. Once |
4627 | again the search for "a" covers the entire string, from right to left, | again the search for "a" covers the entire string, from right to left, |
4628 | so we are no better off. However, if the pattern is written as | so we are no better off. However, if the pattern is written as |
4629 | ||
4630 | ^.*+(?<=abcd) | ^.*+(?<=abcd) |
4631 | ||
4632 | there can be no backtracking for the .*+ item; it can match only the | there can be no backtracking for the .*+ item; it can match only the |
4633 | entire string. The subsequent lookbehind assertion does a single test | entire string. The subsequent lookbehind assertion does a single test |
4634 | on the last four characters. If it fails, the match fails immediately. | on the last four characters. If it fails, the match fails immediately. |
4635 | For long strings, this approach makes a significant difference to the | For long strings, this approach makes a significant difference to the |
4636 | processing time. | processing time. |
4637 | ||
4638 | Using multiple assertions | Using multiple assertions |
# | Line 4547 ASSERTIONS | Line 4641 ASSERTIONS |
4641 | ||
4642 | (?<=\d{3})(?<!999)foo | (?<=\d{3})(?<!999)foo |
4643 | ||
4644 | matches "foo" preceded by three digits that are not "999". Notice that | matches "foo" preceded by three digits that are not "999". Notice that |
4645 | each of the assertions is applied independently at the same point in | each of the assertions is applied independently at the same point in |
4646 | the subject string. First there is a check that the previous three | the subject string. First there is a check that the previous three |
4647 | characters are all digits, and then there is a check that the same | characters are all digits, and then there is a check that the same |
4648 | three characters are not "999". This pattern does not match "foo" pre- | three characters are not "999". This pattern does not match "foo" pre- |
4649 | ceded by six characters, the first of which are digits and the last | ceded by six characters, the first of which are digits and the last |
4650 | three of which are not "999". For example, it doesn't match "123abc- | three of which are not "999". For example, it doesn't match "123abc- |
4651 | foo". A pattern to do that is | foo". A pattern to do that is |
4652 | ||
4653 | (?<=\d{3}...)(?<!999)foo | (?<=\d{3}...)(?<!999)foo |
4654 | ||
4655 | This time the first assertion looks at the preceding six characters, | This time the first assertion looks at the preceding six characters, |
4656 | checking that the first three are digits, and then the second assertion | checking that the first three are digits, and then the second assertion |
4657 | checks that the preceding three characters are not "999". | checks that the preceding three characters are not "999". |
4658 | ||
# | Line 4566 ASSERTIONS | Line 4660 ASSERTIONS |
4660 | ||
4661 | (?<=(?<!foo)bar)baz | (?<=(?<!foo)bar)baz |
4662 | ||
4663 | matches an occurrence of "baz" that is preceded by "bar" which in turn | matches an occurrence of "baz" that is preceded by "bar" which in turn |
4664 | is not preceded by "foo", while | is not preceded by "foo", while |
4665 | ||
4666 | (?<=\d{3}(?!999)...)foo | (?<=\d{3}(?!999)...)foo |
4667 | ||
4668 | is another pattern that matches "foo" preceded by three digits and any | is another pattern that matches "foo" preceded by three digits and any |
4669 | three characters that are not "999". | three characters that are not "999". |
4670 | ||
4671 | ||
4672 | CONDITIONAL SUBPATTERNS | CONDITIONAL SUBPATTERNS |
4673 | ||
4674 | It is possible to cause the matching process to obey a subpattern con- | It is possible to cause the matching process to obey a subpattern con- |
4675 | ditionally or to choose between two alternative subpatterns, depending | ditionally or to choose between two alternative subpatterns, depending |
4676 | on the result of an assertion, or whether a previous capturing subpat- | on the result of an assertion, or whether a specific capturing subpat- |
4677 | tern matched or not. The two possible forms of conditional subpattern | tern has already been matched. The two possible forms of conditional |
4678 | are | subpattern are: |
4679 | ||
4680 | (?(condition)yes-pattern) | (?(condition)yes-pattern) |
4681 | (?(condition)yes-pattern|no-pattern) | (?(condition)yes-pattern|no-pattern) |
4682 | ||
4683 | If the condition is satisfied, the yes-pattern is used; otherwise the | If the condition is satisfied, the yes-pattern is used; otherwise the |
4684 | no-pattern (if present) is used. If there are more than two alterna- | no-pattern (if present) is used. If there are more than two alterna- |
4685 | tives in the subpattern, a compile-time error occurs. | tives in the subpattern, a compile-time error occurs. |
4686 | ||
4687 | There are four kinds of condition: references to subpatterns, refer- | There are four kinds of condition: references to subpatterns, refer- |
4688 | ences to recursion, a pseudo-condition called DEFINE, and assertions. | ences to recursion, a pseudo-condition called DEFINE, and assertions. |
4689 | ||
4690 | Checking for a used subpattern by number | Checking for a used subpattern by number |
4691 | ||
4692 | If the text between the parentheses consists of a sequence of digits, | If the text between the parentheses consists of a sequence of digits, |
4693 | the condition is true if the capturing subpattern of that number has | the condition is true if a capturing subpattern of that number has pre- |
4694 | previously matched. An alternative notation is to precede the digits | viously matched. If there is more than one capturing subpattern with |
4695 | with a plus or minus sign. In this case, the subpattern number is rela- | the same number (see the earlier section about duplicate subpattern |
4696 | tive rather than absolute. The most recently opened parentheses can be | numbers), the condition is true if any of them have been set. An alter- |
4697 | referenced by (?(-1), the next most recent by (?(-2), and so on. In | native notation is to precede the digits with a plus or minus sign. In |
4698 | looping constructs it can also make sense to refer to subsequent groups | this case, the subpattern number is relative rather than absolute. The |
4699 | with constructs such as (?(+2). | most recently opened parentheses can be referenced by (?(-1), the next |
4700 | most recent by (?(-2), and so on. In looping constructs it can also | |
4701 | make sense to refer to subsequent groups with constructs such as | |
4702 | (?(+2). | |
4703 | ||
4704 | Consider the following pattern, which contains non-significant white | Consider the following pattern, which contains non-significant white |
4705 | space to make it more readable (assume the PCRE_EXTENDED option) and to | space to make it more readable (assume the PCRE_EXTENDED option) and to |
# | Line 4645 CONDITIONAL SUBPATTERNS | Line 4742 CONDITIONAL SUBPATTERNS |
4742 | ||
4743 | (?<OPEN> \( )? [^()]+ (?(<OPEN>) \) ) | (?<OPEN> \( )? [^()]+ (?(<OPEN>) \) ) |
4744 | ||
4745 | If the name used in a condition of this kind is a duplicate, the test | |
4746 | is applied to all subpatterns of the same name, and is true if any one | |
4747 | of them has matched. | |
4748 | ||
4749 | Checking for pattern recursion | Checking for pattern recursion |
4750 | ||
# | Line 4655 CONDITIONAL SUBPATTERNS | Line 4755 CONDITIONAL SUBPATTERNS |
4755 | ||
4756 | (?(R3)...) or (?(R&name)...) | (?(R3)...) or (?(R&name)...) |
4757 | ||
4758 | the condition is true if the most recent recursion is into the subpat- | the condition is true if the most recent recursion is into a subpattern |
4759 | tern whose number or name is given. This condition does not check the | whose number or name is given. This condition does not check the entire |
4760 | entire recursion stack. | recursion stack. If the name used in a condition of this kind is a |
4761 | duplicate, the test is applied to all subpatterns of the same name, and | |
4762 | is true if any one of them is the most recent recursion. | |
4763 | ||
4764 | At "top level", all these recursion test conditions are false. Recur- | At "top level", all these recursion test conditions are false. The |
4765 | sive patterns are described below. | syntax for recursive patterns is described below. |
4766 | ||
4767 | Defining subpatterns for use by reference only | Defining subpatterns for use by reference only |
4768 | ||
# | Line 4680 CONDITIONAL SUBPATTERNS | Line 4782 CONDITIONAL SUBPATTERNS |
4782 | group named "byte" is defined. This matches an individual component of | group named "byte" is defined. This matches an individual component of |
4783 | an IPv4 address (a number less than 256). When matching takes place, | an IPv4 address (a number less than 256). When matching takes place, |
4784 | this part of the pattern is skipped because DEFINE acts like a false | this part of the pattern is skipped because DEFINE acts like a false |
4785 | condition. | condition. The rest of the pattern uses references to the named group |
4786 | to match the four dot-separated components of an IPv4 address, insist- | |
4787 | The rest of the pattern uses references to the named group to match the | ing on a word boundary at each end. |
four dot-separated components of an IPv4 address, insisting on a word | ||
boundary at each end. | ||
4788 | ||
4789 | Assertion conditions | Assertion conditions |
4790 | ||
# | Line 4752 RECURSIVE PATTERNS | Line 4852 RECURSIVE PATTERNS |
4852 | This PCRE pattern solves the nested parentheses problem (assume the | This PCRE pattern solves the nested parentheses problem (assume the |
4853 | PCRE_EXTENDED option is set so that white space is ignored): | PCRE_EXTENDED option is set so that white space is ignored): |
4854 | ||
4855 | \( ( (?>[^()]+) | (?R) )* \) | \( ( [^()]++ | (?R) )* \) |
4856 | ||
4857 | First it matches an opening parenthesis. Then it matches any number of | First it matches an opening parenthesis. Then it matches any number of |
4858 | substrings which can either be a sequence of non-parentheses, or a | substrings which can either be a sequence of non-parentheses, or a |
4859 | recursive match of the pattern itself (that is, a correctly parenthe- | recursive match of the pattern itself (that is, a correctly parenthe- |
4860 | sized substring). Finally there is a closing parenthesis. | sized substring). Finally there is a closing parenthesis. Note the use |
4861 | of a possessive quantifier to avoid backtracking into sequences of non- | |
4862 | parentheses. | |
4863 | ||
4864 | If this were part of a larger pattern, you would not want to recurse | If this were part of a larger pattern, you would not want to recurse |
4865 | the entire pattern, so instead you could use this: | the entire pattern, so instead you could use this: |
4866 | ||
4867 | ( \( ( (?>[^()]+) | (?1) )* \) ) | ( \( ( [^()]++ | (?1) )* \) ) |
4868 | ||
4869 | We have put the pattern into parentheses, and caused the recursion to | We have put the pattern into parentheses, and caused the recursion to |
4870 | refer to them instead of the whole pattern. | refer to them instead of the whole pattern. |
4871 | ||
4872 | In a larger pattern, keeping track of parenthesis numbers can be | In a larger pattern, keeping track of parenthesis numbers can be |
4873 | tricky. This is made easier by the use of relative references. (A Perl | tricky. This is made easier by the use of relative references (a Perl |
4874 | 5.10 feature.) Instead of (?1) in the pattern above you can write | 5.10 feature). Instead of (?1) in the pattern above you can write |
4875 | (?-2) to refer to the second most recently opened parentheses preceding | (?-2) to refer to the second most recently opened parentheses preceding |
4876 | the recursion. In other words, a negative number counts capturing | the recursion. In other words, a negative number counts capturing |
4877 | parentheses leftwards from the point at which it is encountered. | parentheses leftwards from the point at which it is encountered. |
# | Line 4784 RECURSIVE PATTERNS | Line 4886 RECURSIVE PATTERNS |
4886 | syntax for this is (?&name); PCRE's earlier syntax (?P>name) is also | syntax for this is (?&name); PCRE's earlier syntax (?P>name) is also |
4887 | supported. We could rewrite the above example as follows: | supported. We could rewrite the above example as follows: |
4888 | ||
4889 | (?<pn> \( ( (?>[^()]+) | (?&pn) )* \) ) | (?<pn> \( ( [^()]++ | (?&pn) )* \) ) |
4890 | ||
4891 | If there is more than one subpattern with the same name, the earliest | If there is more than one subpattern with the same name, the earliest |
4892 | one is used. | one is used. |
4893 | ||
4894 | This particular example pattern that we have been looking at contains | This particular example pattern that we have been looking at contains |
4895 | nested unlimited repeats, and so the use of atomic grouping for match- | nested unlimited repeats, and so the use of a possessive quantifier for |
4896 | ing strings of non-parentheses is important when applying the pattern | matching strings of non-parentheses is important when applying the pat- |
4897 | to strings that do not match. For example, when this pattern is applied | tern to strings that do not match. For example, when this pattern is |
4898 | to | applied to |
4899 | ||
4900 | (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa() | (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa() |
4901 | ||
4902 | it yields "no match" quickly. However, if atomic grouping is not used, | it yields "no match" quickly. However, if a possessive quantifier is |
4903 | the match runs for a very long time indeed because there are so many | not used, the match runs for a very long time indeed because there are |
4904 | different ways the + and * repeats can carve up the subject, and all | so many different ways the + and * repeats can carve up the subject, |
4905 | have to be tested before failure can be reported. | and all have to be tested before failure can be reported. |
4906 | ||
4907 | At the end of a match, the values set for any capturing subpatterns are | At the end of a match, the values set for any capturing subpatterns are |
4908 | those from the outermost level of the recursion at which the subpattern | those from the outermost level of the recursion at which the subpattern |
# | Line 4814 RECURSIVE PATTERNS | Line 4916 RECURSIVE PATTERNS |
4916 | value taken on at the top level. If additional parentheses are added, | value taken on at the top level. If additional parentheses are added, |
4917 | giving | giving |
4918 | ||
4919 | \( ( ( (?>[^()]+) | (?R) )* ) \) | \( ( ( [^()]++ | (?R) )* ) \) |
4920 | ^ ^ | ^ ^ |
4921 | ^ ^ | ^ ^ |
4922 | ||
# | Line 4894 RECURSIVE PATTERNS | Line 4996 RECURSIVE PATTERNS |
4996 | If you want to match typical palindromic phrases, the pattern has to | If you want to match typical palindromic phrases, the pattern has to |
4997 | ignore all non-word characters, which can be done like this: | ignore all non-word characters, which can be done like this: |
4998 | ||
4999 | ^\W*+(?:((.)\W*+(?1)\W*+\2|)|((.)\W*+(?3)\W*+4|\W*+.\W*+))\W*+$ | ^\W*+(?:((.)\W*+(?1)\W*+\2|)|((.)\W*+(?3)\W*+\4|\W*+.\W*+))\W*+$ |
5000 | ||
5001 | If run with the PCRE_CASELESS option, this pattern matches phrases such | If run with the PCRE_CASELESS option, this pattern matches phrases such |
5002 | as "A man, a plan, a canal: Panama!" and it works well in both PCRE and | as "A man, a plan, a canal: Panama!" and it works well in both PCRE and |
# | Line 4903 RECURSIVE PATTERNS | Line 5005 RECURSIVE PATTERNS |
5005 | great deal longer (ten times or more) to match typical phrases, and | great deal longer (ten times or more) to match typical phrases, and |
5006 | Perl takes so long that you think it has gone into a loop. | Perl takes so long that you think it has gone into a loop. |
5007 | ||
5008 | WARNING: The palindrome-matching patterns above work only if the sub- | |
5009 | ject string does not start with a palindrome that is shorter than the | |
5010 | entire string. For example, although "abcba" is correctly matched, if | |
5011 | the subject is "ababa", PCRE finds the palindrome "aba" at the start, | |
5012 | then fails at top level because the end of the string does not follow. | |
5013 | Once again, it cannot jump back into the recursion to try other alter- | |
5014 | natives, so the entire match fails. | |
5015 | ||
5016 | ||
5017 | SUBPATTERNS AS SUBROUTINES | SUBPATTERNS AS SUBROUTINES |
5018 | ||
# | Line 5034 BACKTRACKING CONTROL | Line 5144 BACKTRACKING CONTROL |
5144 | ||
5145 | This verb causes the match to end successfully, skipping the remainder | This verb causes the match to end successfully, skipping the remainder |
5146 | of the pattern. When inside a recursion, only the innermost pattern is | of the pattern. When inside a recursion, only the innermost pattern is |
5147 | ended immediately. If the (*ACCEPT) is inside capturing parentheses, | ended immediately. If (*ACCEPT) is inside capturing parentheses, the |
5148 | the data so far is captured. (This feature was added to PCRE at release | data so far is captured. (This feature was added to PCRE at release |
5149 | 8.00.) For example: | 8.00.) For example: |
5150 | ||
5151 | A((?:A|B(*ACCEPT)|C)D) | A((?:A|B(*ACCEPT)|C)D) |
# | Line 5068 BACKTRACKING CONTROL | Line 5178 BACKTRACKING CONTROL |
5178 | ||
5179 | This verb causes the whole match to fail outright if the rest of the | This verb causes the whole match to fail outright if the rest of the |
5180 | pattern does not match. Even if the pattern is unanchored, no further | pattern does not match. Even if the pattern is unanchored, no further |
5181 | attempts to find a match by advancing the start point take place. Once | attempts to find a match by advancing the starting point take place. |
5182 | (*COMMIT) has been passed, pcre_exec() is committed to finding a match | Once (*COMMIT) has been passed, pcre_exec() is committed to finding a |
5183 | at the current starting point, or not at all. For example: | match at the current starting point, or not at all. For example: |
5184 | ||
5185 | a+(*COMMIT)b | a+(*COMMIT)b |
5186 | ||
# | Line 5102 BACKTRACKING CONTROL | Line 5212 BACKTRACKING CONTROL |
5212 | If the subject is "aaaac...", after the first match attempt fails | If the subject is "aaaac...", after the first match attempt fails |
5213 | (starting at the first character in the string), the starting point | (starting at the first character in the string), the starting point |
5214 | skips on to start the next attempt at "c". Note that a possessive quan- | skips on to start the next attempt at "c". Note that a possessive quan- |
5215 | tifer does not have the same effect in this example; although it would | tifer does not have the same effect as this example; although it would |
5216 | suppress backtracking during the first match attempt, the second | suppress backtracking during the first match attempt, the second |
5217 | attempt would start at the second character instead of skipping on to | attempt would start at the second character instead of skipping on to |
5218 | "c". | "c". |
# | Line 5125 BACKTRACKING CONTROL | Line 5235 BACKTRACKING CONTROL |
5235 | ||
5236 | SEE ALSO | SEE ALSO |
5237 | ||
5238 | pcreapi(3), pcrecallout(3), pcrematching(3), pcre(3). | pcreapi(3), pcrecallout(3), pcrematching(3), pcresyntax(3), pcre(3). |
5239 | ||
5240 | ||
5241 | AUTHOR | AUTHOR |
# | Line 5137 AUTHOR | Line 5247 AUTHOR |
5247 | ||
5248 | REVISION | REVISION |
5249 | ||
5250 | Last updated: 22 September 2009 | Last updated: 04 October 2009 |
5251 | Copyright (c) 1997-2009 University of Cambridge. | Copyright (c) 1997-2009 University of Cambridge. |
5252 | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ |
5253 | ||
5254 | ||
5255 | PCRESYNTAX(3) PCRESYNTAX(3) | PCRESYNTAX(3) PCRESYNTAX(3) |
5256 | ||
5257 | ||
# | Line 5493 REVISION | Line 5603 REVISION |
5603 | Last updated: 11 April 2009 | Last updated: 11 April 2009 |
5604 | Copyright (c) 1997-2009 University of Cambridge. | Copyright (c) 1997-2009 University of Cambridge. |
5605 | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ |
5606 | ||
5607 | ||
5608 | PCREPARTIAL(3) PCREPARTIAL(3) | PCREPARTIAL(3) PCREPARTIAL(3) |
5609 | ||
5610 | ||
# | Line 5533 PARTIAL MATCHING IN PCRE | Line 5643 PARTIAL MATCHING IN PCRE |
5643 | plete match, though the details differ between the two matching func- | plete match, though the details differ between the two matching func- |
5644 | tions. If both options are set, PCRE_PARTIAL_HARD takes precedence. | tions. If both options are set, PCRE_PARTIAL_HARD takes precedence. |
5645 | ||
5646 | Setting a partial matching option disables one of PCRE's optimizations. | Setting a partial matching option disables two of PCRE's optimizations. |
5647 | PCRE remembers the last literal byte in a pattern, and abandons match- | PCRE remembers the last literal byte in a pattern, and abandons match- |
5648 | ing immediately if such a byte is not present in the subject string. | ing immediately if such a byte is not present in the subject string. |
5649 | This optimization cannot be used for a subject string that might match | This optimization cannot be used for a subject string that might match |
5650 | only partially. | only partially. If the pattern was studied, PCRE knows the minimum |
5651 | length of a matching string, and does not bother to run the matching | |
5652 | function on shorter strings. This optimization is also disabled for | |
5653 | partial matching. | |
5654 | ||
5655 | ||
5656 | PARTIAL MATCHING USING pcre_exec() | PARTIAL MATCHING USING pcre_exec() |
5657 | ||
5658 | A partial match occurs during a call to pcre_exec() whenever the end of | A partial match occurs during a call to pcre_exec() whenever the end of |
5659 | the subject string is reached successfully, but matching cannot con- | the subject string is reached successfully, but matching cannot con- |
5660 | tinue because more characters are needed. However, at least one charac- | tinue because more characters are needed. However, at least one charac- |
5661 | ter must have been matched. (In other words, a partial match can never | ter must have been matched. (In other words, a partial match can never |
5662 | be an empty string.) | be an empty string.) |
5663 | ||
5664 | If PCRE_PARTIAL_SOFT is set, the partial match is remembered, but | If PCRE_PARTIAL_SOFT is set, the partial match is remembered, but |
5665 | matching continues as normal, and other alternatives in the pattern are | matching continues as normal, and other alternatives in the pattern are |
5666 | tried. If no complete match can be found, pcre_exec() returns | tried. If no complete match can be found, pcre_exec() returns |
5667 | PCRE_ERROR_PARTIAL instead of PCRE_ERROR_NOMATCH. If there are at least | PCRE_ERROR_PARTIAL instead of PCRE_ERROR_NOMATCH. If there are at least |
5668 | two slots in the offsets vector, the first of them is set to the offset | two slots in the offsets vector, the first of them is set to the offset |
5669 | of the earliest character that was inspected when the partial match was | of the earliest character that was inspected when the partial match was |
5670 | found. For convenience, the second offset points to the end of the | found. For convenience, the second offset points to the end of the |
5671 | string so that a substring can easily be extracted. | string so that a substring can easily be identified. |
5672 | ||
5673 | For the majority of patterns, the first offset identifies the start of | For the majority of patterns, the first offset identifies the start of |
5674 | the partially matched string. However, for patterns that contain look- | the partially matched string. However, for patterns that contain look- |
5675 | behind assertions, or \K, or begin with \b or \B, earlier characters | behind assertions, or \K, or begin with \b or \B, earlier characters |
5676 | have been inspected while carrying out the match. For example: | have been inspected while carrying out the match. For example: |
5677 | ||
5678 | /(?<=abc)123/ | /(?<=abc)123/ |
5679 | ||
5680 | This pattern matches "123", but only if it is preceded by "abc". If the | This pattern matches "123", but only if it is preceded by "abc". If the |
5681 | subject string is "xyzabc12", the offsets after a partial match are for | subject string is "xyzabc12", the offsets after a partial match are for |
5682 | the substring "abc12", because all these characters are needed if | the substring "abc12", because all these characters are needed if |
5683 | another match is tried with extra characters added. | another match is tried with extra characters added. |
5684 | ||
5685 | If there is more than one partial match, the first one that was found | If there is more than one partial match, the first one that was found |
5686 | provides the data that is returned. Consider this pattern: | provides the data that is returned. Consider this pattern: |
5687 | ||
5688 | /123\w+X|dogY/ | /123\w+X|dogY/ |
5689 | ||
5690 | If this is matched against the subject string "abc123dog", both alter- | If this is matched against the subject string "abc123dog", both alter- |
5691 | natives fail to match, but the end of the subject is reached during | natives fail to match, but the end of the subject is reached during |
5692 | matching, so PCRE_ERROR_PARTIAL is returned instead of | matching, so PCRE_ERROR_PARTIAL is returned instead of |
5693 | PCRE_ERROR_NOMATCH. The offsets are set to 3 and 9, identifying | PCRE_ERROR_NOMATCH. The offsets are set to 3 and 9, identifying |
5694 | "123dog" as the first partial match that was found. (In this example, | "123dog" as the first partial match that was found. (In this example, |
5695 | there are two partial matches, because "dog" on its own partially | there are two partial matches, because "dog" on its own partially |
5696 | matches the second alternative.) | matches the second alternative.) |
5697 | ||
5698 | If PCRE_PARTIAL_HARD is set for pcre_exec(), it returns PCRE_ERROR_PAR- | If PCRE_PARTIAL_HARD is set for pcre_exec(), it returns PCRE_ERROR_PAR- |
5699 | TIAL as soon as a partial match is found, without continuing to search | TIAL as soon as a partial match is found, without continuing to search |
5700 | for possible complete matches. The difference between the two options | for possible complete matches. The difference between the two options |
5701 | can be illustrated by a pattern such as: | can be illustrated by a pattern such as: |
5702 | ||
5703 | /dog(sbody)?/ | /dog(sbody)?/ |
5704 | ||
5705 | This matches either "dog" or "dogsbody", greedily (that is, it prefers | This matches either "dog" or "dogsbody", greedily (that is, it prefers |
5706 | the longer string if possible). If it is matched against the string | the longer string if possible). If it is matched against the string |
5707 | "dog" with PCRE_PARTIAL_SOFT, it yields a complete match for "dog". | "dog" with PCRE_PARTIAL_SOFT, it yields a complete match for "dog". |
5708 | However, if PCRE_PARTIAL_HARD is set, the result is PCRE_ERROR_PARTIAL. | However, if PCRE_PARTIAL_HARD is set, the result is PCRE_ERROR_PARTIAL. |
5709 | On the other hand, if the pattern is made ungreedy the result is dif- | On the other hand, if the pattern is made ungreedy the result is dif- |
5710 | ferent: | ferent: |
5711 | ||
5712 | /dog(sbody)??/ | /dog(sbody)??/ |
5713 | ||
5714 | In this case the result is always a complete match because pcre_exec() | In this case the result is always a complete match because pcre_exec() |
5715 | finds that first, and it never continues after finding a match. It | finds that first, and it never continues after finding a match. It |
5716 | might be easier to follow this explanation by thinking of the two pat- | might be easier to follow this explanation by thinking of the two pat- |
5717 | terns like this: | terns like this: |
5718 | ||
5719 | /dog(sbody)?/ is the same as /dogsbody|dog/ | /dog(sbody)?/ is the same as /dogsbody|dog/ |
5720 | /dog(sbody)??/ is the same as /dog|dogsbody/ | /dog(sbody)??/ is the same as /dog|dogsbody/ |
5721 | ||
5722 | The second pattern will never match "dogsbody" when pcre_exec() is | The second pattern will never match "dogsbody" when pcre_exec() is |
5723 | used, because it will always find the shorter match first. | used, because it will always find the shorter match first. |
5724 | ||
5725 | ||
5726 | PARTIAL MATCHING USING pcre_dfa_exec() | PARTIAL MATCHING USING pcre_dfa_exec() |
5727 | ||
5728 | The pcre_dfa_exec() function moves along the subject string character | The pcre_dfa_exec() function moves along the subject string character |
5729 | by character, without backtracking, searching for all possible matches | by character, without backtracking, searching for all possible matches |
5730 | simultaneously. If the end of the subject is reached before the end of | simultaneously. If the end of the subject is reached before the end of |
5731 | the pattern, there is the possibility of a partial match, again pro- | the pattern, there is the possibility of a partial match, again pro- |
5732 | vided that at least one character has matched. | vided that at least one character has matched. |
5733 | ||
5734 | When PCRE_PARTIAL_SOFT is set, PCRE_ERROR_PARTIAL is returned only if | When PCRE_PARTIAL_SOFT is set, PCRE_ERROR_PARTIAL is returned only if |
5735 | there have been no complete matches. Otherwise, the complete matches | there have been no complete matches. Otherwise, the complete matches |
5736 | are returned. However, if PCRE_PARTIAL_HARD is set, a partial match | are returned. However, if PCRE_PARTIAL_HARD is set, a partial match |
5737 | takes precedence over any complete matches. The portion of the string | takes precedence over any complete matches. The portion of the string |
5738 | that was inspected when the longest partial match was found is set as | that was inspected when the longest partial match was found is set as |
5739 | the first matching string, provided there are at least two slots in the | the first matching string, provided there are at least two slots in the |
5740 | offsets vector. | offsets vector. |
5741 | ||
5742 | Because pcre_dfa_exec() always searches for all possible matches, and | Because pcre_dfa_exec() always searches for all possible matches, and |
5743 | there is no difference between greedy and ungreedy repetition, its be- | there is no difference between greedy and ungreedy repetition, its be- |
5744 | haviour is different from pcre_exec when PCRE_PARTIAL_HARD is set. Con- | haviour is different from pcre_exec when PCRE_PARTIAL_HARD is set. Con- |
5745 | sider the string "dog" matched against the ungreedy pattern shown | sider the string "dog" matched against the ungreedy pattern shown |
5746 | above: | above: |
5747 | ||
5748 | /dog(sbody)??/ | /dog(sbody)??/ |
5749 | ||
5750 | Whereas pcre_exec() stops as soon as it finds the complete match for | Whereas pcre_exec() stops as soon as it finds the complete match for |
5751 | "dog", pcre_dfa_exec() also finds the partial match for "dogsbody", and | "dog", pcre_dfa_exec() also finds the partial match for "dogsbody", and |
5752 | so returns that when PCRE_PARTIAL_HARD is set. | so returns that when PCRE_PARTIAL_HARD is set. |
5753 | ||
5754 | ||
5755 | PARTIAL MATCHING AND WORD BOUNDARIES | PARTIAL MATCHING AND WORD BOUNDARIES |
5756 | ||
5757 | If a pattern ends with one of sequences \w or \W, which test for word | If a pattern ends with one of sequences \w or \W, which test for word |
5758 | boundaries, partial matching with PCRE_PARTIAL_SOFT can give counter- | boundaries, partial matching with PCRE_PARTIAL_SOFT can give counter- |
5759 | intuitive results. Consider this pattern: | intuitive results. Consider this pattern: |
5760 | ||
5761 | /\bcat\b/ | /\bcat\b/ |
5762 | ||
5763 | This matches "cat", provided there is a word boundary at either end. If | This matches "cat", provided there is a word boundary at either end. If |
5764 | the subject string is "the cat", the comparison of the final "t" with a | the subject string is "the cat", the comparison of the final "t" with a |
5765 | following character cannot take place, so a partial match is found. | following character cannot take place, so a partial match is found. |
5766 | However, pcre_exec() carries on with normal matching, which matches \b | However, pcre_exec() carries on with normal matching, which matches \b |
5767 | at the end of the subject when the last character is a letter, thus | at the end of the subject when the last character is a letter, thus |
5768 | finding a complete match. The result, therefore, is not PCRE_ERROR_PAR- | finding a complete match. The result, therefore, is not PCRE_ERROR_PAR- |
5769 | TIAL. The same thing happens with pcre_dfa_exec(), because it also | TIAL. The same thing happens with pcre_dfa_exec(), because it also |
5770 | finds the complete match. | finds the complete match. |
5771 | ||
5772 | Using PCRE_PARTIAL_HARD in this case does yield PCRE_ERROR_PARTIAL, | Using PCRE_PARTIAL_HARD in this case does yield PCRE_ERROR_PARTIAL, |
5773 | because then the partial match takes precedence. | because then the partial match takes precedence. |
5774 | ||
5775 | ||
5776 | FORMERLY RESTRICTED PATTERNS | FORMERLY RESTRICTED PATTERNS |
5777 | ||
5778 | For releases of PCRE prior to 8.00, because of the way certain internal | For releases of PCRE prior to 8.00, because of the way certain internal |
5779 | optimizations were implemented in the pcre_exec() function, the | optimizations were implemented in the pcre_exec() function, the |
5780 | PCRE_PARTIAL option (predecessor of PCRE_PARTIAL_SOFT) could not be | PCRE_PARTIAL option (predecessor of PCRE_PARTIAL_SOFT) could not be |
5781 | used with all patterns. From release 8.00 onwards, the restrictions no | used with all patterns. From release 8.00 onwards, the restrictions no |
5782 | longer apply, and partial matching with pcre_exec() can be requested | longer apply, and partial matching with pcre_exec() can be requested |
5783 | for any pattern. | for any pattern. |
5784 | ||
5785 | Items that were formerly restricted were repeated single characters and | Items that were formerly restricted were repeated single characters and |
5786 | repeated metasequences. If PCRE_PARTIAL was set for a pattern that did | repeated metasequences. If PCRE_PARTIAL was set for a pattern that did |
5787 | not conform to the restrictions, pcre_exec() returned the error code | not conform to the restrictions, pcre_exec() returned the error code |
5788 | PCRE_ERROR_BADPARTIAL (-13). This error code is no longer in use. The | PCRE_ERROR_BADPARTIAL (-13). This error code is no longer in use. The |
5789 | PCRE_INFO_OKPARTIAL call to pcre_fullinfo() to find out if a compiled | PCRE_INFO_OKPARTIAL call to pcre_fullinfo() to find out if a compiled |
5790 | pattern can be used for partial matching now always returns 1. | pattern can be used for partial matching now always returns 1. |
5791 | ||
5792 | ||
5793 | EXAMPLE OF PARTIAL MATCHING USING PCRETEST | EXAMPLE OF PARTIAL MATCHING USING PCRETEST |
5794 | ||
5795 | If the escape sequence \P is present in a pcretest data line, the | If the escape sequence \P is present in a pcretest data line, the |
5796 | PCRE_PARTIAL_SOFT option is used for the match. Here is a run of | PCRE_PARTIAL_SOFT option is used for the match. Here is a run of |
5797 | pcretest that uses the date example quoted above: | pcretest that uses the date example quoted above: |
5798 | ||
5799 | re> /^\d?\d(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d\d$/ | re> /^\d?\d(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d\d$/ |
# | Line 5696 EXAMPLE OF PARTIAL MATCHING USING PCRETE | Line 5809 EXAMPLE OF PARTIAL MATCHING USING PCRETE |
5809 | data> j\P | data> j\P |
5810 | No match | No match |
5811 | ||
5812 | The first data string is matched completely, so pcretest shows the | The first data string is matched completely, so pcretest shows the |
5813 | matched substrings. The remaining four strings do not match the com- | matched substrings. The remaining four strings do not match the com- |
5814 | plete pattern, but the first two are partial matches. Similar output is | plete pattern, but the first two are partial matches. Similar output is |
5815 | obtained when pcre_dfa_exec() is used. | obtained when pcre_dfa_exec() is used. |
5816 | ||
5817 | If the escape sequence \P is present more than once in a pcretest data | If the escape sequence \P is present more than once in a pcretest data |
5818 | line, the PCRE_PARTIAL_HARD option is set for the match. | line, the PCRE_PARTIAL_HARD option is set for the match. |
5819 | ||
5820 | ||
5821 | MULTI-SEGMENT MATCHING WITH pcre_dfa_exec() | MULTI-SEGMENT MATCHING WITH pcre_dfa_exec() |
5822 | ||
5823 | When a partial match has been found using pcre_dfa_exec(), it is possi- | When a partial match has been found using pcre_dfa_exec(), it is possi- |
5824 | ble to continue the match by providing additional subject data and | ble to continue the match by providing additional subject data and |
5825 | calling pcre_dfa_exec() again with the same compiled regular expres- | calling pcre_dfa_exec() again with the same compiled regular expres- |
5826 | sion, this time setting the PCRE_DFA_RESTART option. You must pass the | sion, this time setting the PCRE_DFA_RESTART option. You must pass the |
5827 | same working space as before, because this is where details of the pre- | same working space as before, because this is where details of the pre- |
5828 | vious partial match are stored. Here is an example using pcretest, | vious partial match are stored. Here is an example using pcretest, |
5829 | using the \R escape sequence to set the PCRE_DFA_RESTART option (\D | using the \R escape sequence to set the PCRE_DFA_RESTART option (\D |
5830 | specifies the use of pcre_dfa_exec()): | specifies the use of pcre_dfa_exec()): |
5831 | ||
5832 | re> /^\d?\d(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d\d$/ | re> /^\d?\d(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d\d$/ |
# | Line 5722 MULTI-SEGMENT MATCHING WITH pcre_dfa_exe | Line 5835 MULTI-SEGMENT MATCHING WITH pcre_dfa_exe |
5835 | data> n05\R\D | data> n05\R\D |
5836 | 0: n05 | 0: n05 |
5837 | ||
5838 | The first call has "23ja" as the subject, and requests partial match- | The first call has "23ja" as the subject, and requests partial match- |
5839 | ing; the second call has "n05" as the subject for the continued | ing; the second call has "n05" as the subject for the continued |
5840 | (restarted) match. Notice that when the match is complete, only the | (restarted) match. Notice that when the match is complete, only the |
5841 | last part is shown; PCRE does not retain the previously partially- | last part is shown; PCRE does not retain the previously partially- |
5842 | matched string. It is up to the calling program to do that if it needs | matched string. It is up to the calling program to do that if it needs |
5843 | to. | to. |
5844 | ||
5845 | You can set the PCRE_PARTIAL_SOFT or PCRE_PARTIAL_HARD options with | You can set the PCRE_PARTIAL_SOFT or PCRE_PARTIAL_HARD options with |
5846 | PCRE_DFA_RESTART to continue partial matching over multiple segments. | PCRE_DFA_RESTART to continue partial matching over multiple segments. |
5847 | This facility can be used to pass very long subject strings to | This facility can be used to pass very long subject strings to |
5848 | pcre_dfa_exec(). | pcre_dfa_exec(). |
5849 | ||
5850 | ||
5851 | MULTI-SEGMENT MATCHING WITH pcre_exec() | MULTI-SEGMENT MATCHING WITH pcre_exec() |
5852 | ||
5853 | From release 8.00, pcre_exec() can also be used to do multi-segment | From release 8.00, pcre_exec() can also be used to do multi-segment |
5854 | matching. Unlike pcre_dfa_exec(), it is not possible to restart the | matching. Unlike pcre_dfa_exec(), it is not possible to restart the |
5855 | previous match with a new segment of data. Instead, new data must be | previous match with a new segment of data. Instead, new data must be |
5856 | added to the previous subject string, and the entire match re-run, | added to the previous subject string, and the entire match re-run, |
5857 | starting from the point where the partial match occurred. Earlier data | starting from the point where the partial match occurred. Earlier data |
5858 | can be discarded. Consider an unanchored pattern that matches dates: | can be discarded. Consider an unanchored pattern that matches dates: |
5859 | ||
5860 | re> /\d?\d(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d\d/ | re> /\d?\d(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d\d/ |
# | Line 5749 MULTI-SEGMENT MATCHING WITH pcre_exec() | Line 5862 MULTI-SEGMENT MATCHING WITH pcre_exec() |
5862 | Partial match: 23ja | Partial match: 23ja |
5863 | ||
5864 | The this stage, an application could discard the text preceding "23ja", | The this stage, an application could discard the text preceding "23ja", |
5865 | add on text from the next segment, and call pcre_exec() again. Unlike | add on text from the next segment, and call pcre_exec() again. Unlike |
5866 | pcre_dfa_exec(), the entire matching string must always be available, | pcre_dfa_exec(), the entire matching string must always be available, |
5867 | and the complete matching process occurs for each call, so more memory | and the complete matching process occurs for each call, so more memory |
5868 | and more processing time is needed. | and more processing time is needed. |
5869 | ||
5870 | Note: If the pattern contains lookbehind assertions, or \K, or starts | Note: If the pattern contains lookbehind assertions, or \K, or starts |
5871 | with \b or \B, the string that is returned for a partial match will | with \b or \B, the string that is returned for a partial match will |
5872 | include characters that precede the partially matched string itself, | include characters that precede the partially matched string itself, |
5873 | because these must be retained when adding on more characters for a | because these must be retained when adding on more characters for a |
5874 | subsequent matching attempt. | subsequent matching attempt. |
5875 | ||
5876 | ||
# | Line 5766 ISSUES WITH MULTI-SEGMENT MATCHING | Line 5879 ISSUES WITH MULTI-SEGMENT MATCHING |
5879 | Certain types of pattern may give problems with multi-segment matching, | Certain types of pattern may give problems with multi-segment matching, |
5880 | whichever matching function is used. | whichever matching function is used. |
5881 | ||
5882 | 1. If the pattern contains tests for the beginning or end of a line, | 1. If the pattern contains tests for the beginning or end of a line, |
5883 | you need to pass the PCRE_NOTBOL or PCRE_NOTEOL options, as appropri- | you need to pass the PCRE_NOTBOL or PCRE_NOTEOL options, as appropri- |
5884 | ate, when the subject string for any call does not contain the begin- | ate, when the subject string for any call does not contain the begin- |
5885 | ning or end of a line. | ning or end of a line. |
5886 | ||
5887 | 2. Lookbehind assertions at the start of a pattern are catered for in | 2. Lookbehind assertions at the start of a pattern are catered for in |
5888 | the offsets that are returned for a partial match. However, in theory, | the offsets that are returned for a partial match. However, in theory, |
5889 | a lookbehind assertion later in the pattern could require even earlier | a lookbehind assertion later in the pattern could require even earlier |
5890 | characters to be inspected, and it might not have been reached when a | characters to be inspected, and it might not have been reached when a |
5891 | partial match occurs. This is probably an extremely unlikely case; you | partial match occurs. This is probably an extremely unlikely case; you |
5892 | could guard against it to a certain extent by always including extra | could guard against it to a certain extent by always including extra |
5893 | characters at the start. | characters at the start. |
5894 | ||
5895 | 3. Matching a subject string that is split into multiple segments may | 3. Matching a subject string that is split into multiple segments may |
5896 | not always produce exactly the same result as matching over one single | not always produce exactly the same result as matching over one single |
5897 | long string, especially when PCRE_PARTIAL_SOFT is used. The section | long string, especially when PCRE_PARTIAL_SOFT is used. The section |
5898 | "Partial Matching and Word Boundaries" above describes an issue that | "Partial Matching and Word Boundaries" above describes an issue that |
5899 | arises if the pattern ends with \b or \B. Another kind of difference | arises if the pattern ends with \b or \B. Another kind of difference |
5900 | may occur when there are multiple matching possibilities, because a | may occur when there are multiple matching possibilities, because a |
5901 | partial match result is given only when there are no completed matches. | partial match result is given only when there are no completed matches. |
5902 | This means that as soon as the shortest match has been found, continua- | This means that as soon as the shortest match has been found, continua- |
5903 | tion to a new subject segment is no longer possible. Consider again | tion to a new subject segment is no longer possible. Consider again |
5904 | this pcretest example: | this pcretest example: |
5905 | ||
5906 | re> /dog(sbody)?/ | re> /dog(sbody)?/ |
# | Line 5801 ISSUES WITH MULTI-SEGMENT MATCHING | Line 5914 ISSUES WITH MULTI-SEGMENT MATCHING |
5914 | 0: dogsbody | 0: dogsbody |
5915 | 1: dog | 1: dog |
5916 | ||
5917 | The first data line passes the string "dogsb" to pcre_exec(), setting | The first data line passes the string "dogsb" to pcre_exec(), setting |
5918 | the PCRE_PARTIAL_SOFT option. Although the string is a partial match | the PCRE_PARTIAL_SOFT option. Although the string is a partial match |
5919 | for "dogsbody", the result is not PCRE_ERROR_PARTIAL, because the | for "dogsbody", the result is not PCRE_ERROR_PARTIAL, because the |
5920 | shorter string "dog" is a complete match. Similarly, when the subject | shorter string "dog" is a complete match. Similarly, when the subject |
5921 | is presented to pcre_dfa_exec() in several parts ("do" and "gsb" being | is presented to pcre_dfa_exec() in several parts ("do" and "gsb" being |
5922 | the first two) the match stops when "dog" has been found, and it is not | the first two) the match stops when "dog" has been found, and it is not |
5923 | possible to continue. On the other hand, if "dogsbody" is presented as | possible to continue. On the other hand, if "dogsbody" is presented as |
5924 | a single string, pcre_dfa_exec() finds both matches. | a single string, pcre_dfa_exec() finds both matches. |
5925 | ||
5926 | Because of these problems, it is probably best to use PCRE_PARTIAL_HARD | Because of these problems, it is probably best to use PCRE_PARTIAL_HARD |
5927 | when matching multi-segment data. The example above then behaves dif- | when matching multi-segment data. The example above then behaves dif- |
5928 | ferently: | ferently: |
5929 | ||
5930 | re> /dog(sbody)?/ | re> /dog(sbody)?/ |
# | Line 5824 ISSUES WITH MULTI-SEGMENT MATCHING | Line 5937 ISSUES WITH MULTI-SEGMENT MATCHING |
5937 | ||
5938 | ||
5939 | 4. Patterns that contain alternatives at the top level which do not all | 4. Patterns that contain alternatives at the top level which do not all |
5940 | start with the same pattern item may not work as expected when | start with the same pattern item may not work as expected when |
5941 | pcre_dfa_exec() is used. For example, consider this pattern: | pcre_dfa_exec() is used. For example, consider this pattern: |
5942 | ||
5943 | 1234|3789 | 1234|3789 |
5944 | ||
5945 | If the first part of the subject is "ABC123", a partial match of the | If the first part of the subject is "ABC123", a partial match of the |
5946 | first alternative is found at offset 3. There is no partial match for | first alternative is found at offset 3. There is no partial match for |
5947 | the second alternative, because such a match does not start at the same | the second alternative, because such a match does not start at the same |
5948 | point in the subject string. Attempting to continue with the string | point in the subject string. Attempting to continue with the string |
5949 | "7890" does not yield a match because only those alternatives that | "7890" does not yield a match because only those alternatives that |
5950 | match at one point in the subject are remembered. The problem arises | match at one point in the subject are remembered. The problem arises |
5951 | because the start of the second alternative matches within the first | because the start of the second alternative matches within the first |
5952 | alternative. There is no problem with anchored patterns or patterns | alternative. There is no problem with anchored patterns or patterns |
5953 | such as: | such as: |
5954 | ||
5955 | 1234|ABCD | 1234|ABCD |
5956 | ||
5957 | where no string can be a partial match for both alternatives. This is | where no string can be a partial match for both alternatives. This is |
5958 | not a problem if pcre_exec() is used, because the entire match has to | not a problem if pcre_exec() is used, because the entire match has to |
5959 | be rerun each time: | be rerun each time: |
5960 | ||
5961 | re> /1234|3789/ | re> /1234|3789/ |
# | Line 5861 AUTHOR | Line 5974 AUTHOR |
5974 | ||
5975 | REVISION | REVISION |
5976 | ||
5977 | Last updated: 05 September 2009 | Last updated: 29 September 2009 |
5978 | Copyright (c) 1997-2009 University of Cambridge. | Copyright (c) 1997-2009 University of Cambridge. |
5979 | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ |
5980 | ||
5981 | ||
5982 | PCREPRECOMPILE(3) PCREPRECOMPILE(3) | PCREPRECOMPILE(3) PCREPRECOMPILE(3) |
5983 | ||
5984 | ||
# | Line 5988 REVISION | Line 6101 REVISION |
6101 | Last updated: 13 June 2007 | Last updated: 13 June 2007 |
6102 | Copyright (c) 1997-2007 University of Cambridge. | Copyright (c) 1997-2007 University of Cambridge. |
6103 | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ |
6104 | ||
6105 | ||
6106 | PCREPERFORM(3) PCREPERFORM(3) | PCREPERFORM(3) PCREPERFORM(3) |
6107 | ||
6108 | ||
# | Line 6138 REVISION | Line 6251 REVISION |
6251 | Last updated: 06 March 2007 | Last updated: 06 March 2007 |
6252 | Copyright (c) 1997-2007 University of Cambridge. | Copyright (c) 1997-2007 University of Cambridge. |
6253 | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ |
6254 | ||
6255 | ||
6256 | PCREPOSIX(3) PCREPOSIX(3) | PCREPOSIX(3) PCREPOSIX(3) |
6257 | ||
6258 | ||
# | Line 6394 REVISION | Line 6507 REVISION |
6507 | Last updated: 02 September 2009 | Last updated: 02 September 2009 |
6508 | Copyright (c) 1997-2009 University of Cambridge. | Copyright (c) 1997-2009 University of Cambridge. |
6509 | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ |
6510 | ||
6511 | ||
6512 | PCRECPP(3) PCRECPP(3) | PCRECPP(3) PCRECPP(3) |
6513 | ||
6514 | ||
# | Line 6735 REVISION | Line 6848 REVISION |
6848 | ||
6849 | Last updated: 17 March 2009 | Last updated: 17 March 2009 |
6850 | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ |
6851 | ||
6852 | ||
6853 | PCRESAMPLE(3) PCRESAMPLE(3) | PCRESAMPLE(3) PCRESAMPLE(3) |
6854 | ||
6855 | ||
# | Line 6765 PCRE SAMPLE PROGRAM | Line 6878 PCRE SAMPLE PROGRAM |
6878 | is going on. | is going on. |
6879 | ||
6880 | If PCRE is installed in the standard include and library directories | If PCRE is installed in the standard include and library directories |
6881 | for your system, you should be able to compile the demonstration pro- | for your operating system, you should be able to compile the demonstra- |
6882 | gram using this command: | tion program using this command: |
6883 | ||
6884 | gcc -o pcredemo pcredemo.c -lpcre | gcc -o pcredemo pcredemo.c -lpcre |
6885 | ||
# | Line 6813 AUTHOR | Line 6926 AUTHOR |
6926 | ||
6927 | REVISION | REVISION |
6928 | ||
6929 | Last updated: 01 September 2009 | Last updated: 30 September 2009 |
6930 | Copyright (c) 1997-2009 University of Cambridge. | Copyright (c) 1997-2009 University of Cambridge. |
6931 | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ |
6932 | PCRESTACK(3) PCRESTACK(3) | PCRESTACK(3) PCRESTACK(3) |
# | Line 6952 REVISION | Line 7065 REVISION |
7065 | Last updated: 09 July 2008 | Last updated: 09 July 2008 |