PCRE Perl Compatible Regular Expressions Learning

时间:2022-12-15 23:28:00

catalog

. PCRE Introduction
. pcre2api
. pcre2jit
. PCRE Programing

1. PCRE Introduction

The PCRE library is a set of functions that implement regular expression pattern matching using the same syntax and semantics as Perl 5. PCRE has its own native API, as well as a set of wrapper functions that correspond to the POSIX regular expression API. The PCRE library is free, even for building proprietary software.
PCRE was originally written for the Exim MTA, but is now used by many high-profile open source projects, including

. Apache
. PHP
. KDE
. Postfix
. Analog
. Nmap
//PCRE has also found its way into some well known commercial products
. Apple Safari
//Some other interesting projects using PCRE include
. Chicken
. Ferite
. Onyx
. Hypermail
. Leafnode
. Askemos
. Wenlin
. 8th

Perl Compatible Regular Expressions (PCRE) is a regular expression C library inspired by the regular expression capabilities in the Perl programming language, written by Philip Hazel, starting in summer 1997.PCRE's syntax is much more powerful and flexible than either of the POSIX regular expression flavors and many classic regular expression libraries. The name is misleading, because PCRE and Perl each have capabilities not shared by the other.

0x1: Features

PCRE has developed an extensive and in some ways unique feature set. While it originally aimed at feature-equivalence with Perl, over time a number of features have been first implemented in PCRE and only much later added to Perl. During the PCRE 7.x and Perl 5.9.x (development track) phase the two projects have coordinated development and are to the extent possible feature equivalent. In some cases PCRE has included in mainline releases features that originated with Perl 5.9.x and in some cases Perl 5.9.x has included features that were previously only available in PCRE.
PCRE includes the following features:

. Just-in-time compiler support
This optional feature is available in version 8.20 and above if enabled when the PCRE library is built. Large performance benefits are possible when (for example) the calling program utilizes the feature with compatible patterns that are executed repeatedly. The just-in-time compiler support was written by Zoltan Herczeg and is not addressed in the POSIX or C++ wrappers. . Consistent escaping rules
Like Perl, PCRE has consistent escaping rules: any non-alpha-numeric character may be escaped to mean its literal value by prefixing a \ (backslash) before the character, and vice versa, any alpha-numeric character preceded by a backslash typically gives it a special meaning. In the case where the sequence has not been defined to be special it will also be treated as a literal, however this usage is not forward compatible as new versions of PCRE may give such patterns a special meaning. A good example of this is \R, which had no special meaning prior to PCRE . In POSIX regular expressions, sometimes backslashes escaped non-alpha-numerics (e.g. \.) and sometimes they introduced a special feature (e.g. \(\)). . Extended character classes
Single-letter character classes are supported in addition to the longer POSIX names. For example \d matches any digit exactly as [[:digit:]] would in POSIX regular expressions. . Minimal matching (a.k.a. "ungreedy")
A ? may be placed after any repetition quantifier to indicate that the shortest match should be used. The default is to attempt the longest match first, and backtrack through shorter matches. e.g. "a.*?b" would match "ab" in "ababab", where "a.*b" would match the entire string. . Unicode character properties
Unicode defines several properties for each character. Patterns in PCRE can match these properties. e.g. \p{Ps}.*?\p{Pe} would match a string beginning with any "opening punctuation" and ending with any "close punctuation" such as "[abc]". Since version 8.10, matching of certain "normal" metacharacters can be driven by Unicode properties when the compile option PCRE_UCP is set. The option can be set for a pattern by including (*UCP) at the start of pattern. The option alters behavior of the following metacharacters: \B, \b, \D, \d, \S, \s, \W, \w, and some of the POSIX character classes. For example, the set of characters matched by \w (word characters) is expanded to include letters and accented letters as defined by Unicode properties. Such matching is slower than the normal (ASCII-only) non-UCP alternative. Note that the UCP option requires the PCRE library to have been built to include UTF- and Unicode property support. Support for UTF- is included in version 8.30 while support for UTF- was added in version 8.32. . Multiline matching
^ and $ can match at the beginning and end of a string only, or at the start and end of each "line" within the string depending on what options are set. . Newline/linebreak options
When PCRE is compiled, a newline default is selected. Which newline/linebreak is in effect affects where PCRE detects ^-line beginnings and $-ends (in multiline mode) as well as what matches dot (regardless of multiline mode unless the dotall (?s) option is set). It also affects PCRE's matching procedure (since version 7.0): when an unanchored pattern fails to match at the start of a newline sequence, PCRE advances past the entire newline sequence before retrying the match. If the newline option alternative in effect includes CRLF as one of the valid linebreaks, it does not skip the \n in a CRLF if the pattern contains specific \r or \n references (since version 7.3). Since version 8.10, the metacharacter \N always matches any character other than linebreak characters. It has the same behavior as "." when the dotall option aka "(?s)" is not in effect.
The newline option can be altered with external options when a pattern is compiled as well as when it is run. Few application using PCRE provide users with the means to apply this setting via an external option. So, new in version 7.3, the newline option can also be stated at the start of the pattern using one of the following:
) (*LF) Newline is a linefeed character. Corresponding linebreaks can be matched with \n.
) (*CR) Newline is a carriage return. Corresponding linebreaks can be matched with \r.
) (*CRLF) Newline/linebreak is a carriage return followed by a linefeed. Corresponding linebreaks can be matched with \r\n.
) (*ANYCRLF) Any of the above encountered in the data will trigger newline processing. Corresponding linebreaks can be matched with (?>\r\n|[\r\n]) or with \R. See below for configuration and options concerning what matches Backslash-R.
) (*ANY) Any of the above plus special Unicode linebreaks. When not in UTF- mode, corresponding linebreaks can be matched with (?>\r\n|\n|\x0b|\f|\r|\x85) or \R. In UTF- mode, two additional characters are recognized as line breaks with (*ANY): LS (line separator, U+), and PS (paragraph separator, U+). On Windows, in non-Unicode data, some of the ANY linebreak characters have other meanings. For example, \x85 can match a horizontal ellipsis, and if encountered while the ANY newline is in effect, it would trigger newline processing. See below for configuration and options concerning what matches Backslash-R. . Backslash-R options
New in version 7.4: When PCRE is compiled, a default is selected for what matches \R. The default can be either to match the linebreaks associated ANYCRLF or those corresponding to ANY. The default can be overridden when necessary by including (*BSR_UNICODE) or (*BSR_ANYCRLF) at the start of the pattern. When providing a (*BSR..) option, you can also provide a (*newline) option, e.g., (*BSR_UNICODE)(*ANY)rest-of-pattern. The Backslash-R options also can be changed with external options by the application calling PCRE, when a pattern is compiled as well as when it is run. . Beginning of pattern options
Linebreak options such as (*LF) documented above; Backslash-R options such as (*BSR_ANYCRLF) documented above; Unicode Character Properties option (*UCP) documented above; and, (*UTF8) option documented as follows: Since version 7.9, if your PCRE library has been compiled with UTF- support, you can specify the (*UTF8) option at the beginning of a pattern instead of setting an external option to invoke UTF- mode. . Named subpatterns
A sub-pattern (surrounded by parentheses, like (...)) may be named by including a leading "?P<name>" after the open-paren. Named subpatterns are a feature that PCRE adopted from Python regular expressions. Since PCRE 7.0, named groups can be defined using (?<name>...) or (?'name'...) as well as (?P<name>...). Named groups can then be invoked with, for example, (?P=name.). . Backreferences
A pattern may refer back to the results of a previous match. For example, (a|b)c\ would match "a" or "b" followed by a "c". Then it would look for the same character (an "a" or a "b") that matched in the first subpattern. . Subroutines
While a backreference provides a mechanism to refer to that part of the subject that has previously matched a subpattern, a subroutine provides a mechanism to reuse an underlying previously defined subpattern. The subpattern's options, such as case independence, are fixed when the subpattern is defined. (a.c)(?1) would match aacabc or abcadc, whereas using a backreference (a.c)\1 would not, though both would match aacaac or abcabc. Starting with version 7.7 PCRE also supports a non-Perl Oniguruma construct for subroutines. They are specified using \g<subpat-number> or \g<subpat-name>. . Atomic grouping
Atomic grouping is a way of preventing backtracking in a pattern. For example, a++bc will match as many "a"s as possible, and never back up to try one less. . Look-ahead and look-behind assertions
Patterns may assert that previous text or subsequent text contains a pattern without consuming matched text (zero-width assertion). For example, /\w+(?=\t)/ matches a word followed by a tab, without including the tab.
Look-behind assertions cannot be of uncertain length.
Since version 7.2, \K can be used in a pattern to reset the start of the current whole match. This provides a flexible alternative approach to look-behind assertions because the discarded part of the match (the part that precedes \K) need not be fixed in length. . Escape sequences for zero-width assertions
E.g. \b for matching zero-width "word boundaries", similar to (?<=\W)(?=\w)|(?<=\w)(?=\W). . Comments
A comment begins with (?# and ends at the next closing parenthesis. . Recursive patterns
A pattern can refer back to itself recursively or to any subpattern. For example, the pattern "\((a*|(?R))*\)" will match any combination of balanced parentheses and "a"s. . Generic callouts
PCRE expressions can embed "(?Cn)" where n is some number. This will call out to an external, user-defined function through the PCRE API, and can be used to embed arbitrary code in a pattern.

0x2: Differences from Perl

PCRE's specification has the following differences to Perl's regular expression

. Recursive matches are atomic in PCRE and non atomic in Perl
This means that "<<!>!>!>><>>!>!>!>" =~ /^(<(?:[^<>]+|(?)|(?))*>)()(!>!>!>)$/ will match in Perl but not in PCRE. . The value of a capture buffer deriving from the ? quantifier (match or times) when nested in another quantified capture buffer is different
"aba" =~ /^(a(b)?)+$/; will result in $ containing 'a' and $ containing undef in Perl, but in PCRE will result in $ containing 'b'. . PCRE allows named capture buffers to be given numeric names; Perl requires the name to follow the rule of barewords
This means that \g{} is unambiguous in Perl, but potentially ambiguous in PCRE. . PCRE does not support certain "experimental" Perl constructs
such as (??{...}) (a callback whose return is evaluated as being part of the pattern) nor the (?{}) construct, although the latter can be emulated using (?Cn). Recursion control verbs added in the Perl 5.9.x series are also not supported. Support for experimental backtracking control verbs (added in Perl 5.10) is available in PCRE since version 7.3. They are (*FAIL), (*F), (*PRUNE), (*SKIP), (*THEN), (*COMMIT), and (*ACCEPT). Perl's corresponding use of arguments with backtracking control verbs is not generally supported. Note however that since version 8.10, PCRE supports the following verbs with a specified argument: (*MARK:markName), (*SKIP:markName), (*PRUNE:markName), and (*THEN:markName). . PCRE and Perl are slightly different in their tolerance of erroneous constructs
Perl allows quantifiers on the (?!) construct, which is meaningless but harmless (albeit inefficient); PCRE produces an error. (Note that such assertions can be harmlessly quantified with PCRE beginning with version 8.13, so the cited example applies only to earlier versions.) . PCRE has a hard limit on recursion depth, Perl does not
With default build options "bbbbXcXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" =~ /.X(.+)+X/ will fail to match due to stack overflow, but Perl will match this correctly. Perl uses the heap for recursion and has no hard limit for recursion depth, whereas PCRE has a compile time hard limit.
With the exception of the above points PCRE is capable of passing the tests in the Perl 't/op/re_tests' file, one of the main syntax level regression tests for Perl's regular expression engine.

Relevant Link:

http://www.pcre.org/
http://en.wikipedia.org/wiki/Perl_Compatible_Regular_Expressions
http://www.pcre.org/current/doc/html/

2. pcre2api

Relevant Link:

http://www.pcre.org/current/doc/html/pcre2api.html

3. pcre2jit

Just-in-time compiling is a heavyweight optimization that can greatly speed up pattern matching. However, it comes at the cost of extra processing before the match is performed, so it is of most benefit when the same pattern is going to be matched many times. This does not necessarily mean many calls of a matching function; if the pattern is not anchored, matching attempts may take place many times at various positions in the subject, even for a single call. Therefore, if the subject string is very long, it may still pay to use JIT even for one-off matches. JIT support is available for all of the 8-bit, 16-bit and 32-bit PCRE2 libraries.

0x1: AVAILABILITY OF JIT SUPPORT

JIT support is an optional feature of PCRE2. The "configure" option --enable-jit (or equivalent CMake option) must be set when PCRE2 is built if you want to use JIT. The support is limited to the following hardware platforms:

. ARM -bit (v5, v7, and Thumb2)
. ARM -bit
. Intel x86 -bit and -bit
. MIPS -bit and -bit
. Power PC -bit and -bit
. SPARC -bit

0x2: SIMPLE USE OF JIT

To make use of the JIT support in the simplest way, all you have to do is to

. call pcre2_compile()
. call pcre2_jit_compile() after successfully compiling a pattern with pcre2_compile().
//This function has two arguments: the first is the compiled pattern pointer that was returned by pcre2_compile(), and the second is zero or more of the following option bits: PCRE2_JIT_COMPLETE, PCRE2_JIT_PARTIAL_HARD, or PCRE2_JIT_PARTIAL_SOFT.

Relevant Link:

http://www.pcre.org/current/doc/html/pcre2jit.html
http://www.pcre.org/current/doc/html/pcre2jit.htm

3. PCRE Programing

0x1: PHP PERC

我们知道,PCRE是一款代码库,它需要被编译到一个程序中之后,才能在程序中使用PCRE相关的API,PHP默认在编译的时候已经将PCRE编译进去了,因此我们在PHP中可以直接使用PCRE的相关API

<?php
/* 模式中的\b标记一个单词边界,所以只有独立的单词"web"会被匹配,而不会匹配单词的部分内容比如"webbing" 或 "cobweb" */
if (preg_match("/\bweb\b/i", "PHP is the web scripting language of choice."))
{
echo "A match was found.";
}
else
{
echo "A match was not found.";
} if (preg_match("/\bweb\b/i", "PHP is the website scripting language of choice."))
{
echo "A match was found.";
}
else
{
echo "A match was not found.";
}
?>

0x2: C PCRE

/*************************************************
* PCRE2 DEMONSTRATION PROGRAM *
*************************************************/ /* This is a demonstration program to illustrate a straightforward way of
calling the PCRE2 regular expression library from a C program. See the
pcre2sample documentation for a short discussion ("man pcre2sample" if you have
the PCRE2 man pages installed). PCRE2 is a revised API for the library, and is
incompatible with the original PCRE API. There are actually three libraries, each supporting a different code unit
width. This demonstration program uses the 8-bit library. In Unix-like environments, if PCRE2 is installed in your standard system
libraries, you should be able to compile this program using this command: gcc -Wall pcre2demo.c -lpcre2-8 -o pcre2demo If PCRE2 is not installed in a standard place, it is likely to be installed
with support for the pkg-config mechanism. If you have pkg-config, you can
compile this program using this command: gcc -Wall pcre2demo.c `pkg-config --cflags --libs libpcre2-8` -o pcre2demo If you do not have pkg-config, you may have to use this: gcc -Wall pcre2demo.c -I/usr/local/include -L/usr/local/lib \
-R/usr/local/lib -lpcre2-8 -o pcre2demo Replace "/usr/local/include" and "/usr/local/lib" with wherever the include and
library files for PCRE2 are installed on your system. Only some operating
systems (Solaris is one) use the -R option. Building under Windows: If you want to statically link this program against a non-dll .a file, you must
define PCRE2_STATIC before including pcre2.h, so in this environment, uncomment
the following line. */ /* #define PCRE2_STATIC */ /* This macro must be defined before including pcre2.h. For a program that uses
only one code unit width, it makes it possible to use generic function names
such as pcre2_compile(). */ #define PCRE2_CODE_UNIT_WIDTH 8 #include <stdio.h>
#include <string.h>
#include <pcre2.h> /**************************************************************************
* Here is the program. The API includes the concept of "contexts" for *
* setting up unusual interface requirements for compiling and matching, *
* such as custom memory managers and non-standard newline definitions. *
* This program does not do any of this, so it makes no use of contexts, *
* always passing NULL where a context could be given. *
**************************************************************************/ int main(int argc, char **argv)
{
pcre2_code *re;
PCRE2_SPTR pattern; /* PCRE2_SPTR is a pointer to unsigned code units of */
PCRE2_SPTR subject; /* the appropriate width (8, 16, or 32 bits). */
PCRE2_SPTR name_table; int crlf_is_newline;
int errornumber;
int find_all;
int i;
int namecount;
int name_entry_size;
int rc;
int utf8; uint32_t option_bits;
uint32_t newline; PCRE2_SIZE erroroffset;
PCRE2_SIZE *ovector; size_t subject_length;
pcre2_match_data *match_data; /**************************************************************************
* First, sort out the command line. There is only one possible option at *
* the moment, "-g" to request repeated matching to find all occurrences, *
* like Perl's /g option. We set the variable find_all to a non-zero value *
* if the -g option is present. Apart from that, there must be exactly two *
* arguments. *
**************************************************************************/ find_all = ;
for (i = ; i < argc; i++)
{
if (strcmp(argv[i], "-g") == )
find_all = ;
else
break;
} /* After the options, we require exactly two arguments, which are the pattern,
and the subject string. */ if (argc - i != )
{
printf("Two arguments required: a regex and a subject string\n");
return ;
} /* As pattern and subject are char arguments, they can be straightforwardly
cast to PCRE2_SPTR as we are working in 8-bit code units. */ pattern = (PCRE2_SPTR)argv[i];
subject = (PCRE2_SPTR)argv[i+];
subject_length = strlen((char *)subject); /*************************************************************************
* Now we are going to compile the regular expression pattern, and handle *
* any errors that are detected. *
*************************************************************************/ re = pcre2_compile(
pattern, /* the pattern */
PCRE2_ZERO_TERMINATED, /* indicates pattern is zero-terminated */
, /* default options */
&errornumber, /* for error number */
&erroroffset, /* for error offset */
NULL); /* use default compile context */ /* Compilation failed: print the error message and exit. */ if (re == NULL)
{
PCRE2_UCHAR buffer[];
pcre2_get_error_message(errornumber, buffer, sizeof(buffer));
printf("PCRE2 compilation failed at offset %d: %s\n", (int)erroroffset, buffer);
return ;
} /*************************************************************************
* If the compilation succeeded, we call PCRE again, in order to do a *
* pattern match against the subject string. This does just ONE match. If *
* further matching is needed, it will be done below. Before running the *
* match we must set up a match_data block for holding the result. *
*************************************************************************/ /* Using this function ensures that the block is exactly the right size for
the number of capturing parentheses in the pattern. */ match_data = pcre2_match_data_create_from_pattern(re, NULL); rc = pcre2_match(
re, /* the compiled pattern */
subject, /* the subject string */
subject_length, /* the length of the subject */
, /* start at offset 0 in the subject */
, /* default options */
match_data, /* block for storing the result */
NULL); /* use default match context */ /* Matching failed: handle error cases */ if (rc < )
{
switch(rc)
{
case PCRE2_ERROR_NOMATCH:
printf("No match\n");
break;
/*
Handle other special cases if you like
*/
default:
printf("Matching error %d\n", rc);
break;
}
pcre2_match_data_free(match_data); /* Release memory used for the match */
pcre2_code_free(re); /* data and the compiled pattern. */
return ;
} /* Match succeded. Get a pointer to the output vector, where string offsets are
stored. */ ovector = pcre2_get_ovector_pointer(match_data);
printf("\nMatch succeeded at offset %d\n", (int)ovector[]); /*************************************************************************
* We have found the first match within the subject string. If the output *
* vector wasn't big enough, say so. Then output any substrings that were *
* captured. *
*************************************************************************/ /* The output vector wasn't big enough. This should not happen, because we used
pcre2_match_data_create_from_pattern() above. */ if (rc == )
printf("ovector was not big enough for all the captured substrings\n"); /* Show substrings stored in the output vector by number. Obviously, in a real
application you might want to do things other than print them. */ for (i = ; i < rc; i++)
{
PCRE2_SPTR substring_start = subject + ovector[*i];
size_t substring_length = ovector[*i+] - ovector[*i];
printf("%2d: %.*s\n", i, (int)substring_length, (char *)substring_start);
} /**************************************************************************
* That concludes the basic part of this demonstration program. We have *
* compiled a pattern, and performed a single match. The code that follows *
* shows first how to access named substrings, and then how to code for *
* repeated matches on the same subject. *
**************************************************************************/ /* See if there are any named substrings, and if so, show them by name. First
we have to extract the count of named parentheses from the pattern. */ (void)pcre2_pattern_info(
re, /* the compiled pattern */
PCRE2_INFO_NAMECOUNT, /* get the number of named substrings */
&namecount); /* where to put the answer */ if (namecount <= )
printf("No named substrings\n");
else
{
PCRE2_SPTR tabptr;
printf("Named substrings\n"); /* Before we can access the substrings, we must extract the table for
translating names to numbers, and the size of each entry in the table. */ (void)pcre2_pattern_info(
re, /* the compiled pattern */
PCRE2_INFO_NAMETABLE, /* address of the table */
&name_table); /* where to put the answer */ (void)pcre2_pattern_info(
re, /* the compiled pattern */
PCRE2_INFO_NAMEENTRYSIZE, /* size of each entry in the table */
&name_entry_size); /* where to put the answer */ /* Now we can scan the table and, for each entry, print the number, the name,
and the substring itself. In the 8-bit library the number is held in two
bytes, most significant first. */ tabptr = name_table;
for (i = ; i < namecount; i++)
{
int n = (tabptr[] << ) | tabptr[];
printf("(%d) %*s: %.*s\n", n, name_entry_size - , tabptr + , int)(ovector[*n+] - ovector[*n]), subject + ovector[*n]);
tabptr += name_entry_size;
}
} /*************************************************************************
* If the "-g" option was given on the command line, we want to continue *
* to search for additional matches in the subject string, in a similar *
* way to the /g option in Perl. This turns out to be trickier than you *
* might think because of the possibility of matching an empty string. *
* What happens is as follows: *
* *
* If the previous match was NOT for an empty string, we can just start *
* the next match at the end of the previous one. *
* *
* If the previous match WAS for an empty string, we can't do that, as it *
* would lead to an infinite loop. Instead, a call of pcre2_match() is *
* made with the PCRE2_NOTEMPTY_ATSTART and PCRE2_ANCHORED flags set. The *
* first of these tells PCRE2 that an empty string at the start of the *
* subject is not a valid match; other possibilities must be tried. The *
* second flag restricts PCRE2 to one match attempt at the initial string *
* position. If this match succeeds, an alternative to the empty string *
* match has been found, and we can print it and proceed round the loop, *
* advancing by the length of whatever was found. If this match does not *
* succeed, we still stay in the loop, advancing by just one character. *
* In UTF-8 mode, which can be set by (*UTF) in the pattern, this may be *
* more than one byte. *
* *
* However, there is a complication concerned with newlines. When the *
* newline convention is such that CRLF is a valid newline, we must *
* advance by two characters rather than one. The newline convention can *
* be set in the regex by (*CR), etc.; if not, we must find the default. *
*************************************************************************/ if (!find_all) /* Check for -g */
{
pcre2_match_data_free(match_data); /* Release the memory that was used */
pcre2_code_free(re); /* for the match data and the pattern. */
return ; /* Exit the program. */
} /* Before running the loop, check for UTF-8 and whether CRLF is a valid newline
sequence. First, find the options with which the regex was compiled and extract
the UTF state. */ (void)pcre2_pattern_info(re, PCRE2_INFO_ALLOPTIONS, &option_bits);
utf8 = (option_bits & PCRE2_UTF) != ; /* Now find the newline convention and see whether CRLF is a valid newline
sequence. */ (void)pcre2_pattern_info(re, PCRE2_INFO_NEWLINE, &newline);
crlf_is_newline = newline == PCRE2_NEWLINE_ANY || newline == PCRE2_NEWLINE_CRLF || newline == PCRE2_NEWLINE_ANYCRLF; /* Loop for second and subsequent matches */ for (;;)
{
uint32_t options = ; /* Normally no options */
PCRE2_SIZE start_offset = ovector[]; /* Start at end of previous match */ /* If the previous match was for an empty string, we are finished if we are
at the end of the subject. Otherwise, arrange to run another match at the
same point to see if a non-empty match can be found. */ if (ovector[] == ovector[])
{
if (ovector[] == subject_length)
break;
options = PCRE2_NOTEMPTY_ATSTART | PCRE2_ANCHORED;
} /* Run the next matching operation */ rc = pcre2_match(
re, /* the compiled pattern */
subject, /* the subject string */
subject_length, /* the length of the subject */
start_offset, /* starting offset in the subject */
options, /* options */
match_data, /* block for storing the result */
NULL); /* use default match context */ /* This time, a result of NOMATCH isn't an error. If the value in "options"
is zero, it just means we have found all possible matches, so the loop ends.
Otherwise, it means we have failed to find a non-empty-string match at a
point where there was a previous empty-string match. In this case, we do what
Perl does: advance the matching position by one character, and continue. We
do this by setting the "end of previous match" offset, because that is picked
up at the top of the loop as the point at which to start again. There are two complications: (a) When CRLF is a valid newline sequence, and
the current position is just before it, advance by an extra byte. (b)
Otherwise we must ensure that we skip an entire UTF character if we are in
UTF mode. */ if (rc == PCRE2_ERROR_NOMATCH)
{
if (options == ) break; /* All matches found */
ovector[] = start_offset + ; /* Advance one code unit */
if (crlf_is_newline && /* If CRLF is newline & */
start_offset < subject_length - && /* we are at CRLF, */
subject[start_offset] == '\r' &&
subject[start_offset + ] == '\n')
ovector[] += ; /* Advance by one more. */
else if (utf8) /* Otherwise, ensure we */
{ /* advance a whole UTF-8 */
while (ovector[] < subject_length) /* character. */
{
if ((subject[ovector[]] & 0xc0) != 0x80)
break;
ovector[] += ;
}
}
continue; /* Go round the loop again */
} /* Other matching errors are not recoverable. */ if (rc < )
{
printf("Matching error %d\n", rc);
pcre2_match_data_free(match_data);
pcre2_code_free(re);
return ;
} /* Match succeded */ printf("\nMatch succeeded again at offset %d\n", (int)ovector[]); /* The match succeeded, but the output vector wasn't big enough. This
should not happen. */ if (rc == )
printf("ovector was not big enough for all the captured substrings\n"); /* As before, show substrings stored in the output vector by number, and then
also any named substrings. */ for (i = ; i < rc; i++)
{
PCRE2_SPTR substring_start = subject + ovector[*i];
size_t substring_length = ovector[*i+] - ovector[*i];
printf("%2d: %.*s\n", i, (int)substring_length, (char *)substring_start);
} if (namecount <= ) printf("No named substrings\n"); else
{
PCRE2_SPTR tabptr = name_table;
printf("Named substrings\n");
for (i = ; i < namecount; i++)
{
int n = (tabptr[] << ) | tabptr[];
printf("(%d) %*s: %.*s\n", n, name_entry_size - , tabptr + , (int)(ovector[*n+] - ovector[*n]), subject + ovector[*n]);
tabptr += name_entry_size;
}
}
} /* End of loop to find second and subsequent matches */ printf("\n");
pcre2_match_data_free(match_data);
pcre2_code_free(re);
return ;
} /* End of pcre2demo.c */

Relevant Link:

http://php.net/manual/zh/function.preg-match.php
http://www.pcre.org/current/doc/html/pcre2demo.html

Copyright (c) 2015 LittleHann All rights reserved

PCRE Perl Compatible Regular Expressions Learning的更多相关文章

  1. Perl Compatible Regular Expressions

    http://www.pcre.org/ http://www.pcre.org/

  2. Python之Regular Expressions(正则表达式)

    在编写处理字符串的程序或网页时,经常会有查找符合某些复杂规则的字符串的需要.正则表达式就是用于描述这些规则的工具.换句话说,正则表达式就是记录文本规则的代码. 很可能你使用过Windows/Dos下用 ...

  3. Introducing Regular Expressions 学习笔记

    Introducing Regular Expressions 读书笔记 工具: regexbuddy:http://download.csdn.net/tag/regexbuddy%E7%A0%B4 ...

  4. Regular Expressions --正则表达式官方教程

    http://docs.oracle.com/javase/tutorial/essential/regex/index.html This lesson explains how to use th ...

  5. Finding Comments in Source Code Using Regular Expressions

    Many text editors have advanced find (and replace) features. When I’m programming, I like to use an ...

  6. Python re module &lpar;regular expressions&rpar;

    regular expressions (RE) 简介 re模块是python中处理正在表达式的一个模块 r"""Support for regular expressi ...

  7. 8 Regular Expressions You Should Know

    Regular expressions are a language of their own. When you learn a new programming language, they're ...

  8. 转载:邮箱正则表达式Comparing E-mail Address Validating Regular Expressions

    Comparing E-mail Address Validating Regular Expressions Updated: 2/3/2012 Summary This page compares ...

  9. Regular Expressions in Grep Command with 10 Examples --reference

    Regular expressions are used to search and manipulate the text, based on the patterns. Most of the L ...

随机推荐

  1. vue&period;js几行实现的简单的todo list

    序:目前前端框架如:vue.react.angular,构建工具fis3.gulp.webpack等等...... 可谓是五花八门,层出不穷,眼花缭乱...其实吧只要你想玩还是可以玩玩的..下面是看了 ...

  2. 我的java后端书架

  3. Linux文件操作常用命令整理

    收集.整理日常系统管理或维护当中的,常用到的一些关于文件操作的命令或需求,后续会慢慢补充.完善! 查看.生成指定目录的目录树结构?   [root@DB-Server ~]#tree   #当前目录 ...

  4. Top Deep Learning Projects in github

    Top Deep Learning Projects A list of popular github projects related to deep learning (ranked by sta ...

  5. Android保存图像到相册

    在应用的图集中,通常会给用户提供保存图片的功能,让用户可以将自己喜欢的图片保存到系统相册中. 这个功能其实很好做,系统提供了现成的API: 简单的来说就这一行代码: [java]  MediaStor ...

  6. Python装饰模式实现源码分享

    1.一般来说,通过继承可以获得父类的属性,还可以通过重载修改其方法. 2.装饰模式可以不以继承的方式而动态地修改类的方法. 3.装饰模式可以不以继承的方式而返回一个被修改的类. 4.基本实现 程序演示 ...

  7. R语言 一元线性回归

    #一元线性回归的基本步骤#1.载入数据 给出散点图 x<-c(0.10,0.11,0.12,0.13,0.14,0.15,0.16,0.17,0.18,0.20,0.21,0.23) y< ...

  8. int 和String之间的互转

    int -> String int i=12345;String s="";第一种方法:s=i+"";第二种方法:s=String.valueOf(i); ...

  9. C3P0连接池参数详解

    <c3p0-config> <default-config> <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数.Default: 3 --> < ...

  10. Lucence

    Lucene是apache软件基金会4 jakarta项目组的一个子项目,是一个开放源代码的全文检索引擎工具包,但它不是一个完整的全文检索引擎,而是一个全文检索引擎的架构,提供了完整的查询引擎和索引引 ...