Professional Documents
Culture Documents
This file contains a concatenation of the PCRE2 man pages, converted to plain
text format for ease of searching with a text editor, or for use on systems
that do not have a man page processor. The small individual files that give
synopses of each function in the library have not been included. Neither has
the pcre2demo program. There are separate text files for the pcre2grep and
pcre2test commands.
-----------------------------------------------------------------------------
NAME
PCRE2 - Perl-compatible regular expressions (revised API)
INTRODUCTION
PCRE2 is the name used for a revised API for the PCRE library, which is
a set of functions, written in C, that implement regular expression
pattern matching using the same syntax and semantics as Perl, with just
a few differences. After nearly two decades, the limitations of the
original API were making development increasingly difficult. The new
API is more extensible, and it was simplified by abolishing the sepa-
rate "study" optimizing function; in PCRE2, patterns are automatically
optimized where possible. Since forking from PCRE1, the code has been
extensively refactored and new features introduced.
The source code for PCRE2 can be compiled to support strings of 8-bit,
16-bit, or 32-bit code units, which means that up to three separate li-
braries may be installed, one for each code unit size. The size of code
unit is not related to the bit size of the underlying hardware. In a
64-bit environment that also supports 32-bit applications, versions of
PCRE2 that are compiled in both 64-bit and 32-bit modes may be needed.
The original work to extend PCRE to 16-bit and 32-bit code units was
done by Zoltan Herczeg and Christian Persch, respectively. In all three
cases, strings can be interpreted either as one character per code
unit, or as UTF-encoded Unicode, with support for Unicode general cate-
gory properties. Unicode support is optional at build time (but is the
default). However, processing strings as UTF code units must be enabled
explicitly at run time. The version of Unicode in use can be discovered
by running
pcre2test -C
Details of exactly which Perl regular expression features are and are
not supported by PCRE2 are given in separate documents. See the
pcre2pattern and pcre2compat pages. There is a syntax summary in the
pcre2syntax page.
SECURITY CONSIDERATIONS
The use of Unicode properties for character types such as \d can also
be enabled from within the pattern, by specifying "(*UCP)". This fea-
ture can be disallowed by setting the PCRE2_NEVER_UCP option.
The use of the \C escape sequence in a UTF-8 or UTF-16 pattern can lead
to problems, because it may leave the current matching point in the
middle of a multi-code-unit character. The PCRE2_NEVER_BACKSLASH_C op-
tion can be used by an application to lock out the use of \C, causing a
compile-time error if it is encountered. It is also possible to build
PCRE2 with the use of \C permanently disabled.
USER DOCUMENTATION
In the "man" and HTML formats, there is also a short page for each C
library function, listing its arguments and results.
AUTHOR
Philip Hazel
University Computing Service
Cambridge, England.
Putting an actual email address here is a spam magnet. If you want to
email me, use my two initials, followed by the two digits 10, at the
domain cam.ac.uk.
REVISION
NAME
PCRE2 - Perl-compatible regular expressions (revised API)
#include <pcre2.h>
PCRE2 is a new API for PCRE, starting at release 10.0. This document
contains a description of all its native functions. See the pcre2 docu-
ment for an overview of all the PCRE2 documentation.
pcre2_match_data *pcre2_match_data_create_from_pattern(
const pcre2_code *code, pcre2_general_context *gcontext);
pcre2_general_context *pcre2_general_context_create(
void *(*private_malloc)(PCRE2_SIZE, void *),
void (*private_free)(void *, void *), void *memory_data);
pcre2_general_context *pcre2_general_context_copy(
pcre2_general_context *gcontext);
pcre2_compile_context *pcre2_compile_context_create(
pcre2_general_context *gcontext);
pcre2_compile_context *pcre2_compile_context_copy(
pcre2_compile_context *ccontext);
pcre2_match_context *pcre2_match_context_create(
pcre2_general_context *gcontext);
pcre2_match_context *pcre2_match_context_copy(
pcre2_match_context *mcontext);
int pcre2_set_recursion_memory_management(
pcre2_match_context *mcontext,
void *(*private_malloc)(PCRE2_SIZE, void *),
void (*private_free)(void *, void *), void *memory_data);
These functions became obsolete at release 10.30 and are retained only
for backward compatibility. They should not be used in new code. The
first is replaced by pcre2_set_depth_limit(); the second is no longer
needed and has no effect (it always returns zero).
pcre2_convert_context *pcre2_convert_context_create(
pcre2_general_context *gcontext);
pcre2_convert_context *pcre2_convert_context_copy(
pcre2_convert_context *cvcontext);
There are three PCRE2 libraries, supporting 8-bit, 16-bit, and 32-bit
code units, respectively. However, there is just one header file,
pcre2.h. This contains the function prototypes and other definitions
for all three libraries. One, two, or all three can be installed simul-
taneously. On Unix-like systems the libraries are called libpcre2-8,
libpcre2-16, and libpcre2-32, and they can also co-exist with the orig-
inal PCRE libraries.
pcre2_compile_8()
pcre2_compile_16()
pcre2_compile_32()
The UCHAR types define unsigned code units of the appropriate widths.
For example, PCRE2_UCHAR16 is usually defined as `uint16_t'. The SPTR
types are constant pointers to the equivalent UCHAR types, that is,
they are pointers to vectors of unsigned code units.
Many applications use only one code unit width. For their convenience,
macros are defined whose names are the generic forms such as pcre2_com-
pile() and PCRE2_SPTR. These macros use the value of the macro
PCRE2_CODE_UNIT_WIDTH to generate the appropriate width-specific func-
tion and macro names. PCRE2_CODE_UNIT_WIDTH is not defined by default.
An application must define it to be 8, 16, or 32 before including
pcre2.h in order to make use of the generic names.
Applications that use more than one code unit width can be linked with
more than one PCRE2 library, but must define PCRE2_CODE_UNIT_WIDTH to
be 0 before including pcre2.h, and then use the real function names.
Any code that is to be included in an environment where the value of
PCRE2_CODE_UNIT_WIDTH is unknown should also use the real function
names. (Unfortunately, it is not possible in C code to save and restore
the value of a macro.)
In the function summaries above, and in the rest of this document and
other PCRE2 documents, functions and data types are described using
their generic names, without the _8, _16, or _32 suffix.
PCRE2 has its own native API, which is described in this document.
There are also some wrapper functions for the 8-bit library that corre-
spond to the POSIX regular expression API, but they do not give access
to all the functionality of PCRE2. They are described in the pcre2posix
documentation. Both these APIs define a set of C function calls.
The native API C data types, function prototypes, option values, and
error codes are defined in the header file pcre2.h, which also contains
definitions of PCRE2_MAJOR and PCRE2_MINOR, the major and minor release
numbers for the library. Applications can use these to include support
for different releases of PCRE2.
The compiling and matching functions recognize various options that are
passed as bits in an options argument. There are also some more compli-
cated parameters such as custom memory management functions and re-
source limits that are passed in "contexts" (which are just memory
blocks, described below). Simple applications do not need to make use
of contexts.
pcre2_substring_copy_byname()
pcre2_substring_copy_bynumber()
pcre2_substring_get_byname()
pcre2_substring_get_bynumber()
pcre2_substring_list_get()
pcre2_substring_length_byname()
pcre2_substring_length_bynumber()
pcre2_substring_nametable_scan()
pcre2_substring_number_from_name()
Functions whose names begin with pcre2_serialize_ are used for saving
compiled patterns on disc or elsewhere, and reloading them later.
Finally, there are functions for finding out information about a com-
piled pattern (pcre2_pattern_info()) and about the configuration with
which PCRE2 was built (pcre2_config()).
Functions with names ending with _free() are used for freeing memory
blocks of various sorts. In all cases, if one of these functions is
called with a NULL argument, it does nothing.
The PCRE2 API uses string lengths and offsets into strings of code
units in several places. These values are always of type PCRE2_SIZE,
which is an unsigned integer type, currently always defined as size_t.
The largest value that can be stored in such a type (that is
~(PCRE2_SIZE)0) is reserved as a special indicator for zero-terminated
strings and unset offsets. Therefore, the longest string that can be
handled is one less than this maximum.
NEWLINES
MULTITHREADING
There are several different blocks of data that are used to pass infor-
mation between the application and the PCRE2 libraries.
The reason for checking the pointer a second time is as follows: Sev-
eral threads may have acquired the shared lock and tested the pointer
for being NULL, but only one of them will be given the write lock, with
the rest kept waiting. The winning thread will compile the pattern and
store the result. After this thread releases the write lock, another
thread will get it, and if it does not retest pointer for being NULL,
will recompile the pattern and overwrite the pointer, creating a memory
leak and possibly causing other issues.
If JIT is being used, but the JIT compilation is not being done immedi-
ately (perhaps waiting to see if the pattern is used often enough),
similar logic is required. JIT compilation updates a value within the
compiled code block, so a thread must gain unique write access to the
pointer before calling pcre2_jit_compile(). Alternatively,
pcre2_code_copy() or pcre2_code_copy_with_tables() can be used to ob-
tain a private copy of the compiled code before calling the JIT com-
piler.
Context blocks
The next main section below introduces the idea of "contexts" in which
PCRE2 functions are called. A context is nothing more than a collection
of parameters that control the way PCRE2 operates. Grouping a number of
parameters together in a context is a convenient way of passing them to
a PCRE2 function without using lots of arguments. The parameters that
are stored in contexts are in some sense "advanced features" of the
API. Many straightforward applications will not need to use contexts.
Match blocks
The matching functions need a block of memory for storing the results
of a match. This includes details of what was matched, as well as addi-
tional information such as the name of a (*MARK) setting. Each thread
must provide its own copy of this memory.
PCRE2 CONTEXTS
Some PCRE2 functions have a lot of parameters, many of which are used
only by specialist applications, for example, those that use custom
memory management or non-standard character tables. To keep function
argument lists at a reasonable size, and at the same time to keep the
API extensible, "uncommon" parameters are passed to certain functions
in a context instead of directly. A context is just a block of memory
that holds the parameter values. Applications that do not need to ad-
just any of the context parameters can pass NULL when a context pointer
is required.
At present, this context just contains pointers to (and data for) ex-
ternal memory management functions that are called from several places
in the PCRE2 library. The context is named `general' rather than
specifically `memory' because in future other fields may be added. If
you do not want to supply your own custom memory management functions,
you do not need to bother with a general context. A general context is
created by:
pcre2_general_context *pcre2_general_context_create(
void *(*private_malloc)(PCRE2_SIZE, void *),
void (*private_free)(void *, void *), void *memory_data);
Whenever code in PCRE2 calls these functions, the final argument is the
value of memory_data. Either of the first two arguments of the creation
function may be NULL, in which case the system memory management func-
tions malloc() and free() are used. (This is not currently useful, as
there are no other fields in a general context, but in future there
might be.) The private_malloc() function is used (if supplied) to ob-
tain memory for storing the context, and all three values are saved as
part of the context.
Whenever PCRE2 creates a data block of any kind, the block contains a
pointer to the free() function that matches the malloc() function that
was used. When the time comes to free the block, this function is
called.
pcre2_general_context *pcre2_general_context_copy(
pcre2_general_context *gcontext);
A compile context is also required if you are using custom memory man-
agement. If none of these apply, just pass NULL as the context argu-
ment of pcre2_compile().
pcre2_compile_context *pcre2_compile_context_create(
pcre2_general_context *gcontext);
pcre2_compile_context *pcre2_compile_context_copy(
pcre2_compile_context *ccontext);
As PCRE2 has developed, almost all the 32 option bits that are avail-
able in the options argument of pcre2_compile() have been used up. To
avoid running out, the compile context contains a set of extra option
bits which are used for some newer, assumed rarer, options. This func-
tion sets those bits. It always sets all the bits (either on or off).
It does not modify any existing setting. The available options are de-
fined in the section entitled "Extra compile options" below.
This sets a maximum length, in code units, for any pattern string that
is compiled with this context. If the pattern is longer, an error is
generated. This facility is provided so that applications that accept
patterns from external sources can limit their size. The default is the
largest number that a PCRE2_SIZE variable can hold, which is effec-
tively unlimited.
A pattern can override the value set in the compile context by starting
with a sequence such as (*CRLF). See the pcre2pattern page for details.
This parameter adjusts the limit, set when PCRE2 is built (default
250), on the depth of parenthesis nesting in a pattern. This limit
stops rogue patterns using up too much system stack when being com-
piled. The limit applies to parentheses of all kinds, not just captur-
ing parentheses.
There is at least one application that runs PCRE2 in threads with very
limited system stack, where running out of stack is to be avoided at
all costs. The parenthesis limit above cannot take account of how much
stack is actually available during compilation. For a finer control,
you can supply a function that is called whenever pcre2_compile()
starts to compile a parenthesized part of a pattern. This function can
check the actual stack size (or anything else that it wants to, of
course).
The first argument to the callout function gives the current depth of
nesting, and the second is user data that is set up by the last argu-
ment of pcre2_set_compile_recursion_guard(). The callout function
should return zero if all is well, or non-zero to force an error.
The match context
pcre2_match_context *pcre2_match_context_create(
pcre2_general_context *gcontext);
pcre2_match_context *pcre2_match_context_copy(
pcre2_match_context *mcontext);
This sets up a callout function for PCRE2 to call after each substitu-
tion made by pcre2_substitute(). Details are given in the section enti-
tled "Creating a new string with substitutions" below.
The offset_limit parameter limits how far an unanchored search can ad-
vance in the subject string. The default value is PCRE2_UNSET. The
pcre2_match() and pcre2_dfa_match() functions return PCRE2_ERROR_NO-
MATCH if a match with a starting point before or at the given offset is
not found. The pcre2_substitute() function makes no more substitutions.
The offset limit facility can be used to track progress when searching
large subject strings or to limit the extent of global substitutions.
See also the PCRE2_FIRSTLINE option, which requires a match to start
before or at the first newline that follows the start of matching in
the subject. If this is set with an offset limit, a match must occur in
the first line and also within the offset limit. In other words, which-
ever limit comes first is used.
A value for the heap limit may also be supplied by an item at the start
of a pattern of the form
(*LIMIT_HEAP=ddd)
The pcre2_match() function starts out using a 20KiB vector on the sys-
tem stack for recording backtracking points. The more nested backtrack-
ing points there are (that is, the deeper the search tree), the more
memory is needed. Heap memory is used only if the initial vector is
too small. If the heap limit is set to a value less than 21 (in partic-
ular, zero) no heap memory will be used. In this case, only patterns
that do not have a lot of nested backtracking can be successfully pro-
cessed.
The default value for the limit can be set when PCRE2 is built; the de-
fault default is 10 million, which handles all but the most extreme
cases. A value for the match limit may also be supplied by an item at
the start of a pattern of the form
(*LIMIT_MATCH=ddd)
The depth limit is not relevant, and is ignored, when matching is done
using JIT compiled code. However, it is supported by pcre2_dfa_match(),
which uses it to limit the depth of nested internal recursive function
calls that implement atomic groups, lookaround assertions, and pattern
recursions. This limits, indirectly, the amount of system stack that is
used. It was more useful in versions before 10.32, when stack memory
was used for local workspace vectors for recursive function calls. From
version 10.32, only local variables are allocated on the stack and as
each call uses only a few hundred bytes, even a small stack can support
quite a lot of recursion.
(*LIMIT_DEPTH=ddd)
PCRE2_CONFIG_BSR
PCRE2_CONFIG_COMPILED_WIDTHS
The output is a uint32_t integer whose lower bits indicate which code
unit widths were selected when PCRE2 was built. The 1-bit indicates
8-bit support, and the 2-bit and 4-bit indicate 16-bit and 32-bit sup-
port, respectively.
PCRE2_CONFIG_DEPTHLIMIT
The output is a uint32_t integer that gives the default limit for the
depth of nested backtracking in pcre2_match() or the depth of nested
recursions, lookarounds, and atomic groups in pcre2_dfa_match(). Fur-
ther details are given with pcre2_set_depth_limit() above.
PCRE2_CONFIG_HEAPLIMIT
PCRE2_CONFIG_JIT
PCRE2_CONFIG_JITTARGET
PCRE2_CONFIG_LINKSIZE
The output is a uint32_t integer that contains the number of bytes used
for internal linkage in compiled regular expressions. When PCRE2 is
configured, the value can be set to 2, 3, or 4, with the default being
2. This is the value that is returned by pcre2_config(). However, when
the 16-bit library is compiled, a value of 3 is rounded up to 4, and
when the 32-bit library is compiled, internal linkages always use 4
bytes, so the configured value is not relevant.
The default value of 2 for the 8-bit and 16-bit libraries is sufficient
for all but the most massive patterns, since it allows the size of the
compiled pattern to be up to 65535 code units. Larger values allow
larger regular expressions to be compiled by those two libraries, but
at the expense of slower matching.
PCRE2_CONFIG_MATCHLIMIT
The output is a uint32_t integer that gives the default match limit for
pcre2_match(). Further details are given with pcre2_set_match_limit()
above.
PCRE2_CONFIG_NEWLINE
PCRE2_CONFIG_NEVER_BACKSLASH_C
PCRE2_CONFIG_PARENSLIMIT
The output is a uint32_t integer that gives the maximum depth of nest-
ing of parentheses (of any kind) in a pattern. This limit is imposed to
cap the amount of system stack used when a pattern is compiled. It is
specified when PCRE2 is built; the default is 250. This limit does not
take into account the stack that may already be used by the calling ap-
plication. For finer control over compilation stack usage, see
pcre2_set_compile_recursion_guard().
PCRE2_CONFIG_STACKRECURSE
This parameter is obsolete and should not be used in new code. The out-
put is a uint32_t integer that is always set to zero.
PCRE2_CONFIG_TABLES_LENGTH
The output is a uint32_t integer that gives the length of PCRE2's char-
acter processing tables in bytes. For details of these tables see the
section on locale support below.
PCRE2_CONFIG_UNICODE_VERSION
PCRE2_CONFIG_UNICODE
PCRE2_CONFIG_VERSION
COMPILING A PATTERN
If the compile context argument ccontext is NULL, memory for the com-
piled pattern is obtained by calling malloc(). Otherwise, it is ob-
tained from the same memory function that was used for the compile con-
text. The caller must free the memory by calling pcre2_code_free() when
it is no longer needed. If pcre2_code_free() is called with a NULL ar-
gument, it returns immediately, without doing anything.
For those options that can be different in different parts of the pat-
tern, the contents of the options argument specifies their settings at
the start of compilation. The PCRE2_ANCHORED, PCRE2_ENDANCHORED, and
PCRE2_NO_UTF_CHECK options can be set at the time of matching as well
as at compile time.
There are nearly 100 positive error codes that pcre2_compile() may re-
turn if it finds an error in the pattern. There are also some negative
error codes that are used for invalid UTF strings when validity check-
ing is in force. These are the same as given by pcre2_match() and
pcre2_dfa_match(), and are described in the pcre2unicode documentation.
There is no separate documentation for the positive error codes, be-
cause the textual error messages that are obtained by calling the
pcre2_get_error_message() function (see "Obtaining a textual error mes-
sage" below) should be self-explanatory. Macro names starting with
PCRE2_ERROR_ are defined for both positive and negative error codes in
pcre2.h.
Some errors are not detected until the whole pattern has been scanned;
in these cases, the offset passed back is the length of the pattern.
Note that the offset is in code units, not characters, even in a UTF
mode. It may sometimes point into the middle of a UTF-8 or UTF-16 char-
acter.
pcre2_code *re;
PCRE2_SIZE erroffset;
int errorcode;
re = pcre2_compile(
"^A.*Z", /* the pattern */
PCRE2_ZERO_TERMINATED, /* the pattern is zero-terminated */
0, /* default options */
&errorcode, /* for error code */
&erroffset, /* for error offset */
NULL); /* no compile context */
Main compile options
The following names for option bits are defined in the pcre2.h header
file:
PCRE2_ANCHORED
PCRE2_ALLOW_EMPTY_CLASS
PCRE2_ALT_BSUX
PCRE2_ALT_CIRCUMFLEX
PCRE2_ALT_VERBNAMES
By default, for compatibility with Perl, the name in any verb sequence
such as (*MARK:NAME) is any sequence of characters that does not in-
clude a closing parenthesis. The name is not processed in any way, and
it is not possible to include a closing parenthesis in the name. How-
ever, if the PCRE2_ALT_VERBNAMES option is set, normal backslash pro-
cessing is applied to verb names and only an unescaped closing paren-
thesis terminates the name. A closing parenthesis can be included in a
name either as \) or between \Q and \E. If the PCRE2_EXTENDED or
PCRE2_EXTENDED_MORE option is set with PCRE2_ALT_VERBNAMES, unescaped
whitespace in verb names is skipped and #-comments are recognized, ex-
actly as in the rest of the pattern.
PCRE2_AUTO_CALLOUT
PCRE2_CASELESS
If this bit is set, letters in the pattern match both upper and lower
case letters in the subject. It is equivalent to Perl's /i option, and
it can be changed within a pattern by a (?i) option setting. If either
PCRE2_UTF or PCRE2_UCP is set, Unicode properties are used for all
characters with more than one other case, and for all characters whose
code points are greater than U+007F. Note that there are two ASCII
characters, K and S, that, in addition to their lower case ASCII equiv-
alents, are case-equivalent with U+212A (Kelvin sign) and U+017F (long
S) respectively. For lower valued characters with only one other case,
a lookup table is used for speed. When neither PCRE2_UTF nor PCRE2_UCP
is set, a lookup table is used for all code points less than 256, and
higher code points (available only in 16-bit or 32-bit mode) are
treated as not having another case.
PCRE2_DOLLAR_ENDONLY
PCRE2_DOTALL
PCRE2_DUPNAMES
If this bit is set, names used to identify capture groups need not be
unique. This can be helpful for certain types of pattern when it is
known that only one instance of the named group can ever be matched.
There are more details of named capture groups below; see also the
pcre2pattern documentation.
PCRE2_ENDANCHORED
If this bit is set, the end of any pattern match must be right at the
end of the string being searched (the "subject string"). If the pattern
match succeeds by reaching (*ACCEPT), but does not reach the end of the
subject, the match fails at the current starting point. For unanchored
patterns, a new match is then tried at the next starting point. How-
ever, if the match succeeds by reaching the end of the pattern, but not
the end of the subject, backtracking occurs and an alternative match
may be found. Consider these two patterns:
.(*ACCEPT)|..
.|..
PCRE2_EXTENDED
If this bit is set, most white space characters in the pattern are to-
tally ignored except when escaped or inside a character class. However,
white space is not allowed within sequences such as (?> that introduce
various parenthesized groups, nor within numerical quantifiers such as
{1,3}. Ignorable white space is permitted between an item and a follow-
ing quantifier and between a quantifier and a following + that indi-
cates possessiveness. PCRE2_EXTENDED is equivalent to Perl's /x option,
and it can be changed within a pattern by a (?x) option setting.
PCRE2_EXTENDED_MORE
PCRE2_FIRSTLINE
PCRE2_LITERAL
PCRE2_MATCH_INVALID_UTF
This option forces PCRE2_UTF (see below) and also enables support for
matching by pcre2_match() in subject strings that contain invalid UTF
sequences. This facility is not supported for DFA matching. For de-
tails, see the pcre2unicode documentation.
PCRE2_MATCH_UNSET_BACKREF
PCRE2_MULTILINE
PCRE2_NEVER_BACKSLASH_C
This option locks out the use of \C in the pattern that is being com-
piled. This escape can cause unpredictable behaviour in UTF-8 or
UTF-16 modes, because it may leave the current matching point in the
middle of a multi-code-unit character. This option may be useful in ap-
plications that process patterns from external sources. Note that there
is also a build-time option that permanently locks out the use of \C.
PCRE2_NEVER_UCP
This option locks out the use of Unicode properties for handling \B,
\b, \D, \d, \S, \s, \W, \w, and some of the POSIX character classes, as
described for the PCRE2_UCP option below. In particular, it prevents
the creator of the pattern from enabling this facility by starting the
pattern with (*UCP). This option may be useful in applications that
process patterns from external sources. The option combination PCRE_UCP
and PCRE_NEVER_UCP causes an error.
PCRE2_NEVER_UTF
PCRE2_NO_AUTO_CAPTURE
PCRE2_NO_AUTO_POSSESS
PCRE2_NO_DOTSTAR_ANCHOR
PCRE2_NO_START_OPTIMIZE
When this is compiled, PCRE2 records the fact that a match must start
with the character "A". Suppose the subject string is "DEFABC". The
start-up optimization scans along the subject, finds "A" and runs the
first match attempt from there. The (*COMMIT) item means that the pat-
tern must match the current starting position, which in this case, it
does. However, if the same match is run with PCRE2_NO_START_OPTIMIZE
set, the initial scan along the subject string does not happen. The
first match attempt is run starting from "D" and when this fails,
(*COMMIT) prevents any further matches being tried, so the overall re-
sult is "no match".
(*MARK:1)B(*MARK:2)(X|Y)
PCRE2_NO_UTF_CHECK
If you know that your pattern is a valid UTF string, and you want to
skip this check for performance reasons, you can set the
PCRE2_NO_UTF_CHECK option. When it is set, the effect of passing an in-
valid UTF string as a pattern is undefined. It may cause your program
to crash or loop.
Note also that setting PCRE2_NO_UTF_CHECK at compile time does not dis-
able the error that is given if an escape sequence for an invalid Uni-
code code point is encountered in the pattern. In particular, the so-
called "surrogate" code points (0xd800 to 0xdfff) are invalid. If you
want to allow escape sequences such as \x{d800} you can set the
PCRE2_EXTRA_ALLOW_SURROGATE_ESCAPES extra option, as described in the
section entitled "Extra compile options" below. However, this is pos-
sible only in UTF-8 and UTF-32 modes, because these values are not rep-
resentable in UTF-16.
PCRE2_UCP
This option has two effects. Firstly, it change the way PCRE2 processes
\B, \b, \D, \d, \S, \s, \W, \w, and some of the POSIX character
classes. By default, only ASCII characters are recognized, but if
PCRE2_UCP is set, Unicode properties are used instead to classify char-
acters. More details are given in the section on generic character
types in the pcre2pattern page. If you set PCRE2_UCP, matching one of
the items it affects takes much longer.
PCRE2_UNGREEDY
PCRE2_USE_OFFSET_LIMIT
PCRE2_UTF
This option causes PCRE2 to regard both the pattern and the subject
strings that are subsequently processed as strings of UTF characters
instead of single-code-unit strings. It is available when PCRE2 is
built to include Unicode support (which is the default). If Unicode
support is not available, the use of this option provokes an error. De-
tails of how PCRE2_UTF changes the behaviour of PCRE2 are given in the
pcre2unicode page. In particular, note that it changes the way
PCRE2_CASELESS handles characters with code points greater than 127.
The option bits that can be set in a compile context by calling the
pcre2_set_compile_extra_options() function are as follows:
PCRE2_EXTRA_ALLOW_SURROGATE_ESCAPES
PCRE2_EXTRA_ALT_BSUX
The original option PCRE2_ALT_BSUX causes PCRE2 to process \U, \u, and
\x in the way that ECMAscript (aka JavaScript) does. Additional func-
tionality was defined by ECMAscript 6; setting PCRE2_EXTRA_ALT_BSUX has
the effect of PCRE2_ALT_BSUX, but in addition it recognizes \u{hhh..}
as a hexadecimal character code, where hhh.. is any number of hexadeci-
mal digits.
PCRE2_EXTRA_BAD_ESCAPE_IS_LITERAL
PCRE2_EXTRA_ESCAPED_CR_IS_LF
PCRE2_EXTRA_MATCH_LINE
PCRE2_EXTRA_MATCH_WORD
LOCALE SUPPORT
PCRE2 contains a built-in set of character tables that are used by de-
fault. These are sufficient for many applications. Normally, the in-
ternal tables recognize only ASCII characters. However, when PCRE2 is
built, it is possible to cause the internal tables to be rebuilt in the
default "C" locale of the local system, which may cause them to be dif-
ferent.
For example, to build and use tables that are appropriate for the
French locale (where accented characters with values greater than 127
are treated as letters), the following code could be used:
setlocale(LC_CTYPE, "fr_FR");
tables = pcre2_maketables(NULL);
ccontext = pcre2_compile_context_create(NULL);
pcre2_set_character_tables(ccontext, tables);
re = pcre2_compile(..., ccontext);
The locale name "fr_FR" is used on Linux and other Unix-like systems;
if you are using Windows, the name for the French locale is "french".
int rc;
size_t length;
rc = pcre2_pattern_info(
re, /* result of pcre2_compile() */
PCRE2_INFO_SIZE, /* what is required */
&length); /* where to put the data */
The possible values for the second argument are defined in pcre2.h, and
are as follows:
PCRE2_INFO_ALLOPTIONS
PCRE2_INFO_ARGOPTIONS
PCRE2_INFO_EXTRAOPTIONS
Return copies of the pattern's options. The third argument should point
to a uint32_t variable. PCRE2_INFO_ARGOPTIONS returns exactly the op-
tions that were passed to pcre2_compile(), whereas PCRE2_INFO_ALLOP-
TIONS returns the compile options as modified by any top-level (*XXX)
option settings such as (*UTF) at the start of the pattern itself.
PCRE2_INFO_EXTRAOPTIONS returns the extra options that were set in the
compile context by calling the pcre2_set_compile_extra_options() func-
tion.
PCRE2_INFO_BACKREFMAX
PCRE2_INFO_BSR
PCRE2_INFO_CAPTURECOUNT
PCRE2_INFO_DEPTHLIMIT
PCRE2_INFO_FIRSTBITMAP
PCRE2_INFO_FIRSTCODETYPE
Return information about the first code unit of any matched string, for
a non-anchored pattern. The third argument should point to a uint32_t
variable. If there is a fixed first value, for example, the letter "c"
from a pattern such as (cat|cow|coyote), 1 is returned, and the value
can be retrieved using PCRE2_INFO_FIRSTCODEUNIT. If there is no fixed
first value, but it is known that a match can occur only at the start
of the subject or following a newline in the subject, 2 is returned.
Otherwise, and for anchored patterns, 0 is returned.
PCRE2_INFO_FIRSTCODEUNIT
Return the value of the first code unit of any matched string for a
pattern where PCRE2_INFO_FIRSTCODETYPE returns 1; otherwise return 0.
The third argument should point to a uint32_t variable. In the 8-bit
library, the value is always less than 256. In the 16-bit library the
value can be up to 0xffff. In the 32-bit library in UTF-32 mode the
value can be up to 0x10ffff, and up to 0xffffffff when not using UTF-32
mode.
PCRE2_INFO_FRAMESIZE
Return the size (in bytes) of the data frames that are used to remember
backtracking positions when the pattern is processed by pcre2_match()
without the use of JIT. The third argument should point to a size_t
variable. The frame size depends on the number of capturing parentheses
in the pattern. Each additional capture group adds two PCRE2_SIZE vari-
ables.
PCRE2_INFO_HASBACKSLASHC
PCRE2_INFO_HASCRORLF
If the pattern set a heap memory limit by including an item of the form
(*LIMIT_HEAP=nnnn) at the start, the value is returned. The third argu-
ment should point to a uint32_t integer. If no such value has been set,
the call to pcre2_pattern_info() returns the error PCRE2_ERROR_UNSET.
Note that this limit will only be used during matching if it is less
than the limit set or defaulted by the caller of the match function.
PCRE2_INFO_JCHANGED
PCRE2_INFO_JITSIZE
PCRE2_INFO_LASTCODETYPE
PCRE2_INFO_LASTCODEUNIT
Return the value of the rightmost literal code unit that must exist in
any matched string, other than at its start, for a pattern where
PCRE2_INFO_LASTCODETYPE returns 1. Otherwise, return 0. The third argu-
ment should point to a uint32_t variable.
PCRE2_INFO_MATCHEMPTY
PCRE2_INFO_MATCHLIMIT
PCRE2_INFO_MINLENGTH
PCRE2_INFO_NAMECOUNT
PCRE2_INFO_NAMEENTRYSIZE
PCRE2_INFO_NAMETABLE
Duplicate names for capture groups with different numbers are permit-
ted, but only if PCRE2_DUPNAMES is set. They appear in the table in the
order in which they were found in the pattern. In the absence of (?|
this is the order of increasing number; when (?| is used this is not
necessarily the case because later capture groups may have lower num-
bers.
(?<date> (?<year>(\d\d)?\d\d) -
(?<month>\d\d) - (?<day>\d\d) )
There are four named capture groups, so the table has four entries, and
each entry in the table is eight bytes long. The table is as follows,
with non-printing bytes shows in hexadecimal, and undefined bytes shown
as ??:
00 01 d a t e 00 ??
00 05 d a y 00 ?? ??
00 04 m o n t h 00
00 02 y e a r 00 ??
When writing code to extract data from named capture groups using the
name-to-number map, remember that the length of the entries is likely
to be different for each compiled pattern.
PCRE2_INFO_NEWLINE
PCRE2_INFO_SIZE
Return the size of the compiled pattern in bytes (for all three li-
braries). The third argument should point to a size_t variable. This
value includes the size of the general data block that precedes the
code units of the compiled pattern itself. The value that is used when
pcre2_compile() is getting memory in which to place the compiled pat-
tern may be slightly larger than the value returned by this option, be-
cause there are cases where the code that calculates the size has to
over-estimate. Processing a pattern with the JIT compiler does not al-
ter the value returned by this option.
pcre2_match_data *pcre2_match_data_create_from_pattern(
const pcre2_code *code, pcre2_general_context *gcontext);
A match data block can be used many times, with the same or different
compiled patterns. You can extract information from a match data block
after a match operation has finished, using functions that are de-
scribed in the sections on matched strings and other match data below.
This function is the main matching facility of the library, and it op-
erates in a Perl-like manner. For specialist use there is also an al-
ternative matching function, which is described below in the section
about the pcre2_dfa_match() function.
\Biss\B
Finding all the matches in a subject is tricky when the pattern can
match an empty string. It is possible to emulate Perl's /g behaviour by
first trying the match again at the same offset, with the
PCRE2_NOTEMPTY_ATSTART and PCRE2_ANCHORED options, and then if that
fails, advancing the starting offset and trying an ordinary match
again. There is some code that demonstrates how to do this in the
pcre2demo sample program. In the most general case, you have to check
to see if the newline convention recognizes CRLF as a newline, and if
so, and the current character is CR followed by LF, advance the start-
ing offset by two characters instead of one.
The unused bits of the options argument for pcre2_match() must be zero.
The only bits that may be set are PCRE2_ANCHORED,
PCRE2_COPY_MATCHED_SUBJECT, PCRE2_ENDANCHORED, PCRE2_NOTBOL, PCRE2_NO-
TEOL, PCRE2_NOTEMPTY, PCRE2_NOTEMPTY_ATSTART, PCRE2_NO_JIT,
PCRE2_NO_UTF_CHECK, PCRE2_PARTIAL_HARD, and PCRE2_PARTIAL_SOFT. Their
action is described below.
PCRE2_ANCHORED
PCRE2_COPY_MATCHED_SUBJECT
PCRE2_ENDANCHORED
PCRE2_NOTBOL
This option specifies that first character of the subject string is not
the beginning of a line, so the circumflex metacharacter should not
match before it. Setting this without having set PCRE2_MULTILINE at
compile time causes circumflex never to match. This option affects only
the behaviour of the circumflex metacharacter. It does not affect \A.
PCRE2_NOTEOL
This option specifies that the end of the subject string is not the end
of a line, so the dollar metacharacter should not match it nor (except
in multiline mode) a newline immediately before it. Setting this with-
out having set PCRE2_MULTILINE at compile time causes dollar never to
match. This option affects only the behaviour of the dollar metacharac-
ter. It does not affect \Z or \z.
PCRE2_NOTEMPTY
a?b?
PCRE2_NOTEMPTY_ATSTART
PCRE2_NO_JIT
PCRE2_NO_UTF_CHECK
The check is carried out before any other processing takes place, and a
negative error code is returned if the check fails. There are several
UTF error codes for each code unit width, corresponding to different
problems with the code unit sequence. There are discussions about the
validity of UTF-8 strings, UTF-16 strings, and UTF-32 strings in the
pcre2unicode documentation.
If you know that your subject is valid, and you want to skip this check
for performance reasons, you can set the PCRE2_NO_UTF_CHECK option when
calling pcre2_match(). You might want to do this for the second and
subsequent calls to pcre2_match() if you are making repeated calls to
find multiple matches in the same subject string.
PCRE2_PARTIAL_HARD
PCRE2_PARTIAL_SOFT
These options turn on the partial matching feature. A partial match oc-
curs if the end of the subject string is reached successfully, but
there are not enough subject characters to complete the match. In addi-
tion, either at least one character must have been inspected or the
pattern must contain a lookbehind, or the pattern must be one that
could match an empty string.
The above rule is a compromise that makes the most common cases work as
expected. For example, if the pattern is .+A (and the PCRE2_DOTALL op-
tion is not set), it does not match the string "\r\nA" because, after
failing at the start, it skips both the CR and the LF before retrying.
However, the pattern [\r\n]A does match that string, because it con-
tains an explicit CR or LF reference, and so advances only by one char-
acter after the first failure.
Notwithstanding the above, anomalous effects may still occur when CRLF
is a valid newline sequence and explicit \r or \n escapes appear in the
pattern.
Alternatively, you can make direct use of the vector of PCRE2_SIZE val-
ues, called the ovector, which contains the offsets of captured
strings. It is part of the match data block. The function
pcre2_get_ovector_pointer() returns the address of the ovector, and
pcre2_get_ovector_count() returns the number of pairs of values it con-
tains.
Within the ovector, the first in each pair of values is set to the off-
set of the first code unit of a substring, and the second is set to the
offset of the first code unit after the end of a substring. These val-
ues are always code unit offsets, not character offsets. That is, they
are byte offsets in the 8-bit library, 16-bit offsets in the 16-bit li-
brary, and 32-bit offsets in the 32-bit library.
If the ovector is too small to hold all the captured substring offsets,
as much as possible is filled in, and the function returns a value of
zero. If captured substrings are not of interest, pcre2_match() may be
called with a match data block whose ovector is of minimum length (that
is, one pair).
It is possible for capture group number n+1 to match some part of the
subject when group n has not been used at all. For example, if the
string "abc" is matched against the pattern (a|(z))(bc) the return from
the function is 4, and groups 1 and 3 are matched, but 2 is not. When
this happens, both values in the offset pairs corresponding to unused
groups are set to PCRE2_UNSET.
Offset values that correspond to unused groups at the end of the ex-
pression are also set to PCRE2_UNSET. For example, if the string "abc"
is matched against the pattern (abc)(x(yz)?)? groups 2 and 3 are not
matched. The return from the function is 2, because the highest used
capture group number is 1. The offsets for for the second and third
capture groupss (assuming the vector is large enough, of course) are
set to PCRE2_UNSET.
After a successful match, the name that is returned is the last mark
name encountered on the matching path through the pattern. Instances of
backtracking verbs without names do not count. Thus, for example, if
the matching path contains (*MARK:A)(*PRUNE), the name "A" is returned.
After a "no match" or a partial match, the last encountered name is re-
turned. For example, consider this pattern:
^(*MARK:A)((*MARK:B)a|b)c
PCRE2_ERROR_NOMATCH
PCRE2_ERROR_PARTIAL
The subject string did not match, but it did match partially. See the
pcre2partial documentation for details of partial matching.
PCRE2_ERROR_BADMAGIC
PCRE2 stores a 4-byte "magic number" at the start of the compiled code,
to catch the case when it is passed a junk pointer. This is the error
that is returned when the magic number is not present.
PCRE2_ERROR_BADMODE
PCRE2_ERROR_BADOFFSET
The value of startoffset was greater than the length of the subject.
PCRE2_ERROR_BADOPTION
PCRE2_ERROR_BADUTFOFFSET
The UTF code unit sequence that was passed as a subject was checked and
found to be valid (the PCRE2_NO_UTF_CHECK option was not set), but the
value of startoffset did not point to the beginning of a UTF character
or the end of the subject.
PCRE2_ERROR_CALLOUT
PCRE2_ERROR_DEPTHLIMIT
PCRE2_ERROR_INTERNAL
PCRE2_ERROR_JIT_STACKLIMIT
This error is returned when a pattern that was successfully studied us-
ing JIT is being matched, but the memory available for the just-in-time
processing stack is not large enough. See the pcre2jit documentation
for more details.
PCRE2_ERROR_MATCHLIMIT
PCRE2_ERROR_NOMEMORY
PCRE2_ERROR_NULL
PCRE2_ERROR_RECURSELOOP
A text message for an error code from any PCRE2 function (compile,
match, or auxiliary) can be obtained by calling pcre2_get_error_mes-
sage(). The code is passed as the first argument, with the remaining
two arguments specifying a code unit buffer and its length in code
units, into which the text message is placed. The message is returned
in code units of the appropriate width for the library that is being
used.
The returned message is terminated with a trailing zero, and the func-
tion returns the number of code units used, excluding the trailing
zero. If the error number is unknown, the negative error code PCRE2_ER-
ROR_BADDATA is returned. If the buffer is too small, the message is
truncated (but still with a trailing zero), and the negative error code
PCRE2_ERROR_NOMEMORY is returned. None of the messages are very long;
a buffer size of 120 code units is ample.
You can find the length in code units of a captured substring without
extracting it by calling pcre2_substring_length_bynumber(). The first
argument is a pointer to the match data block, the second is the group
number, and the third is a pointer to a variable into which the length
is placed. If you just want to know whether or not the substring has
been captured, you can pass the third argument as NULL.
The return value from all these functions is zero for success, or a
negative error code. If the pattern match failed, the match failure
code is returned. If a substring number greater than zero is used af-
ter a partial match, PCRE2_ERROR_PARTIAL is returned. Other possible
error codes are:
PCRE2_ERROR_NOMEMORY
PCRE2_ERROR_NOSUBSTRING
There is no substring with that number in the pattern, that is, the
number is greater than the number of capturing parentheses.
PCRE2_ERROR_UNAVAILABLE
The substring number, though not greater than the number of captures in
the pattern, is greater than the number of slots in the ovector, so the
substring could not be captured.
PCRE2_ERROR_UNSET
The substring did not participate in the match. For example, if the
pattern is (abc)|(def) and the subject is "def", and the ovector con-
tains at least two capturing slots, substring number 1 is unset.
The address of the memory block is returned via listptr, which is also
the start of the list of string pointers. The end of the list is marked
by a NULL pointer. The address of the list of lengths is returned via
lengthsptr. If your strings do not contain binary zeros and you do not
therefore need the lengths, you may supply NULL as the lengthsptr argu-
ment to disable the creation of a list of lengths. The yield of the
function is zero if all went well, or PCRE2_ERROR_NOMEMORY if the mem-
ory block could not be obtained. When the list is no longer needed, it
should be freed by calling pcre2_substring_list_free().
(a+)b(?<xxx>\d+)...
the number of the capture group called "xxx" is 2. If the name is known
to be unique (PCRE2_DUPNAMES was not set), you can find the number from
the name by calling pcre2_substring_number_from_name(). The first argu-
ment is the compiled pattern, and the second is the name. The yield of
the function is the group number, PCRE2_ERROR_NOSUBSTRING if there is
no group with that name, or PCRE2_ERROR_NOUNIQUESUBSTRING if there is
more than one group with that name. Given the number, you can extract
the substring directly from the ovector, or use one of the "bynumber"
functions described above.
The contents of the externally supplied match data block are not
changed when PCRE2_SUBSTITUTE_MATCHED is set. If PCRE2_SUBSTI-
TUTE_GLOBAL is also set, pcre2_match() is called after the first sub-
stitution to check for further matches, but this is done using an in-
ternally obtained match data block, thus always leaving the external
block unchanged.
The code argument is not used for matching before the first substitu-
tion when PCRE2_SUBSTITUTE_MATCHED is set, but it must be provided,
even when PCRE2_SUBSTITUTE_GLOBAL is not set, because it contains in-
formation such as the UTF setting and the number of capturing parenthe-
ses in the pattern.
If the function is not successful, the value set via outlengthptr de-
pends on the type of error. For syntax errors in the replacement
string, the value is the offset in the replacement string where the er-
ror was detected. For other errors, the value is PCRE2_UNSET by de-
fault. This includes the case of the output buffer being too small, un-
less PCRE2_SUBSTITUTE_OVERFLOW_LENGTH is set.
Either a group number or a group name can be given for <n>. Curly
brackets are required only if the following character would be inter-
preted as part of the number or name. The number may be zero to include
the entire matched string. For example, if the pattern a(b)c is
matched with "=abc=" and the replacement string "+$1$0$1+", the result
is "=+babcb+=".
$*MARK inserts the name from the last encountered backtracking control
verb on the matching path that has a name. (*MARK) must always include
a name, but the other verbs need not. For example, in the case of
(*MARK:A)(*PRUNE) the name inserted is "A", but for (*MARK:A)(*PRUNE:B)
the relevant name is "B". This facility can be used to perform simple
simultaneous substitutions, as this pcre2test example shows:
/(*MARK:pear)apple|(*MARK:orange)lemon/g,replace=${*MARK}
apple lemon
2: pear orange
/B/g,replace=!,use_offset_limit
ABC ABC ABC ABC\=offset=3,offset_limit=12
2: ABC A!C A!C ABC
There are also four escape sequences for forcing the case of inserted
letters. The insertion mechanism has three states: no case forcing,
force upper case, and force lower case. The escape sequences change the
current state: \U and \L change to upper or lower case forcing, respec-
tively, and \E (when not terminating a \Q quoted sequence) reverts to
no case forcing. The sequences \u and \l force the next character (if
it is a letter) to upper or lower case, respectively, and then the
state automatically reverts to no case forcing. Case forcing applies to
all inserted characters, including those from capture groups and let-
ters within \Q...\E quoted sequences. If either PCRE2_UTF or PCRE2_UCP
was set when the pattern was compiled, Unicode properties are used for
case forcing characters whose code points are greater than 127.
Note that case forcing sequences such as \U...\E do not nest. For exam-
ple, the result of processing "\Uaa\LBB\Ecc\E" is "AAbbcc"; the final
\E has no effect. Note also that the PCRE2_ALT_BSUX and PCRE2_EX-
TRA_ALT_BSUX options do not apply to replacement strings.
${<n>:-<string>}
${<n>:+<string1>:<string2>}
As before, <n> may be a group number or a name. The first form speci-
fies a default value. If group <n> is set, its value is inserted; if
not, <string> is expanded and the result inserted. The second form
specifies strings that are expanded and inserted when group <n> is set
or unset, respectively. The first form is just a convenient shorthand
for
${<n>:+${<n>}:<string>}
/(some)?(body)/substitute_extended,replace=${1:+\U:\L}HeLLo
body
1: hello
somebody
1: HELLO
The PCRE2_SUBSTITUTE_UNSET_EMPTY option does not affect these extended
substitutions. However, PCRE2_SUBSTITUTE_UNKNOWN_UNSET does cause un-
known groups in the extended syntax forms to be treated as unset.
Substitution errors
As for all PCRE2 errors, a text message that describes the error can be
obtained by calling the pcre2_get_error_message() function (see "Ob-
taining a textual error message" above).
Substitution callouts
The version field contains the version number of the block format. The
current version is 0. The version number will increase in future if
more fields are added, but the intention is never to remove any of the
existing fields.
The subscount field is the number of the current match. It is 1 for the
first callout, 2 for the second, and so on. The input and output point-
ers are copies of the values passed to pcre2_substitute().
The ovector field points to the ovector, which contains the result of
the most recent match. The oveccount field contains the number of pairs
that are set in the ovector, and is always greater than zero.
Normally, patterns that use duplicate names are such that in any one
match, only one of each set of identically-named groups participates.
An example is shown in the pcre2pattern documentation.
If you want to get full details of all captured substrings for a given
name, you must use the pcre2_substring_nametable_scan() function. The
first argument is the compiled pattern, and the second is the name. If
the third and fourth arguments are NULL, the function returns a group
number for a unique name, or PCRE2_ERROR_NOUNIQUESUBSTRING otherwise.
When the third and fourth arguments are not NULL, they must be pointers
to variables that are updated by the function. After it has run, they
point to the first and last entries in the name-to-number table for the
given name, and the function returns the length of each entry in code
units. In both cases, PCRE2_ERROR_NOSUBSTRING is returned if there are
no entries for the given name.
The format of the name table is described above in the section entitled
Information about a pattern. Given all the relevant entries for the
name, you can extract each of their numbers, and hence the captured
data.
What you have to do is to insert a callout right at the end of the pat-
tern. When your callout function is called, extract and save the cur-
rent matched substring. Then return 1, which forces pcre2_match() to
backtrack and try other alternatives. Ultimately, when it runs out of
matches, pcre2_match() will yield PCRE2_ERROR_NOMATCH.
The arguments for the pcre2_dfa_match() function are the same as for
pcre2_match(), plus two extras. The ovector within the match data block
is used in a different way, and this is described below. The other com-
mon arguments are used in the same way as for pcre2_match(), so their
description is not repeated here.
The two additional arguments provide workspace for the function. The
workspace vector should contain at least 20 elements. It is used for
keeping track of multiple paths through the pattern tree. More
workspace is needed for patterns and subjects where there are a lot of
potential matches.
int wspace[20];
pcre2_match_data *md = pcre2_match_data_create(4, NULL);
int rc = pcre2_dfa_match(
re, /* result of pcre2_compile() */
"some string", /* the subject string */
11, /* the length of the subject string */
0, /* start at offset 0 in the subject */
0, /* default options */
md, /* the match data block */
NULL, /* a match context; NULL means use defaults */
wspace, /* working space vector */
20); /* number of elements (NOT size in bytes) */
PCRE2_PARTIAL_HARD
PCRE2_PARTIAL_SOFT
These have the same general effect as they do for pcre2_match(), but
the details are slightly different. When PCRE2_PARTIAL_HARD is set for
pcre2_dfa_match(), it returns PCRE2_ERROR_PARTIAL if the end of the
subject is reached and there is still at least one matching possibility
that requires additional characters. This happens even if some complete
matches have already been found. When PCRE2_PARTIAL_SOFT is set, the
return code PCRE2_ERROR_NOMATCH is converted into PCRE2_ERROR_PARTIAL
if the end of the subject is reached, there have been no complete
matches, but there is still at least one matching possibility. The por-
tion of the string that was inspected when the longest partial match
was found is set as the first matching string in both cases. There is a
more detailed discussion of partial and multi-segment matching, with
examples, in the pcre2partial documentation.
PCRE2_DFA_SHORTEST
When pcre2_dfa_match() succeeds, it may have matched more than one sub-
string in the subject. Note, however, that all the matches from one run
of the function start at the same point in the subject. The shorter
matches are all initial substrings of the longer matches. For example,
if the pattern
<.*>
PCRE2_ERROR_DFA_UITEM
PCRE2_ERROR_DFA_UCOND
PCRE2_ERROR_DFA_UINVALID_UTF
PCRE2_ERROR_DFA_WSSIZE
PCRE2_ERROR_DFA_RECURSE
PCRE2_ERROR_DFA_BADRESTART
SEE ALSO
AUTHOR
Philip Hazel
University Computing Service
Cambridge, England.
REVISION
NAME
PCRE2 - Perl-compatible regular expressions (revised API)
BUILDING PCRE2
The rest of this document describes the optional features of PCRE2 that
can be selected when the library is compiled. It assumes use of the
configure script, where the optional features are selected or dese-
lected by providing options to configure before running the make com-
mand. However, the same options can be selected in both Unix-like and
non-Unix-like environments if you are using CMake instead of configure
to build PCRE2.
If you are not using Autotools or CMake, option selection can be done
by editing the config.h file, or by passing parameter settings to the
compiler, as described in NON-AUTOTOOLS-BUILD.
The complete list of options for configure (which includes the standard
ones such as the selection of the installation directory) can be ob-
tained by running
./configure --help
--enable-pcre2-16
--enable-pcre2-32
--disable-pcre2-8
as well. At least one of the three libraries must be built. Note that
the POSIX wrapper is for the 8-bit library only, and that pcre2grep is
an 8-bit program. Neither of these are built if you select only the
16-bit or 32-bit libraries.
The Autotools PCRE2 building process uses libtool to build both shared
and static libraries by default. You can suppress an unwanted library
by adding one of
--disable-shared
--disable-static
By default, PCRE2 is built with support for Unicode and UTF character
strings. To build it without Unicode support, add
--disable-unicode
Of itself, Unicode support does not make PCRE2 treat strings as UTF-8,
UTF-16 or UTF-32. To do that, applications that use the library can set
the PCRE2_UTF option when they call pcre2_compile() to compile a pat-
tern. Alternatively, patterns may be started with (*UTF) unless the
application has locked this out by setting PCRE2_NEVER_UTF.
The \C escape sequence, which matches a single code unit, even in a UTF
mode, can cause unpredictable behaviour because it may leave the cur-
rent matching point in the middle of a multi-code-unit character. The
application can lock it out by setting the PCRE2_NEVER_BACKSLASH_C op-
tion when calling pcre2_compile(). There is also a build-time option
--enable-never-backslash-C
(note the upper case C) which locks out the use of \C entirely.
--enable-jit
--enable-jit=auto
which enables JIT only if the current hardware is supported. You can
check if JIT is enabled in the configuration summary that is output at
the end of a configure run. If you are enabling JIT under SELinux you
may also want to add
--enable-jit-sealloc
--disable-pcre2grep-jit
NEWLINE RECOGNITION
--enable-newline-is-cr
--enable-newline-is-crlf
--enable-newline-is-anycrlf
which causes PCRE2 to recognize any of the three sequences CR, LF, or
CRLF as indicating a line ending. A fifth option, specified by
--enable-newline-is-any
--enable-newline-is-nul
WHAT \R MATCHES
--enable-bsr-anycrlf
the default is changed so that \R matches only CR, LF, or CRLF. What-
ever is selected when PCRE2 is built can be overridden by applications
that use the library.
Within a compiled pattern, offset values are used to point from one
part to another (for example, from an opening parenthesis to an alter-
nation metacharacter). By default, in the 8-bit and 16-bit libraries,
two-byte values are used for these offsets, leading to a maximum size
for a compiled pattern of around 64 thousand code units. This is suffi-
cient to handle all but the most gigantic patterns. Nevertheless, some
people do want to process truly enormous patterns, so it is possible to
compile PCRE2 to use three-byte or four-byte offsets by adding a set-
ting such as
--with-link-size=3
--with-match-limit=500000
The pcre2_match() function starts out using a 20KiB vector on the sys-
tem stack to record backtracking points. The more nested backtracking
points there are (that is, the deeper the search tree), the more memory
is needed. If the initial vector is not large enough, heap memory is
used, up to a certain limit, which is specified in kibibytes (units of
1024 bytes). The limit can be changed at run time, as described in the
pcre2api documentation. The default limit (in effect unlimited) is 20
million. You can change this by a setting such as
--with-heap-limit=500
which limits the amount of heap to 500 KiB. This limit applies only to
interpretive matching in pcre2_match() and pcre2_dfa_match(), which may
also use the heap for internal workspace when processing complicated
patterns. This limit does not apply when JIT (which has its own memory
arrangements) is used.
You can also explicitly limit the depth of nested backtracking in the
pcre2_match() interpreter. This limit defaults to the value that is set
for --with-match-limit. You can set a lower default limit by adding,
for example,
--with-match-limit_depth=10000
--enable-rebuild-chartables
If you need to create alternative tables when cross compiling, you will
have to do so "by hand". There may also be other reasons for creating
tables manually. To cause pcre2_dftables to be built on the local
host, run a normal compiling command, and then run the program with the
output file as its argument, for example:
cc src/pcre2_dftables.c -o pcre2_dftables
./pcre2_dftables src/pcre2_chartables.c
This builds the tables in the default locale of the local host. If you
want to specify a locale, you must use the -L option:
You can also specify -b (with or without -L). This causes the tables to
be written in binary instead of as source code. A set of binary tables
can be loaded into memory by an application and passed to pcre2_com-
pile() in the same way as tables created by calling pcre2_maketables().
The tables are just a string of bytes, independent of hardware charac-
teristics such as endianness. This means they can be bundled with an
application that runs in different environments, to ensure consistent
behaviour.
--enable-ebcdic --disable-unicode
It is not possible to support both EBCDIC and UTF-8 codes in the same
version of the library. Consequently, --enable-unicode and --enable-
ebcdic are mutually exclusive.
By default, pcre2grep reads all files as plain text. You can build it
so that it recognizes files whose names end in .gz or .bz2, and reads
them with libz or libbz2, respectively, by adding one or both of
--enable-pcre2grep-libz
--enable-pcre2grep-libbz2
to the configure command. These options naturally require that the rel-
evant libraries are installed on your system. Configuration will fail
if they are not.
--with-pcre2grep-bufsize=51200
--with-pcre2grep-max-bufsize=2097152
--enable-pcre2test-libreadline
--enable-pcre2test-libedit
"Readline uses the termcap functions, but does not link with
the termcap or curses library itself, allowing applications
which link with readline the to choose an appropriate library."
LIBS="-ncurses"
If you add
--enable-debug
If you add
--enable-valgrind
If your C compiler is gcc, you can build a version of PCRE2 that can
generate a code coverage report for its test suite. To enable this, you
must install lcov version 1.6 or above. Then specify
--enable-coverage
CCACHE_DISABLE=1
make coverage
This creates a fresh coverage report for the PCRE2 test suite. It is
equivalent to running "make coverage-reset", "make coverage-baseline",
"make check", and then "make coverage-report".
make coverage-reset
make coverage-baseline
make coverage-report
make coverage-clean-report
This removes the generated coverage report without cleaning the cover-
age data itself.
make coverage-clean-data
This removes the captured coverage data without removing the coverage
files created at compile time (*.gcno).
make coverage-clean
This cleans all coverage data including the generated coverage report.
For more information about code coverage, see the gcov and lcov docu-
mentation.
The C99 standard defines formatting modifiers z and t for size_t and
ptrdiff_t values, respectively. By default, PCRE2 uses these modifiers
in environments other than Microsoft Visual Studio when __STDC_VER-
SION__ is defined and has a value greater than or equal to 199901L (in-
dicating C99). However, there is at least one environment that claims
to be C99 but does not support these modifiers. If
--disable-percent-zt
There is a special option for use by people who want to run fuzzing
tests on PCRE2:
--enable-fuzz-support
OBSOLETE OPTION
--disable-stack-for-recursion
was set, memory on the heap was used. From release 10.30 onwards this
has changed (the stack is no longer used) and this option now does
nothing except give a warning.
SEE ALSO
pcre2api(3), pcre2-config(3).
AUTHOR
Philip Hazel
University Computing Service
Cambridge, England.
REVISION
NAME
PCRE2 - Perl-compatible regular expressions (revised API)
SYNOPSIS
#include <pcre2.h>
DESCRIPTION
A(?C3)B
it is processed as if it were
(?C255)A(?C3)B(?C255)
A(\d{2}|--)
(?C255)A(?C255)((?C255)\d{2}(?C255)|(?C255)-(?C255)-(?C255))(?C255)
Notice that there is a callout before and after each parenthesis and
alternation bar. If the pattern contains a conditional group whose con-
dition is an assertion, an automatic callout is inserted immediately
before the condition. Such a callout may also be inserted explicitly,
for example:
(?(?C9)(?=a)ab|de) (?(?C%text%)(?!=d)ab|de)
MISSING CALLOUTS
Auto-possessification
--->aaaa
+0 ^ a+
+2 ^ ^ [bc]
No match
--->aaaa
+0 ^ a+
+2 ^ ^ [bc]
+2 ^ ^ [bc]
+2 ^ ^ [bc]
+2 ^^ [bc]
No match
This time, when matching [bc] fails, the matcher backtracks into a+ and
tries again, repeatedly, until a+ itself fails.
Automatic .* anchoring
--->aa
+0 ^ .*
+2 ^ ^ \d
+2 ^^ \d
+2 ^ \d
No match
This shows that all match attempts start at the beginning of the sub-
ject. In other words, the pattern is anchored. You can disable this op-
timization by passing PCRE2_NO_DOTSTAR_ANCHOR to pcre2_compile(), or
starting the pattern with (*NO_DOTSTAR_ANCHOR). In this case, the out-
put changes to:
--->aa
+0 ^ .*
+2 ^ ^ \d
+2 ^^ \d
+2 ^ \d
+0 ^ .*
+2 ^^ \d
+2 ^ \d
No match
This shows more match attempts, starting at the second subject charac-
ter. Another optimization, described in the next section, means that
there is no subsequent attempt to match with an empty subject.
Other optimizations
Other optimizations that provide fast "no match" results also affect
callouts. For example, if the pattern is
ab(?C4)cd
PCRE2 knows that any matching string must contain the letter "d". If
the subject string is "abyz", the lack of "d" means that matching
doesn't ever start, and the callout is never reached. However, with
"abyd", though the result is still no match, the callout is obeyed.
For most patterns PCRE2 also knows the minimum length of a matching
string, and will immediately give a "no match" return without actually
running a match if the subject is not long enough, or, for unanchored
patterns, if it has been scanned far enough.
uint32_t version;
uint32_t callout_number;
uint32_t capture_top;
uint32_t capture_last;
uint32_t callout_flags;
PCRE2_SIZE *offset_vector;
PCRE2_SPTR mark;
PCRE2_SPTR subject;
PCRE2_SIZE subject_length;
PCRE2_SIZE start_match;
PCRE2_SIZE current_position;
PCRE2_SIZE pattern_position;
PCRE2_SIZE next_item_length;
PCRE2_SIZE callout_string_offset;
PCRE2_SIZE callout_string_length;
PCRE2_SPTR callout_string;
The version field contains the version number of the block format. The
current version is 2; the three callout string fields were added for
version 1, and the callout_flags field for version 2. If you are writ-
ing an application that might use an earlier release of PCRE2, you
should check the version number before accessing any of these fields.
The version number will increase in future if more fields are added,
but the intention is never to remove any of the existing fields.
The remaining fields in the callout block are the same for both kinds
of callout.
The capture_last field contains the number of the most recently cap-
tured substring, and the capture_top field contains one more than the
number of the highest numbered captured substring so far. If no sub-
strings have yet been captured, the value of capture_last is 0 and the
value of capture_top is 1. The values of these fields do not always
differ by one; for example, when the callout in the pattern
((a)(b))(?C2) is taken, capture_last is 1 but capture_top is 4.
For DFA matching, the offset_vector field points to the ovector that
was passed to the matching function in the match data block for call-
outs at the top level, but to an internal ovector during the processing
of pattern recursions, lookarounds, and atomic groups. However, these
ovectors hold no useful information because pcre2_dfa_match() does not
support substring capturing. The value of capture_top is always 1 and
the value of capture_last is always 0 for DFA matching.
The subject and subject_length fields contain copies of the values that
were passed to the matching function.
The start_match field normally contains the offset within the subject
at which the current match attempt started. However, if the escape se-
quence \K has been encountered, this value is changed to reflect the
modified starting point. If the pattern is not anchored, the callout
function may be called several times from the same point in the pattern
for different starting points in the subject.
PCRE2_CALLOUT_STARTMATCH
This is set for the first callout after the start of matching for each
new starting position in the subject.
PCRE2_CALLOUT_BACKTRACK
This is set if there has been a matching backtrack since the previous
callout, or since the start of matching if this is the first callout
from a pcre2_match() run.
Both bits are set when a backtrack has caused a "bumpalong" to a new
starting position in the subject. Output from pcre2test does not indi-
cate the presence of these bits unless the callout_extra modifier is
set.
CALLOUT ENUMERATION
AUTHOR
Philip Hazel
University Computing Service
Cambridge, England.
REVISION
NAME
PCRE2 - Perl-compatible regular expressions (revised API)
This document describes some of the differences in the ways that PCRE2
and Perl handle regular expressions. The differences described here are
with respect to Perl version 5.32.0, but as both Perl and PCRE2 are
continually changing, the information may at times be out of date.
4. The following Perl escape sequences are not supported: \F, \l, \L,
\u, \U, and \N when followed by a character name. \N on its own, match-
ing a non-newline character, and \N{U+dd..}, matching a Unicode code
point, are supported. The escapes that modify the case of following
letters are implemented by Perl's general string-handling and are not
part of its pattern matching engine. If any of these are encountered by
PCRE2, an error is generated by default. However, if either of the
PCRE2_ALT_BSUX or PCRE2_EXTRA_ALT_BSUX options is set, \U and \u are
interpreted as ECMAScript interprets them.
5. The Perl escape sequences \p, \P, and \X are supported only if PCRE2
is built with Unicode support (the default). The properties that can be
tested with \p and \P are limited to the general category properties
such as Lu and Nd, script names such as Greek or Han, and the derived
properties Any and L&. Both PCRE2 and Perl support the Cs (surrogate)
property, but in PCRE2 its use is limited. See the pcre2pattern docu-
mentation for details. The long synonyms for property names that Perl
supports (such as \p{Letter}) are not supported by PCRE2, nor is it
permitted to prefix any of these properties with "Is".
10. If a pattern contains more than one backtracking control verb, the
first one that is backtracked onto acts. For example, in the pattern
A(*COMMIT)B(*PRUNE)C a failure in B triggers (*COMMIT), but a failure
in C triggers (*PRUNE). Perl's behaviour is more complex; in many cases
it is the same as PCRE2, but there are cases where it differs.
11. There are some differences that are concerned with the settings of
captured strings when part of a pattern is repeated. For example,
matching "aba" against the pattern /^(a(b)?)+$/ in Perl leaves $2 un-
set, but in PCRE2 it is set to "b".
13. Perl used to recognize comments in some places that PCRE2 does not,
for example, between the ( and ? at the start of a group. If the /x
modifier is set, Perl allowed white space between ( and ? though the
latest Perls give an error (for a while it was just deprecated). There
may still be some cases where Perl behaves differently.
14. Perl, when in warning mode, gives warnings for character classes
such as [A-\d] or [a-[:digit:]]. It then treats the hyphens as liter-
als. PCRE2 has no warning features, so it gives an error in these cases
because they are almost certainly user mistakes.
16. From release 5.32.0, Perl locks out the use of \K in lookaround as-
sertions. In PCRE2, \K is acted on when it occurs in positive asser-
tions, but is ignored in negative assertions.
17. PCRE2 provides some extensions to the Perl regular expression fa-
cilities. Perl 5.10 included new features that were not in earlier
versions of Perl, some of which (such as named parentheses) were in
PCRE2 for some time before. This list is with respect to Perl 5.32:
(b) From PCRE2 10.23, backreferences to groups of fixed length are sup-
ported in lookbehinds, provided that there is no possibility of refer-
encing a non-unique number or name. Perl does not support backrefer-
ences in lookbehinds.
(h) The \R escape sequence can be restricted to match only CR, LF, or
CRLF by the PCRE2_BSR_ANYCRLF option.
18. The Perl /a modifier restricts /d numbers to pure ascii, and the
/aa modifier restricts /i case-insensitive matching to pure ascii, ig-
noring Unicode rules. This separation cannot be represented with
PCRE2_UCP.
19. Perl has different limits than PCRE2. See the pcre2limit documenta-
tion for details. Perl went with 5.10 from recursion to iteration keep-
ing the intermediate matches on the heap, which is ~10% slower but does
not fall into any stack-overflow limit. PCRE2 made a similar change at
release 10.30, and also has many build-time and run-time customizable
limits.
AUTHOR
Philip Hazel
University Computing Service
Cambridge, England.
REVISION
NAME
PCRE2 - Perl-compatible regular expressions (revised API)
To make use of the JIT support in the simplest way, all you have to do
is to 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_COM-
PLETE, PCRE2_JIT_PARTIAL_HARD, or PCRE2_JIT_PARTIAL_SOFT.
You can call pcre2_jit_compile() multiple times for the same compiled
pattern. It does nothing if it has previously compiled code for any of
the option bits. For example, you can call it once with PCRE2_JIT_COM-
PLETE and (perhaps later, when you find you need partial matching)
again with PCRE2_JIT_COMPLETE and PCRE2_JIT_PARTIAL_HARD. This time it
will ignore PCRE2_JIT_COMPLETE and just compile code for partial match-
ing. If pcre2_jit_compile() is called with no option bits set, it imme-
diately returns zero. This is an alternative way of testing whether JIT
is available.
There are some pcre2_match() options that are not supported by JIT, and
there are also some pattern items that JIT cannot handle. Details are
given below. In both cases, matching automatically falls back to the
interpretive code. If you want to know whether JIT was actually used
for a particular match, you should arrange for a JIT callback function
to be set up as described in the section entitled "Controlling the JIT
stack" below, even if you do not need to supply a non-default JIT
stack. Such a callback function is called whenever JIT code is about to
be obeyed. If the match-time options are not right for JIT execution,
the callback function is not obeyed.
The pcre2_match() options that are supported for JIT matching are
PCRE2_COPY_MATCHED_SUBJECT, PCRE2_NOTBOL, PCRE2_NOTEOL, PCRE2_NOTEMPTY,
PCRE2_NOTEMPTY_ATSTART, PCRE2_NO_UTF_CHECK, PCRE2_PARTIAL_HARD, and
PCRE2_PARTIAL_SOFT. The PCRE2_ANCHORED and PCRE2_ENDANCHORED options
are not supported at match time.
The only unsupported pattern items are \C (match a single data unit)
when running in a UTF mode, and a callout immediately before an asser-
tion condition in a conditional group.
When a pattern is matched using JIT matching, the return values are the
same as those given by the interpretive pcre2_match() code, with the
addition of one new error code: PCRE2_ERROR_JIT_STACKLIMIT. This means
that the memory used for the JIT stack was insufficient. See "Control-
ling the JIT stack" below for a discussion of JIT stack usage.
pcre2_match_context *mcontext
pcre2_jit_callback callback
void *data
You may safely use the same JIT stack for more than one pattern (either
by assigning directly or by callback), as long as the patterns are
matched sequentially in the same thread. Currently, the only way to set
up non-sequential matches in one thread is to use callouts: if a call-
out function starts another match, that match must use a different JIT
stack to the one used for currently suspended match(es).
Strictly speaking, even more is allowed. You can assign the same non-
NULL stack to a match context that is used by any number of patterns,
as long as they are not used for matching by multiple threads at the
same time. For example, you could use the same stack in all compiled
patterns, with a global mutex in the callback to wait until the stack
is available for use. However, this is an inefficient solution, and not
recommended.
Modern operating systems have a nice feature: they can reserve an ad-
dress space instead of allocating memory. We can safely allocate memory
pages inside this address space, so the stack could grow without moving
memory data (this is important because of pointers). Thus we can allo-
cate 1MiB address space, and use only a single memory page (usually
4KiB) if that is enough. However, we can still grow up to 1MiB anytime
if needed.
The owner of the stack is the user program, not the JIT studied pattern
or anything else. The user program must ensure that if a stack is being
used by pcre2_match(), (that is, it is assigned to a match context that
is passed to the pattern currently running), that stack must not be
used by any other threads (to avoid overwriting the same memory area).
The best practice for multithreaded programs is to allocate a stack for
each thread, and return this stack through the JIT callback function.
You can free a JIT stack at any time, as long as it will not be used by
pcre2_match() again. When you assign the stack to a match context, only
a pointer is set. There is no reference counting or any other magic.
You can free compiled patterns, contexts, and stacks in any order, any-
time. Just do not call pcre2_match() with a match context pointing to
an already freed stack, as that will cause SEGFAULT. (Also, do not free
a stack currently used by pcre2_match() in another thread). You can
also replace the stack in a context at any time when it is not in use.
You should free the previous stack before assigning a replacement.
(6) OK, the stack is for long term memory allocation. But what happens
if a pattern causes stack overflow with a stack of 1MiB? Is that 1MiB
kept until the stack is freed?
(7) This is too much of a headache. Isn't there any better solution for
JIT stack handling?
The JIT executable allocator does not free all memory when it is possi-
ble. It expects new allocations, and keeps some free memory around to
improve allocation speed. However, in low memory conditions, it might
be better to free all possible memory. You can cause this to happen by
calling pcre2_jit_free_unused_memory(). Its argument is a general con-
text, for custom memory management, or NULL for standard memory manage-
ment.
EXAMPLE CODE
re = pcre2_compile(pattern, PCRE2_ZERO_TERMINATED, 0,
&errornumber, &erroffset, NULL);
rc = pcre2_jit_compile(re, PCRE2_JIT_COMPLETE);
mcontext = pcre2_match_context_create(NULL);
jit_stack = pcre2_jit_stack_create(32*1024, 512*1024, NULL);
pcre2_jit_stack_assign(mcontext, NULL, jit_stack);
match_data = pcre2_match_data_create(re, 10);
rc = pcre2_match(re, subject, length, 0, 0, match_data, mcontext);
/* Process result */
pcre2_code_free(re);
pcre2_match_data_free(match_data);
pcre2_match_context_free(mcontext);
pcre2_jit_stack_free(jit_stack);
Because the API described above falls back to interpreted matching when
JIT is not available, it is convenient for programs that are written
for general use in many environments. However, calling JIT via
pcre2_match() does have a performance impact. Programs that are written
for use where JIT is known to be available, and which need the best
possible performance, can instead use a "fast path" API to call JIT
matching directly instead of calling pcre2_match() (obviously only for
patterns that have been successfully processed by pcre2_jit_compile()).
Bypassing the sanity checks and the pcre2_match() wrapping can give
speedups of more than 10%.
SEE ALSO
pcre2api(3)
AUTHOR
REVISION
NAME
PCRE2 - Perl-compatible regular expressions (revised API)
There are some size limitations in PCRE2 but it is hoped that they will
never in practice be relevant.
The maximum length (in code units) of a subject string is one less than
the largest number a PCRE2_SIZE variable can hold. PCRE2_SIZE is an un-
signed integer type, usually defined as size_t. Its maximum value (that
is ~(PCRE2_SIZE)0) is reserved as a special indicator for zero-termi-
nated strings and unset offsets.
AUTHOR
Philip Hazel
University Computing Service
Cambridge, England.
REVISION
NAME
PCRE2 - Perl-compatible regular expressions (revised API)
This document describes the two different algorithms that are available
in PCRE2 for matching a compiled regular expression against a given
subject string. The "standard" algorithm is the one provided by the
pcre2_match() function. This works in the same as as Perl's matching
function, and provide a Perl-compatible matching operation. The just-
in-time (JIT) optimization that is described in the pcre2jit documenta-
tion is compatible with this function.
When there is only one possible way in which a given subject string can
match a pattern, the two algorithms give the same answer. A difference
arises, however, when there are multiple possibilities. For example, if
the pattern
^<.*>
there are three possible answers. The standard algorithm finds only one
of them, whereas the alternative algorithm finds all three.
The set of strings that are matched by a regular expression can be rep-
resented as a tree structure. An unlimited repetition in the pattern
makes the tree of infinite size, but it is still a tree. Matching the
pattern to a given subject string (from a given starting point) can be
thought of as a search of the tree. There are two ways to search a
tree: depth-first and breadth-first, and these correspond to the two
matching algorithms provided by PCRE2.
The scan continues until either the end of the subject is reached, or
there are no more unterminated paths. At this point, terminated paths
represent the different matching possibilities (if there are none, the
match has failed). Thus, if there is more than one possible match,
this algorithm finds all of them, and in particular, it finds the long-
est. The matches are returned in decreasing order of length. There is
an option to stop the algorithm after the first match (which is neces-
sarily the shortest) is found.
Note that all the matches that are found start at the same point in the
subject. If the pattern
cat(er(pillar)?)?
1. Because the algorithm finds all possible matches, the greedy or un-
greedy nature of repetition quantifiers is not relevant (though it may
affect auto-possessification, as just described). During matching,
greedy and ungreedy quantifiers are treated in exactly the same way.
However, possessive quantifiers can make a difference when what follows
could also match what is quantified, for example in a pattern like
this:
^a++\w!
This pattern matches "aaab!" but not "aaa!", which would be matched by
a non-possessive quantifier. Similarly, if an atomic group is present,
it is matched as if it were a standalone pattern at the current point,
and the longest match is then "locked in" for the rest of the overall
pattern.
6. Because many paths through the tree may be active, the \K escape se-
quence, which resets the start of the match when encountered (but may
be on some paths and not on others), is not supported.
1. All possible matches (at a single point in the subject) are automat-
ically found, and in particular, the longest match is found. To find
more than one match using the standard algorithm, you have to do kludgy
things with callouts.
3. Although atomic groups are supported, their use does not provide the
performance advantage that it does for the standard algorithm.
AUTHOR
Philip Hazel
University Computing Service
Cambridge, England.
REVISION
NAME
PCRE2 - Perl-compatible regular expressions
PCRE2_JIT_PARTIAL_HARD
PCRE2_JIT_PARTIAL_SOFT
A possible partial match occurs during matching when the end of the
subject string is reached successfully, but either more characters are
needed to complete the match, or the addition of more characters might
change what is matched.
Example 1: if the pattern is /abc/ and the subject is "ab", more char-
acters are definitely needed to complete a match. In this case both
hard and soft matching options yield a partial match.
(2) The pattern contains one or more lookbehind assertions. This condi-
tion exists in case there is a lookbehind that inspects characters be-
fore the start of the match.
(3) There is a special case when the whole pattern can match an empty
string. When the starting point is at the end of the subject, the
empty string match is a possibility, and if PCRE2_PARTIAL_SOFT is set
and neither of the above conditions is true, it is returned. However,
because adding more characters might result in a non-empty match,
PCRE2_PARTIAL_HARD returns a partial match, which in this case means
"there is going to be a match at this point, but until some more char-
acters are added, we do not know if it will be an empty string or some-
thing longer".
A successful match
A complete match has been found, starting and ending within this sub-
ject.
PCRE2_ERROR_NOMATCH
No match can start anywhere in this subject.
PCRE2_ERROR_PARTIAL
Adding more characters may result in a complete match that uses one
or more characters from the end of this subject.
When a partial match is returned, the first two elements in the ovector
point to the portion of the subject that was matched, but the values in
the rest of the ovector are undefined. The appearance of \K in the pat-
tern has no effect for a partial match. Consider this pattern:
/abc\K123/
If there is more than one partial match, the first one that was found
provides the data that is returned. Consider this pattern:
/123\w+X|dogY/
The difference between the two partial matching options can be illus-
trated by a pattern such as:
/dog(sbody)?/
/dog(sbody)??/
The second pattern will never match "dogsbody", because it will always
find the shorter match first.
The pcre2test data modifiers partial_hard (or ph) and partial_soft (or
ps) set PCRE2_PARTIAL_HARD and PCRE2_PARTIAL_SOFT, respectively, when
calling pcre2_match(). Here is a run of pcre2test using a pattern that
matches the whole subject in the form of a date:
re> /^\d?\d(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d\d$/
data> 25dec3\=ph
Partial match: 23dec3
data> 3ju\=ph
Partial match: 3ju
data> 3juj\=ph
No match
This example gives the same results for both hard and soft partial
matching options. Here is an example where there is a difference:
re> /^\d?\d(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d\d$/
data> 25jun04\=ps
0: 25jun04
1: jun
data> 25jun04\=ph
Partial match: 25jun04
When a partial match occurs, the next segment must be added to the cur-
rent subject and the match re-run, using the startoffset argument of
pcre2_match() to begin at the point where the partial match started.
For example:
re> /\d?\d(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d\d/
data> ...the date is 23ja\=ph
Partial match: 23ja
data> ...the date is 23jan19 and on that day...\=offset=15
0: 23jan19
1: jan
Note the use of the offset modifier to start the new match where the
partial match was found. In this example, the next segment was added to
the one in which the partial match was found. This is the most
straightforward approach, typically using a memory buffer that is twice
the size of each segment. After a partial match, the first half of the
buffer is discarded, the second half is moved to the start of the buf-
fer, and a new segment is added before repeating the match as in the
example above. After a no match, the entire buffer can be discarded.
If there are memory constraints, you may want to discard text that pre-
cedes a partial match before adding the next segment. Unfortunately,
this is not at present straightforward. In cases such as the above,
where the pattern does not contain any lookbehinds, it is sufficient to
retain only the partially matched substring. However, if the pattern
contains a lookbehind assertion, characters that precede the start of
the partial match may have been inspected during the matching process.
When pcre2test displays a partial match, it indicates these characters
with '<' if the allusedtext modifier is set:
re> "(?<=123)abc"
data> xx123ab\=ph,allusedtext
Partial match: 123ab
<<<
If you know the approximate length of the matching substrings, you can
use that to decide how much text to retain. The only lookbehind infor-
mation that is currently available via the API is the length of the
longest individual lookbehind in a pattern, but this can be misleading
if there are nested lookbehinds. The value returned by calling
pcre2_pattern_info() with the PCRE2_INFO_MAXLOOKBEHIND option is the
maximum number of characters (not code units) that any individual look-
behind moves back when it is processed. A pattern such as
"(?<=(?<!b)a)" has a maximum lookbehind value of one, but inspects two
characters before its starting point.
The DFA function moves along the subject string character by character,
without backtracking, searching for all possible matches simultane-
ously. If the end of the subject is reached before the end of the pat-
tern, there is the possibility of a partial match.
Because the DFA function always searches for all possible matches, and
there is no difference between greedy and ungreedy repetition, its be-
haviour is different from the pcre2_match(). Consider the string "dog"
matched against this ungreedy pattern:
/dog(sbody)??/
When a partial match has been found using the DFA matching function, it
is possible to continue the match by providing additional subject data
and calling the function again with the same compiled regular expres-
sion, this time setting the PCRE2_DFA_RESTART option. You must pass the
same working space as before, because this is where details of the pre-
vious partial match are stored. You can set the PCRE2_PARTIAL_SOFT or
PCRE2_PARTIAL_HARD options with PCRE2_DFA_RESTART to continue partial
matching over multiple segments. Here is an example using pcre2test:
re> /^\d?\d(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d\d$/
data> 23ja\=dfa,ps
Partial match: 23ja
data> n05\=dfa,dfa_restart
0: n05
The first call has "23ja" as the subject, and requests partial match-
ing; the second call has "n05" as the subject for the continued
(restarted) match. Notice that when the match is complete, only the
last part is shown; PCRE2 does not retain the previously partially-
matched string. It is up to the calling program to do that if it needs
to. This means that, for an unanchored pattern, if a continued match
fails, it is not possible to try again at a new starting point. All
this facility is capable of doing is continuing with the previous match
attempt. For example, consider this pattern:
1234|3789
If you do want to allow for starting again at the next character, one
way of doing it is to retain some or all of the segment and try a new
complete match, as described for pcre2_match() above. Another possibil-
ity is to work with two buffers. If a partial match at offset n in the
first buffer is followed by "no match" when PCRE2_DFA_RESTART is used
on the second buffer, you can then try a new match starting at offset
n+1 in the first buffer.
AUTHOR
Philip Hazel
University Computing Service
Cambridge, England.
REVISION
NAME
PCRE2 - Perl-compatible regular expressions (revised API)
The syntax and semantics of the regular expressions that are supported
by PCRE2 are described in detail below. There is a quick-reference syn-
tax summary in the pcre2syntax page. PCRE2 tries to match Perl syntax
and semantics as closely as it can. PCRE2 also supports some alterna-
tive regular expression syntax (which does not conflict with the Perl
syntax) in order to provide some compatibility with regular expressions
in Python, .NET, and Oniguruma.
This document discusses the regular expression patterns that are sup-
ported by PCRE2 when its main matching function, pcre2_match(), is
used. PCRE2 also has an alternative matching function,
pcre2_dfa_match(), which matches using a different algorithm that is
not Perl-compatible. Some of the features discussed below are not
available when DFA matching is used. The advantages and disadvantages
of the alternative function, and how it differs from the normal func-
tion, are discussed in the pcre2matching page.
UTF support
In the 8-bit and 16-bit PCRE2 libraries, characters may be coded either
as single code units, or as multiple UTF-8 or UTF-16 code units. UTF-32
can be specified for the 32-bit library, in which case it constrains
the character values to valid Unicode code points. To process UTF
strings, PCRE2 must be built to include Unicode support (which is the
default). When using UTF strings you must either call the compiling
function with one or both of the PCRE2_UTF or PCRE2_MATCH_INVALID_UTF
options, or the pattern must start with the special sequence (*UTF),
which is equivalent to setting the relevant PCRE2_UTF. How setting a
UTF mode affects pattern matching is mentioned in several places below.
There is also a summary of features in the pcre2unicode page.
Some applications that allow their users to supply patterns may wish to
restrict them to non-UTF data for security reasons. If the
PCRE2_NEVER_UTF option is passed to pcre2_compile(), (*UTF) is not al-
lowed, and its appearance in a pattern causes an error.
Some applications that allow their users to supply patterns may wish to
restrict them for security reasons. If the PCRE2_NEVER_UCP option is
passed to pcre2_compile(), (*UCP) is not allowed, and its appearance in
a pattern causes an error.
Disabling auto-possessification
These facilities are provided to catch runaway matches that are pro-
voked by patterns with huge matching trees. A common example is a pat-
tern with nested unlimited repeats applied to a long string that does
not match. When one of these limits is reached, pcre2_match() gives an
error return. The limits can also be set by items at the start of the
pattern of the form
(*LIMIT_HEAP=d)
(*LIMIT_MATCH=d)
(*LIMIT_DEPTH=d)
where d is any number of decimal digits. However, the value of the set-
ting must be less than the value set (or defaulted) by the caller of
pcre2_match() for it to have any effect. In other words, the pattern
writer can lower the limits set by the programmer, but not raise them.
If there is more than one setting of one of these limits, the lower
value is used. The heap limit is specified in kibibytes (units of 1024
bytes).
Newline conventions
These override the default and the options given to the compiling func-
tion. For example, on a Unix system where LF is the default newline se-
quence, the pattern
(*CR)a.b
The newline convention affects where the circumflex and dollar asser-
tions are true. It also affects the interpretation of the dot metachar-
acter when PCRE2_DOTALL is not set, and the behaviour of \N when not
followed by an opening brace. However, it does not affect what the \R
escape sequence matches. By default, this is any Unicode newline se-
quence, for Perl compatibility. However, this can be changed; see the
next section and the description of \R in the section entitled "Newline
sequences" below. A change of \R setting can be combined with a change
of newline convention.
The power of regular expressions comes from the ability to include wild
cards, character classes, alternatives, and repetitions in the pattern.
These are encoded in the pattern by the use of metacharacters, which do
not stand for themselves but instead are interpreted in some special
way.
There are two different sets of metacharacters: those that are recog-
nized anywhere in the pattern except within square brackets, and those
that are recognized within square brackets. Outside square brackets,
the metacharacters are as follows:
BACKSLASH
Only ASCII digits and letters have any special meaning after a back-
slash. All other characters (in particular, those whose code points are
greater than 127) are treated as literals.
Non-printing characters
Characters whose code points are less than 256 can be defined by either
of the two syntaxes for \x or by an octal sequence. There is no differ-
ence in the way they are handled. For example, \xdc is exactly the same
as \x{dc} or \334. However, using the braced versions does make such
sequences easier to read.
There are some legacy applications where the escape sequence \r is ex-
pected to match a newline. If the PCRE2_EXTRA_ESCAPED_CR_IS_LF option
is set, \r in a pattern is converted to \n so that it matches a LF
(linefeed) instead of a CR (carriage return) character.
Thus, apart from \c?, these escapes generate the same character code
values as they do in an ASCII environment, though the meanings of the
values mostly differ. For example, \cG always generates code value 7,
which is BEL in ASCII but DEL in EBCDIC.
The sequence \c? generates DEL (127, hex 7F) in an ASCII environment,
but because 127 is not a control character in EBCDIC, Perl makes it
generate the APC character. Unfortunately, there are several variants
of EBCDIC. In most of them the APC character has the value 255 (hex
FF), but in the one Perl calls POSIX-BC its value is 95 (hex 5F). If
certain other characters have POSIX-BC values, PCRE2 makes \c? generate
95; otherwise it generates 255.
After \0 up to two further octal digits are read. If there are fewer
than two digits, just those that are present are used. Thus the se-
quence \0\x\015 specifies two binary zeros followed by a CR character
(code value 13). Make sure you supply two digits after the initial zero
if the pattern character that follows is itself an octal digit.
Note that octal values of 100 or greater that are specified using this
syntax must not be introduced by a leading zero, because no more than
three octal digits are ever read.
Invalid Unicode code points are all those in the range 0xd800 to 0xdfff
(the so-called "surrogate" code points). The check for these can be
disabled by the caller of pcre2_compile() by setting the option
PCRE2_EXTRA_ALLOW_SURROGATE_ESCAPES. However, this is possible only in
UTF-8 and UTF-32 modes, because these values are not representable in
UTF-16.
All the sequences that define a single character value can be used both
inside and outside character classes. In addition, inside a character
class, \b is interpreted as the backspace character (hex 08).
In Perl, the sequences \F, \l, \L, \u, and \U are recognized by its
string handler and used to modify the case of following characters. By
default, PCRE2 does not support these escape sequences in patterns.
However, if either of the PCRE2_ALT_BSUX or PCRE2_EXTRA_ALT_BSUX op-
tions is set, \U matches a "U" character, and \u can be used to define
a character by code point, as described above.
The \N escape sequence has the same meaning as the "." metacharacter
when PCRE2_DOTALL is not set, but setting PCRE2_DOTALL does not change
the meaning of \N. Note that when \N is followed by an opening brace it
has a different meaning. See the section entitled "Non-printing charac-
ters" above for details. Perl also uses \N{name} to specify characters
by Unicode name; PCRE2 does not support this.
Each pair of lower and upper case escape sequences partitions the com-
plete set of characters into two disjoint sets. Any given character
matches one, and only one, of each pair. The sequences can appear both
inside and outside character classes. They each match one character of
the appropriate type. If the current matching point is at the end of
the subject string, all of them fail, because there is no character to
match.
By default, characters whose code points are greater than 127 never
match \d, \s, or \w, and always match \D, \S, and \W, although this may
be different for characters in the range 128-255 when locale-specific
matching is happening. These escape sequences retain their original
meanings from before Unicode support was available, mainly for effi-
ciency reasons. If the PCRE2_UCP option is set, the behaviour is
changed so that Unicode properties are used to determine character
types, as follows:
The upper case escapes match the inverse sets of characters. Note that
\d matches only decimal digits, whereas \w matches any Unicode digit,
as well as any Unicode letter, and underscore. Note also that PCRE2_UCP
affects \b, and \B because they are defined in terms of \w and \W.
Matching these sequences is noticeably slower when PCRE2_UCP is set.
The sequences \h, \H, \v, and \V, in contrast to the other sequences,
which match only ASCII characters by default, always match a specific
list of code points, whether or not PCRE2_UCP is set. The horizontal
space characters are:
In 8-bit, non-UTF-8 mode, only the characters with code points less
than 256 are relevant.
Newline sequences
(?>\r\n|\n|\x0b|\f|\r|\x85)
In other modes, two additional characters whose code points are greater
than 255 are added: LS (line separator, U+2028) and PS (paragraph sepa-
rator, U+2029). Unicode support is not needed for these characters to
be recognized.
These override the default and the options given to the compiling func-
tion. Note that these special settings, which are not Perl-compatible,
are recognized only at the very start of a pattern, and that they must
be in upper case. If more than one of them is present, the last one is
used. They can be combined with a change of newline convention; for ex-
ample, a pattern can start with:
(*ANY)(*BSR_ANYCRLF)
They can also be combined with the (*UTF) or (*UCP) special sequences.
Inside a character class, \R is treated as an unrecognized escape se-
quence, and causes an error.
When PCRE2 is built with Unicode support (the default), three addi-
tional escape sequences that match characters with specific properties
are available. They can be used in any mode, though in 8-bit and 16-bit
non-UTF modes these sequences are of course limited to testing charac-
ters whose code points are less than U+0100 and U+10000, respectively.
In 32-bit non-UTF mode, code points greater than 0x10ffff (the Unicode
limit) may be encountered. These are all treated as being in the Un-
known script and with an unassigned type. The extra escape sequences
are:
\p{Greek}
\P{Han}
If only one letter is specified with \p or \P, it includes all the gen-
eral category properties that start with that letter. In this case, in
the absence of negation, the curly brackets in the escape sequence are
optional; these two examples have the same effect:
\p{L}
\pL
C Other
Cc Control
Cf Format
Cn Unassigned
Co Private use
Cs Surrogate
L Letter
Ll Lower case letter
Lm Modifier letter
Lo Other letter
Lt Title case letter
Lu Upper case letter
M Mark
Mc Spacing mark
Me Enclosing mark
Mn Non-spacing mark
N Number
Nd Decimal number
Nl Letter number
No Other number
P Punctuation
Pc Connector punctuation
Pd Dash punctuation
Pe Close punctuation
Pf Final punctuation
Pi Initial punctuation
Po Other punctuation
Ps Open punctuation
S Symbol
Sc Currency symbol
Sk Modifier symbol
Sm Mathematical symbol
So Other symbol
Z Separator
Zl Line separator
Zp Paragraph separator
Zs Space separator
The special property L& is also supported: it matches a character that
has the Lu, Ll, or Lt property, in other words, a letter that is not
classified as a modifier or "other".
The long synonyms for property names that Perl supports (such as
\p{Letter}) are not supported by PCRE2, nor is it permitted to prefix
any of these properties with "Is".
2. Do not end between CR and LF; otherwise end after any control char-
acter.
7. Do not break within emoji flag sequences. That is, do not break be-
tween regional indicator (RI) characters if there are an odd number of
RI characters before the break point.
Xan matches characters that have either the L (letter) or the N (num-
ber) property. Xps matches the characters tab, linefeed, vertical tab,
form feed, or carriage return, and any other character that has the Z
(separator) property. Xsp is the same as Xps; in PCRE1 it used to ex-
clude vertical tab, for Perl compatibility, but Perl changed. Xwd
matches the same characters as Xan, plus underscore.
foo\Kbar
matches "foobar", but reports that it has matched "bar". \K does not
interact with anchoring in any way. The pattern:
^foo\Kbar
matches only when the subject begins with "foobar" (in single line
mode), though it again reports the matched string as "bar". This fea-
ture is similar to a lookbehind assertion (described below). However,
in this case, the part of the subject before the real match does not
have to be of fixed length, as lookbehind assertions do. The use of \K
does not interfere with the setting of captured substrings. For exam-
ple, when the pattern
(foo)\Kbar
(?<=\Kfoo)bar
Simple assertions
The \A, \Z, and \z assertions differ from the traditional circumflex
and dollar (described in the next section) in that they only ever match
at the very start and end of the subject string, whatever options are
set. Thus, they are independent of multiline mode. These three asser-
tions are not affected by the PCRE2_NOTBOL or PCRE2_NOTEOL options,
which affect only the behaviour of the circumflex and dollar metachar-
acters. However, if the startoffset argument of pcre2_match() is non-
zero, indicating that matching is to start at a point other than the
beginning of the subject, \A can never match. The difference between
\Z and \z is that \Z matches before a newline at the end of the string
as well as at the very end, whereas \z matches only at the end.
For example, the pattern /^abc$/ matches the subject string "def\nabc"
(where \n represents a newline) in multiline mode, but not otherwise.
Consequently, patterns that are anchored in single line mode because
all branches start with ^ are not anchored in multiline mode, and a
match for circumflex is possible when the startoffset argument of
pcre2_match() is non-zero. The PCRE2_DOLLAR_ENDONLY option is ignored
if PCRE2_MULTILINE is set.
Note that the sequences \A, \Z, and \z can be used to match the start
and end of the subject in both modes, and if all branches of a pattern
start with \A it is always anchored, whether or not PCRE2_MULTILINE is
set.
Outside a character class, a dot in the pattern matches any one charac-
ter in the subject string except (by default) a character that signi-
fies the end of a line.
Outside a character class, the escape sequence \C matches any one code
unit, whether or not a UTF mode is set. In the 8-bit library, one code
unit is one byte; in the 16-bit library it is a 16-bit unit; in the
32-bit library it is a 32-bit unit. Unlike a dot, \C always matches
line-ending characters. The feature is provided in Perl in order to
match individual bytes in UTF-8 mode, but it is unclear how it can use-
fully be used.
(?| (?=[\x00-\x7f])(\C) |
(?=[\x80-\x{7ff}])(\C)(\C) |
(?=[\x{800}-\x{ffff}])(\C)(\C)(\C) |
(?=[\x{10000}-\x{1fffff}])(\C)(\C)(\C)(\C))
In this example, a group that starts with (?| resets the capturing
parentheses numbers in each alternative (see "Duplicate Group Numbers"
below). The assertions at the start of each branch check the next UTF-8
character for values whose encoding uses 1, 2, 3, or 4 bytes, respec-
tively. The character's individual bytes are then captured by the ap-
propriate number of \C groups.
For example, the character class [aeiou] matches any lower case vowel,
while [^aeiou] matches any character that is not a lower case vowel.
Note that a circumflex is just a convenient notation for specifying the
characters that are in the class by enumerating those that are not. A
class that starts with a circumflex is not an assertion; it still con-
sumes a character from the subject string, and therefore it fails if
the current pointer is at the end of the string.
Characters that might indicate line breaks are never treated in any
special way when matching character classes, whatever line-ending se-
quence is in use, and whatever setting of the PCRE2_DOTALL and
PCRE2_MULTILINE options is used. A class such as [^a] always matches
one of these characters.
The generic character type escape sequences \d, \D, \h, \H, \p, \P, \s,
\S, \v, \V, \w, and \W may appear in a character class, and add the
characters that they match to the class. For example, [\dABCDEF]
matches any hexadecimal digit. In UTF modes, the PCRE2_UCP option af-
fects the meanings of \d, \s, \w and their upper case partners, just as
it does when they appear outside a character class, as described in the
section entitled "Generic character types" above. The escape sequence
\b has a different meaning inside a character class; it matches the
backspace character. The sequences \B, \R, and \X are not special in-
side a character class. Like any other unrecognized escape sequences,
they cause an error. The same is true for \N when not followed by an
opening brace.
It is not possible to have the literal character "]" as the end charac-
ter of a range. A pattern such as [W-]46] is interpreted as a class of
two characters ("W" and "-") followed by a literal string "46]", so it
would match "W46]" or "-46]". However, if the "]" is escaped with a
backslash it is interpreted as the end of range, so [W-\]46] is inter-
preted as a class containing a range followed by two other characters.
The octal or hexadecimal representation of "]" can also be used to end
a range.
Ranges normally include all code points between the start and end char-
acters, inclusive. They can also be used for code points specified nu-
merically, for example [\000-\037]. Ranges can include any characters
that are valid for the current mode. In any UTF mode, the so-called
"surrogate" characters (those whose code points lie between 0xd800 and
0xdfff inclusive) may not be specified explicitly by default (the
PCRE2_EXTRA_ALLOW_SURROGATE_ESCAPES option disables this check). How-
ever, ranges such as [\x{d7ff}-\x{e000}], which include the surrogates,
are always permitted.
Perl supports the POSIX notation for character classes. This uses names
enclosed by [: and :] within the enclosing square brackets. PCRE2 also
supports this notation. For example,
[01[:alpha:]%]
matches "0", "1", any alphabetic character, or "%". The supported class
names are:
[12[:^digit:]]
matches "1", "2", or any non-digit. PCRE2 (and Perl) also recognize the
POSIX syntax [.ch.] and [=ch=] where "ch" is a "collating element", but
these are not supported, and an error is given if they are encountered.
By default, characters with values greater than 127 do not match any of
the POSIX character classes, although this may be different for charac-
ters in the range 128-255 when locale-specific matching is happening.
However, if the PCRE2_UCP option is passed to pcre2_compile(), some of
the classes are changed so that Unicode character properties are used.
This is achieved by replacing certain POSIX classes with other se-
quences, as follows:
[:alnum:] becomes \p{Xan}
[:alpha:] becomes \p{L}
[:blank:] becomes \h
[:cntrl:] becomes \p{Cc}
[:digit:] becomes \p{Nd}
[:lower:] becomes \p{Ll}
[:space:] becomes \p{Xps}
[:upper:] becomes \p{Lu}
[:word:] becomes \p{Xwd}
[:graph:] This matches characters that have glyphs that mark the page
when printed. In Unicode property terms, it matches all char-
acters with the L, M, N, P, S, or Cf properties, except for:
[:punct:] This matches all characters that have the Unicode P (punctua-
tion) property, plus those characters with code points less
than 256 that have the S (Symbol) property.
The other POSIX classes are unchanged, and match only characters with
code points less than 256.
In the POSIX.2 compliant library that was included in 4.4BSD Unix, the
ugly syntax [[:<:]] and [[:>:]] is used for matching "start of word"
and "end of word". PCRE2 treats these items as follows:
VERTICAL BAR
i for PCRE2_CASELESS
m for PCRE2_MULTILINE
n for PCRE2_NO_AUTO_CAPTURE
s for PCRE2_DOTALL
x for PCRE2_EXTENDED
xx for PCRE2_EXTENDED_MORE
When one of these option changes occurs at top level (that is, not in-
side group parentheses), the change applies to the remainder of the
pattern that follows. An option change within a group (see below for a
description of groups) affects only that part of the group that follows
it, so
(a(?i)b)c
(a(?i)b|c)
matches "ab", "aB", "c", and "C", even though when matching "C" the
first branch is abandoned before the option setting. This is because
the effects of option settings happen at compile time. There would be
some very weird behaviour otherwise.
(?i:saturday|sunday)
(?:(?i)saturday|sunday)
GROUPS
cat(aract|erpillar|)
2. It creates a "capture group". This means that, when the whole pat-
tern matches, the portion of the subject string that matched the group
is passed back to the caller, separately from the portion that matched
the whole pattern. (This applies only to the traditional matching
function; the DFA matching function does not support capturing.)
the captured substrings are "red king", "red", and "king", and are num-
bered 1, 2, and 3, respectively.
The fact that plain parentheses fulfil two functions is not always
helpful. There are often times when grouping is required without cap-
turing. If an opening parenthesis is followed by a question mark and a
colon, the group does not do any capturing, and is not counted when
computing the number of any subsequent capture groups. For example, if
the string "the white queen" is matched against the pattern
the captured substrings are "white queen" and "queen", and are numbered
1 and 2. The maximum number of capture groups is 65535.
(?i:saturday|sunday)
(?:(?i)saturday|sunday)
match exactly the same set of strings. Because alternative branches are
tried from left to right, and options are not reset until the end of
the group is reached, an option setting in one branch does affect sub-
sequent branches, so the above patterns match "SUNDAY" as well as "Sat-
urday".
(?|(Sat)ur|(Sun))day
Because the two alternatives are inside a (?| group, both sets of cap-
turing parentheses are numbered one. Thus, when the pattern matches,
you can look at captured substring number one, whichever alternative
matched. This construct is useful when you want to capture part, but
not all, of one of a number of alternatives. Inside a (?| group, paren-
theses are numbered as usual, but the number is reset at the start of
each branch. The numbers of any capturing parentheses that follow the
whole group start after the highest number used in any branch. The fol-
lowing example is taken from the Perl documentation. The numbers under-
neath show in which buffer the captured content will be stored.
/(?|(abc)|(def))\1/
Warning: When more than one capture group has the same number, as de-
scribed in the previous section, a name given to one of them applies to
all of them. Perl allows identically numbered groups to have different
names. Consider this pattern, where there are two capture groups, both
numbered 1:
(?|(?<AA>aa)|(?<BB>bb))
In an attempt to reduce confusion, PCRE2 does not allow the same group
number to be associated with more than one name. The example above pro-
vokes a compile-time error. However, there is still scope for confu-
sion. Consider this pattern:
(?|(?<AA>aa)|(bb))
Although the second group number 1 is not explicitly named, the name AA
is still an alias for any group 1. Whether the pattern matches "aa" or
"bb", a reference by name to group AA yields the matched string.
(?|(?<AA>aa)|(?<AA>bb))
Duplicate names can be useful for patterns where only one instance of
the named capture group can match. Suppose you want to match the name
of a weekday, either as a 3-letter abbreviation or as the full name,
and in both cases you want to extract the abbreviation. This pattern
(ignoring the line breaks) does the job:
(?J)
(?<DN>Mon|Fri|Sun)(?:day)?|
(?<DN>Tue)(?:sday)?|
(?<DN>Wed)(?:nesday)?|
(?<DN>Thu)(?:rsday)?|
(?<DN>Sat)(?:urday)?
There are five capture groups, but only one is ever set after a match.
The convenience functions for extracting the data by name returns the
substring for the first (and in this example, the only) group of that
name that matched. This saves searching to find which numbered group it
was. (An alternative way of solving this problem is to use a "branch
reset" group, as described in the previous section.)
(?J)(?:(?<n>foo)|(?<n>bar))\k<n>
If you make a subroutine call to a non-unique named group, the one that
corresponds to the first occurrence of the name is used. In the absence
of duplicate numbers this is the one with the lowest number.
If you use a named reference in a condition test (see the section about
conditions below), either to check whether a capture group has matched,
or to check for recursion, all groups with the same name are tested. If
the condition is true for any one of them, the overall condition is
true. This is the same behaviour as testing by number. For further de-
tails of the interfaces for handling named capture groups, see the
pcre2api documentation.
REPETITION
z{2,4}
[aeiou]{3,}
matches at least 3 successive vowels, but may match many more, whereas
\d{8}
(a?)*
/\*.*\*/
to the string
/\*.*?\*/
does the right thing with the C comments. The meaning of the various
quantifiers is not otherwise changed, just the preferred number of
matches. Do not confuse this use of question mark with its use as a
quantifier in its own right. Because it has two uses, it can sometimes
appear doubled, as in
\d??\d
which matches one digit by preference, but can match two if that is the
only way the rest of the pattern matches.
However, there are some cases where the optimization cannot be used.
When .* is inside capturing parentheses that are the subject of a
backreference elsewhere in the pattern, a match at the start may fail
where a later one succeeds. Consider, for example:
(.*)abc\1
Another case where implicit anchoring is not applied is when the lead-
ing .* is inside an atomic group. Once again, a match at the start may
fail where a later one succeeds. Consider this pattern:
(?>.*?a)b
It matches "ab" in the subject "aab". The use of the backtracking con-
trol verbs (*PRUNE) and (*SKIP) also disable this optimization, and
there is an option, PCRE2_NO_DOTSTAR_ANCHOR, to do so explicitly.
(tweedle[dume]{3}\s*)+
(a|(b))+
Consider, for example, the pattern \d+foo when applied to the subject
line
123456bar
After matching all 6 digits and then failing to match "foo", the normal
action of the matcher is to try again with only 5 digits matching the
\d+ item, and then with 4, and so on, before ultimately failing.
"Atomic grouping" (a term taken from Jeffrey Friedl's book) provides
the means for specifying that once a group has matched, it is not to be
re-evaluated in this way.
If we use atomic grouping for the previous example, the matcher gives
up immediately on failing to match "foo" the first time. The notation
is a kind of special parenthesis, starting with (?> as in this example:
(?>\d+)foo
(*atomic:\d+)foo
This kind of parenthesized group "locks up" the part of the pattern it
contains once it has matched, and a failure further into the pattern is
prevented from backtracking into it. Backtracking past it to previous
items, however, works as normal.
Atomic groups are not capture groups. Simple cases such as the above
example can be thought of as a maximizing repeat that must swallow ev-
erything it can. So, while both \d+ and \d+? are prepared to adjust
the number of digits they match in order to make the rest of the pat-
tern match, (?>\d+) can only match an entire sequence of digits.
\d++foo
Note that a possessive quantifier can be used with an entire group, for
example:
(abc|xyz){2,3}+
When a pattern contains an unlimited repeat inside a group that can it-
self be repeated an unlimited number of times, the use of an atomic
group is the only way to avoid some failing matches taking a very long
time indeed. The pattern
(\D+|<\d+>)*[!?]
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
((?>\D+)|<\d+>)*[!?]
BACKREFERENCES
(ring), \1
(ring), \g1
(ring), \g{1}
(abc(def)ghi)\g{-1}
The sequence \g{+1} is a reference to the next capture group. This kind
of forward reference can be useful in patterns that repeat. Perl does
not support the use of + in this way.
((?i)rah)\s+\1
matches "rah rah" and "RAH RAH", but not "RAH rah", even though the
original capture group is matched caselessly.
(?<p1>(?i)rah)\s+\k<p1>
(?'p1'(?i)rah)\s+\k{p1}
(?P<p1>(?i)rah)\s+(?P=p1)
(?<p1>(?i)rah)\s+\g{p1}
A capture group that is referenced by name may appear in the pattern
before or after the reference.
There may be more than one backreference to the same group. If a group
has not actually been used in a particular match, backreferences to it
always fail by default. For example, the pattern
(a|(bc))\2
Because there may be many capture groups in a pattern, all digits fol-
lowing a backslash are taken as part of a potential backreference num-
ber. If the pattern continues with a digit character, some delimiter
must be used to terminate the backreference. If the PCRE2_EXTENDED or
PCRE2_EXTENDED_MORE option is set, this can be white space. Otherwise,
the \g{} syntax or an empty comment (see "Comments" below) can be used.
Recursive backreferences
(a|b\1)+
matches any number of "a"s and also "aba", "ababbaa" etc. At each iter-
ation of the group, the backreference matches the character string cor-
responding to the previous iteration. In order for this to work, the
pattern must be such that the first iteration does not need to match
the backreference. This can be done using alternation, as in the exam-
ple above, or by a quantifier with a minimum of zero.
For versions of PCRE2 less than 10.25, backreferences of this type used
to cause the group that they reference to be treated as an atomic
group. This restriction no longer applies, and backtracking into such
groups can occur as normal.
ASSERTIONS
Traditionally, symbolic sequences such as (?= and (?<= have been used
to specify lookaround assertions. Perl 5.28 introduced some experimen-
tal alphabetic alternatives which might be easier to remember. They all
start with (* instead of (? and must be written using lower case let-
ters. PCRE2 supports the following synonyms:
Lookahead assertions start with (?= for positive assertions and (?! for
negative assertions. For example,
\w+(?=;)
matches a word followed by a semicolon, but does not include the semi-
colon in the match, and
foo(?!bar)
(?!foo)bar
Lookbehind assertions
Lookbehind assertions start with (?<= for positive assertions and (?<!
for negative assertions. For example,
(?<!foo)bar
(?<=bullock|donkey)
is permitted, but
(?<!dogs?|cats?)
(?<=ab(c|de))
is not permitted, because its single top-level branch can match two
different lengths, but it is acceptable to PCRE2 if rewritten to use
two top-level branches:
(?<=abc|abde)
In some cases, the escape sequence \K (see above) can be used instead
of a lookbehind assertion to get round the fixed-length restriction.
In UTF-8 and UTF-16 modes, PCRE2 does not allow the \C escape (which
matches a single code unit even in a UTF mode) to appear in lookbehind
assertions, because it makes it impossible to calculate the length of
the lookbehind. The \X and \R escapes, which can match different num-
bers of code units, are never permitted in lookbehinds.
\b(\w)\w++(?<=\1)
abcd$
when applied to a long string that does not match. Because matching
proceeds from left to right, PCRE2 will look for each "a" in the sub-
ject and then see if what follows matches the rest of the pattern. If
the pattern is specified as
^.*abcd$
the initial .* matches the entire string at first, but when this fails
(because there is no following "a"), it backtracks to match all but the
last character, then all but the last two characters, and so on. Once
again the search for "a" covers the entire string, from right to left,
so we are no better off. However, if the pattern is written as
^.*+(?<=abcd)
there can be no backtracking for the .*+ item because of the possessive
quantifier; it can match only the entire string. The subsequent lookbe-
hind assertion does a single test on the last four characters. If it
fails, the match fails immediately. For long strings, this approach
makes a significant difference to the processing time.
Using multiple assertions
Several assertions (of any sort) may occur in succession. For example,
(?<=\d{3})(?<!999)foo
matches "foo" preceded by three digits that are not "999". Notice that
each of the assertions is applied independently at the same point in
the subject string. First there is a check that the previous three
characters are all digits, and then there is a check that the same
three characters are not "999". This pattern does not match "foo" pre-
ceded by six characters, the first of which are digits and the last
three of which are not "999". For example, it doesn't match "123abc-
foo". A pattern to do that is
(?<=\d{3}...)(?<!999)foo
This time the first assertion looks at the preceding six characters,
checking that the first three are digits, and then the second assertion
checks that the preceding three characters are not "999".
(?<=(?<!foo)bar)baz
(?<=\d{3}(?!999)...)foo
is another pattern that matches "foo" preceded by three digits and any
three characters that are not "999".
NON-ATOMIC ASSERTIONS
For a subject such as "word1 word2 word3 word2 word3 word4" the result
is "word3". How does it work? At the start, ^(?x) anchors the pattern
and sets the "x" option, which causes white space (introduced for read-
ability) to be ignored. Inside the assertion, the greedy .* at first
consumes the entire string, but then has to backtrack until the rest of
the assertion can match a word, which is captured by group 1. In other
words, when the assertion first succeeds, it captures the right-most
word in the string.
The current matching point is then reset to the start of the subject,
and the rest of the pattern match checks for two occurrences of the
captured word, using an ungreedy .*? to scan from the left. If this
succeeds, we are done, but if the last word in the string does not oc-
cur twice, this part of the pattern fails. If a traditional atomic
lookhead (?= or (*pla: had been used, the assertion could not be re-en-
tered, and the whole match would fail. The pattern would succeed only
if the very last word in the subject was found twice.
Using a non-atomic lookahead, however, means that when the last word
does not occur twice in the string, the lookahead can backtrack and
find the second-last word, and so on, until either the match succeeds,
or all words have been tested.
SCRIPT RUNS
\s+(*sr:\S+)
To be sure that they are all from the Latin script (for example), a
lookahead can be used:
\s+(?=\p{Latin})(*sr:\S+)
\s+(?=[0-9_.]*\p{Latin})(*sr:\S+)
Note that the atomic group is inside the script run. Putting it outside
would not prevent backtracking into the script run pattern.
Warning: The (*ACCEPT) control verb (see below) should not be used
within a script run group, because it causes an immediate exit from the
group, bypassing the script run checking.
CONDITIONAL GROUPS
(?(condition)yes-pattern)
(?(condition)yes-pattern|no-pattern)
( \( )? [^()]+ (?(1) \) )
If you were embedding this pattern in a larger one, you could use a
relative reference:
((?(R1)a+|(?1)b))
(?(R&name)...)
This condition does not check the entire recursion stack. It tests only
the current level. If the name used in a condition of this kind is a
duplicate, the test is applied to all groups of the same name, and is
true if any one of them is the most recent recursion.
The first part of the pattern is a DEFINE group inside which a another
group named "byte" is defined. This matches an individual component of
an IPv4 address (a number less than 256). When matching takes place,
this part of the pattern is skipped because DEFINE acts like a false
condition. The rest of the pattern uses references to the named group
to match the four dot-separated components of an IPv4 address, insist-
ing on a word boundary at each end.
Programs that link with a PCRE2 library can check the version by call-
ing pcre2_config() with appropriate arguments. Users of applications
that do not have access to the underlying code cannot do this. A spe-
cial "condition" called VERSION exists to allow such users to discover
which version of PCRE2 they are dealing with by using this condition to
match a string such as "yesno". VERSION must be followed either by "="
or ">=" and a version number. For example:
(?(VERSION>=10.4)yes|no)
Assertion conditions
(?(?=[^a-z]*[a-z])
\d{2}-[a-z]{3}-\d{2} | \d{2}-\d{2}-\d{2} )
COMMENTS
There are two ways of including comments in patterns that are processed
by PCRE2. In both cases, the start of the comment must not be in a
character class, nor in the middle of any other sequence of related
characters such as (?: or a group name or number. The characters that
make up a comment play no part in the pattern matching.
The sequence (?# marks the start of a comment that continues up to the
next closing parenthesis. Nested parentheses are not permitted. If the
PCRE2_EXTENDED or PCRE2_EXTENDED_MORE option is set, an unescaped #
character also introduces a comment, which in this case continues to
immediately after the next newline character or character sequence in
the pattern. Which characters are interpreted as newlines is controlled
by an option passed to the compiling function or by a special sequence
at the start of the pattern, as described in the section entitled "New-
line conventions" above. Note that the end of this type of comment is a
literal newline sequence in the pattern; escape sequences that happen
to represent a newline do not count. For example, consider this pattern
when PCRE2_EXTENDED is set, and the default newline convention (a sin-
gle linefeed character) is in force:
RECURSIVE PATTERNS
For some time, Perl has provided a facility that allows regular expres-
sions to recurse (amongst other things). It does this by interpolating
Perl code in the expression at run time, and the code can refer to the
expression itself. A Perl pattern using code interpolation to solve the
parentheses problem can be created like this:
The (?p{...}) item interpolates Perl code at run time, and in this case
refers recursively to the pattern in which it appears.
This PCRE2 pattern solves the nested parentheses problem (assume the
PCRE2_EXTENDED option is set so that white space is ignored):
\( ( [^()]++ | (?R) )* \)
If this were part of a larger pattern, you would not want to recurse
the entire pattern, so instead you could use this:
( \( ( [^()]++ | (?1) )* \) )
We have put the pattern into parentheses, and caused the recursion to
refer to them instead of the whole pattern.
The first two capture groups (a) and (b) are both numbered 1, and group
(c) is number 2. When the reference (?-2) is encountered, the second
most recently opened parentheses has the number 1, but it is the first
such group (the (a) group) to which the recursion refers. This would be
the same if an absolute reference (?1) was used. In other words, rela-
tive references are just a shorthand for computing a group number.
If there is more than one group with the same name, the earliest one is
used.
The example pattern that we have been looking at contains nested unlim-
ited repeats, and so the use of a possessive quantifier for matching
strings of non-parentheses is important when applying the pattern to
strings that do not match. For example, when this pattern is applied to
(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()
(ab(cd)ef)
Do not confuse the (?R) item with the condition (R), which tests for
recursion. Consider this pattern, which matches text in angle brack-
ets, allowing for arbitrary nesting. Only digits are allowed in nested
brackets (that is, when recursing), whereas any characters are permit-
ted at the outer level.
^((.)(?1)\2|.?)$
^\W*+((.)\W*+(?1)\W*+\2|\W*+.?)\W*+$
Another way in which PCRE2 and Perl used to differ in their recursion
processing is in the handling of captured values. Formerly in Perl,
when a group was called recursively or as a subroutine (see the next
section), it had no access to any values that were captured outside the
recursion, whereas in PCRE2 these values can be referenced. Consider
this pattern:
^(.)(\1|a(?2))
This pattern matches "bab". The first capturing parentheses match "b",
then in the second group, when the backreference \1 fails to match "b",
the second alternative matches "a" and then recurses. In the recursion,
\1 does now match "b" and so the whole match succeeds. This match used
to fail in Perl, but in later versions (I tried 5.024) it now works.
GROUPS AS SUBROUTINES
(...(absolute)...)...(?2)...
(...(relative)...)...(?-1)...
(...(?+1)...(relative)...
(abc)(?i:(?-1))
(abc)(?i:\g<-1>)
Note that \g{...} (Perl syntax) and \g<...> (Oniguruma syntax) are not
synonymous. The former is a backreference; the latter is a subroutine
call.
CALLOUTS
Perl has a feature whereby using the sequence (?{...}) causes arbitrary
Perl code to be obeyed in the middle of matching a regular expression.
This makes it possible, amongst other things, to extract different sub-
strings that match the same pair of parentheses when there is a repeti-
tion.
During matching, when PCRE2 reaches a callout point, the external func-
tion is called. It is provided with the number or string argument of
the callout, the position in the pattern, and one item of data that is
also set in the match block. The callout function may cause matching to
proceed, to backtrack, or to fail.
(?C1)abc(?C2)def
(?(?C9)(?=a)abc|def)
Note that this applies only to assertion conditions, not to other types
of condition.
BACKTRACKING CONTROL
The maximum length of a name is 255 in the 8-bit library and 65535 in
the 16-bit and 32-bit libraries. If the name is empty, that is, if the
closing parenthesis immediately follows the colon, the effect is as if
the colon were not there. Any number of these verbs may occur in a pat-
tern. Except for (*ACCEPT), they may not be quantified.
(*ACCEPT) or (*ACCEPT:NAME)
This verb causes the match to end successfully, skipping the remainder
of the pattern. However, when it is inside a capture group that is
called as a subroutine, only that group is ended successfully. Matching
then continues at the outer level. If (*ACCEPT) in triggered in a posi-
tive assertion, the assertion succeeds; in a negative assertion, the
assertion fails.
A((?:A|B(*ACCEPT)|C)D)
This matches "AB", "AAD", or "ACD"; when it matches "AB", "B" is cap-
tured by the outer parentheses.
(A(*ACCEPT)??B)C
Warning: (*ACCEPT) should not be used within a script run group, be-
cause it causes an immediate exit from the group, bypassing the script
run checking.
(*FAIL) or (*FAIL:NAME)
a+(?C)(*FAIL)
A match with the string "aaaa" always fails, but the callout is taken
before each backtrack happens (in this example, 10 times).
There is one verb whose main purpose is to track how a match was ar-
rived at, though it also has a secondary use in conjunction with ad-
vancing the match starting point (see (*SKIP) below).
(*MARK:NAME) or (*:NAME)
A name is always required with this verb. For all the other backtrack-
ing control verbs, a NAME argument is optional.
The mark name that was last encountered on the matching path is passed
back. A verb without a NAME argument is ignored for this purpose. Here
is an example of pcre2test output, where the "mark" modifier requests
the retrieval and outputting of (*MARK) data:
re> /X(*MARK:A)Y|X(*MARK:B)Z/mark
data> XY
0: XY
MK: A
XZ
0: XZ
MK: B
The (*MARK) name is tagged with "MK:" in this output, and in this exam-
ple it indicates which of the two alternatives matched. This is a more
efficient way of obtaining this information than putting each alterna-
tive in its own capturing parentheses.
re> /X(*MARK:A)Y|X(*MARK:B)Z/mark
data> XP
No match, mark = B
Note that in this unanchored example the mark is retained from the
match attempt that started at the letter "X" in the subject. Subsequent
match attempts starting at "P" and then with an empty string do not get
as far as the (*MARK) item, but nevertheless do not reset it.
The following verbs do nothing when they are encountered. Matching con-
tinues with what follows, but if there is a subsequent match failure,
causing a backtrack to the verb, a failure is forced. That is, back-
tracking cannot pass to the left of the verb. However, when one of
these verbs appears inside an atomic group or in a lookaround assertion
that is true, its effect is confined to that group, because once the
group has been matched, there is never any backtracking into it. Back-
tracking from beyond an assertion or an atomic group ignores the entire
group, and seeks a preceding backtracking point.
These verbs differ in exactly what kind of failure occurs when back-
tracking reaches them. The behaviour described below is what happens
when the verb is not in a subroutine or an assertion. Subsequent sec-
tions cover these special cases.
(*COMMIT) or (*COMMIT:NAME)
This verb causes the whole match to fail outright if there is a later
matching failure that causes backtracking to reach it. Even if the pat-
tern is unanchored, no further attempts to find a match by advancing
the starting point take place. If (*COMMIT) is the only backtracking
verb that is encountered, once it has been passed pcre2_match() is com-
mitted to finding a match at the current starting point, or not at all.
For example:
a+(*COMMIT)b
Note that (*COMMIT) at the start of a pattern is not the same as an an-
chor, unless PCRE2's start-of-match optimizations are turned off, as
shown in this output from pcre2test:
re> /(*COMMIT)abc/
data> xyzabc
0: abc
data>
re> /(*COMMIT)abc/no_start_optimize
data> xyzabc
No match
For the first pattern, PCRE2 knows that any match must start with "a",
so the optimization skips along the subject to "a" before applying the
pattern to the first set of data. The match attempt then succeeds. The
second pattern disables the optimization that skips along to the first
character. The pattern is now applied starting at "x", and so the
(*COMMIT) causes the match to fail without trying any other starting
points.
(*PRUNE) or (*PRUNE:NAME)
This verb causes the match to fail at the current starting position in
the subject if there is a later matching failure that causes backtrack-
ing to reach it. If the pattern is unanchored, the normal "bumpalong"
advance to the next starting character then happens. Backtracking can
occur as usual to the left of (*PRUNE), before it is reached, or when
matching to the right of (*PRUNE), but if there is no match to the
right, backtracking cannot cross (*PRUNE). In simple cases, the use of
(*PRUNE) is just an alternative to an atomic group or possessive quan-
tifier, but there are some uses of (*PRUNE) that cannot be expressed in
any other way. In an anchored pattern (*PRUNE) has the same effect as
(*COMMIT).
(*SKIP)
This verb, when given without a name, is like (*PRUNE), except that if
the pattern is unanchored, the "bumpalong" advance is not to the next
character, but to the position in the subject where (*SKIP) was encoun-
tered. (*SKIP) signifies that whatever text was matched leading up to
it cannot be part of a successful match if there is a later mismatch.
Consider:
a+(*SKIP)b
(*SKIP:NAME)
The search for a (*MARK) name uses the normal backtracking mechanism,
which means that it does not see (*MARK) settings that are inside
atomic groups or assertions, because they are never re-entered by back-
tracking. Compare the following pcre2test examples:
re> /a(?>(*MARK:X))(*SKIP:X)(*F)|(.)/
data: abc
0: a
1: a
data:
re> /a(?:(*MARK:X))(*SKIP:X)(*F)|(.)/
data: abc
0: b
1: b
(*THEN) or (*THEN:NAME)
This verb causes a skip to the next innermost alternative when back-
tracking reaches it. That is, it cancels any further backtracking
within the current alternative. Its name comes from the observation
that it can be used for a pattern-based if-then-else block:
( COND1 (*THEN) FOO | COND2 (*THEN) BAR | COND3 (*THEN) BAZ ) ...
If the COND1 pattern matches, FOO is tried (and possibly further items
after the end of the group if FOO succeeds); on failure, the matcher
skips to the second alternative and tries COND2, without backtracking
into COND1. If that succeeds and BAR fails, COND3 is tried. If subse-
quently BAZ fails, there are no more alternatives, so there is a back-
track to whatever came before the entire group. If (*THEN) is not in-
side an alternation, it acts like (*PRUNE).
A group that does not contain a | character is just a part of the en-
closing alternative; it is not a nested alternation with only one al-
ternative. The effect of (*THEN) extends beyond such a group to the en-
closing alternative. Consider this pattern, where A, B, etc. are com-
plex pattern fragments that do not contain any | characters at this
level:
A (B(*THEN)C) | D
A (B(*THEN)C | (*FAIL)) | D
The effect of (*THEN) is now confined to the inner group. After a fail-
ure in C, matching moves to (*FAIL), which causes the whole group to
fail because there are no more alternatives to try. In this case,
matching does backtrack into A.
If the subject is "ba", this pattern does not match. Because .*? is un-
greedy, it initially matches zero characters. The condition (?=a) then
fails, the character "b" is matched, but "c" is not. At this point,
matching does not backtrack to .*? as might perhaps be expected from
the presence of the | character. The conditional group is part of the
single alternative that comprises the whole pattern, and so the match
fails. (If there was a backtrack into .*?, allowing it to match "b",
the match would succeed.)
(A(*COMMIT)B(*THEN)C|ABD)
...(*COMMIT)(*PRUNE)...
/(a(*COMMIT)b)+ac/
The remaining verbs act only when a later failure causes a backtrack to
reach them. This means that, for the Perl-compatible assertions, their
effect is confined to the assertion, because Perl lookaround assertions
are atomic. A backtrack that occurs after such an assertion is complete
does not jump back into the assertion. Note in particular that a
(*MARK) name that is set in an assertion is not "seen" by an instance
of (*SKIP:NAME) later in the pattern.
The other backtracking verbs are not treated specially if they appear
in a standalone positive assertion. In a conditional positive asser-
tion, backtracking (from within the assertion) into (*COMMIT), (*SKIP),
or (*PRUNE) causes the condition to be false. However, for both stand-
alone and conditional negative assertions, backtracking into (*COMMIT),
(*SKIP), or (*PRUNE) causes the assertion to be true, without consider-
ing any further alternative branches.
SEE ALSO
AUTHOR
Philip Hazel
University Computing Service
Cambridge, England.
REVISION
Last updated: 06 October 2020
Copyright (c) 1997-2020 University of Cambridge.
------------------------------------------------------------------------------
NAME
PCRE2 - Perl-compatible regular expressions (revised API)
PCRE2 PERFORMANCE
Two aspects of performance are discussed below: memory usage and pro-
cessing time. The way you express your pattern as a regular expression
can affect both of them.
(abc|def){2,4}
is compiled as if it were
(abc|def)(abc|def)((abc|def)(abc|def)?)?
For regular expressions whose quantifiers use only small numbers, this
is not usually a problem. However, if the numbers are large, and par-
ticularly if such repetitions are nested, the memory usage can become
an embarrassment. For example, the very simple pattern
((ab){1,1000}c){1,3}
uses over 50KiB when compiled using the 8-bit library. When PCRE2 is
compiled with its default internal pointer size of two bytes, the size
limit on a compiled pattern is 65535 code units in the 8-bit and 16-bit
libraries, and this is reached with the above pattern if the outer rep-
etition is increased from 3 to 4. PCRE2 can be compiled to use larger
internal pointers and thus handle larger compiled patterns, but it is
better to try to rewrite your pattern to use less memory if you can.
One way of reducing the memory usage for such patterns is to make use
of PCRE2's "subroutine" facility. Re-writing the above pattern as
((ab)(?2){0,999}c)(?1){0,2}
reduces the memory requirements to around 16KiB, and indeed it remains
under 20KiB even with the outer repetition increased to 100. However,
this kind of pattern is not always exactly equivalent, because any cap-
tures within subroutine calls are lost when the subroutine completes.
If this is not a problem, this kind of rewriting will allow you to
process patterns that PCRE2 cannot otherwise handle. The matching per-
formance of the two different versions of the pattern are roughly the
same. (This applies from release 10.30 - things were different in ear-
lier releases.)
The "match depth" parameter can be used to limit the depth of function
recursion, and the "match heap" parameter to limit heap memory in
pcre2_dfa_match().
PROCESSING TIME
By default, the escape sequences \b, \d, \s, and \w, and the POSIX
character classes such as [:alpha:] do not use Unicode properties,
partly for backwards compatibility, and partly for performance reasons.
However, you can set the PCRE2_UCP option or start the pattern with
(*UCP) if you want Unicode character properties to be used. This can
double the matching time for items such as \d, when matched with
pcre2_match(); the performance loss is less with a DFA matching func-
tion, and in both cases there is not much difference for \b.
.*second
If you are using such a pattern with subject strings that do not con-
tain newlines, the best performance is obtained by setting
PCRE2_DOTALL, or starting the pattern with ^.* or ^.*? to indicate ex-
plicit anchoring. That saves PCRE2 from having to scan along the sub-
ject looking for a newline to restart at.
^(a+)*
This can match "aaaa" in 16 different ways, and this number increases
very rapidly as the string gets longer. (The * repeat can match 0, 1,
2, 3, or 4 times, and for each of those cases other than 0 or 4, the +
repeats can match different numbers of times.) When the remainder of
the pattern is such that the entire match is going to fail, PCRE2 has
in principle to try every possible variation, and this can take an ex-
tremely long time, even for relatively short strings.
(a+)*b
(a+)*\d
with the pattern above. The former gives a failure almost instantly
when applied to a whole line of "a" characters, whereas the latter
takes an appreciable time with strings longer than about 20 characters.
([^<]|<(?!inet))+
([^<]++|<(?!inet))+
This runs much faster, because sequences of characters that do not con-
tain "<" are "swallowed" in one item inside the parentheses, and a pos-
sessive quantifier is used to stop any backtracking into the runs of
non-"<" characters. This version also uses a lot less memory because
entry to a new set of parentheses happens only when a "<" character
that is not followed by "inet" is encountered (and we assume this is
relatively rare).
This example shows that one way of optimizing performance when matching
long subject strings is to write repeated parenthesized subpatterns to
match more than one character whenever possible.
You can set limits on the amount of processing that takes place when
matching, and on the amount of heap memory that is used. The default
values of the limits are very large, and unlikely ever to operate. They
can be changed when PCRE2 is built, and they can also be set when
pcre2_match() or pcre2_dfa_match() is called. For details of these in-
terfaces, see the pcre2build documentation and the section entitled
"The match context" in the pcre2api documentation.
AUTHOR
Philip Hazel
University Computing Service
Cambridge, England.
REVISION
Last updated: 03 February 2019
Copyright (c) 1997-2019 University of Cambridge.
------------------------------------------------------------------------------
NAME
PCRE2 - Perl-compatible regular expressions (revised API)
SYNOPSIS
#include <pcre2posix.h>
DESCRIPTION
This set of functions provides a POSIX-style API for the PCRE2 regular
expression 8-bit library. There are no POSIX-style wrappers for PCRE2's
16-bit and 32-bit libraries. See the pcre2api documentation for a de-
scription of PCRE2's native API, which contains much additional func-
tionality.
The functions described here are wrapper functions that ultimately call
the PCRE2 native API. Their prototypes are defined in the pcre2posix.h
header file, and they all have unique names starting with pcre2_. How-
ever, the pcre2posix.h header also contains macro definitions that con-
vert the standard POSIX names such regcomp() into pcre2_regcomp() etc.
This means that a program can use the usual POSIX names without running
the risk of accidentally linking with POSIX functions from a different
library.
Those POSIX option bits that can reasonably be mapped to PCRE2 native
options have been implemented. In addition, the option REG_EXTENDED is
defined with the value zero. This has no effect, but since programs
that are written to the POSIX interface often use it, this makes it
easier to slot in PCRE2 as a replacement library. Other POSIX options
are not even defined.
There are also some options that are not defined by POSIX. These have
been added at the request of users who want to make use of certain
PCRE2-specific features via the POSIX calling interface or to add BSD
or GNU functionality.
When PCRE2 is called via these functions, it is only the API that is
POSIX-like in style. The syntax and semantics of the regular expres-
sions themselves are still those of Perl, subject to the setting of
various PCRE2 options, as described below. "POSIX-like in style" means
that the API approximates to the POSIX definition; it is not fully
POSIX-compatible, and in multi-unit encoding domains it is probably
even less compatible.
The descriptions below use the actual names of the functions, but, as
described above, the standard POSIX names (without the pcre2_ prefix)
may also be used.
COMPILING A PATTERN
The argument cflags is either zero, or contains one or more of the bits
defined by the following macros:
REG_DOTALL
REG_ICASE
REG_NOSPEC
REG_NOSUB
REG_PEND
If this option is set, the reg_endp field in the preg structure (which
has the type const char *) must be set to point to the character beyond
the end of the pattern before calling pcre2_regcomp(). The pattern it-
self may now contain binary zeros, which are treated as data charac-
ters. Without REG_PEND, a binary zero terminates the pattern and the
re_endp field is ignored. This is a GNU extension to the POSIX standard
and should be used with caution in software intended to be portable to
other systems.
REG_UCP
The PCRE2_UCP option is set when the regular expression is passed for
compilation to the native function. This causes PCRE2 to use Unicode
properties when matchine \d, \w, etc., instead of just recognizing
ASCII values. Note that REG_UCP is not part of the POSIX standard.
REG_UNGREEDY
REG_UTF
The PCRE2_UTF option is set when the regular expression is passed for
compilation to the native function. This causes the pattern itself and
all data strings used for matching it to be treated as UTF-8 strings.
Note that REG_UTF is not part of the POSIX standard.
This area is not simple, because POSIX and Perl take different views of
things. It is not possible to get PCRE2 to obey POSIX semantics, but
then PCRE2 was never intended to be a POSIX engine. The following table
lists the different possibilities for matching newline characters in
Perl and PCRE2:
This behaviour is not what happens when PCRE2 is called via its POSIX
API. By default, PCRE2's behaviour is the same as Perl's, except that
there is no equivalent for PCRE2_DOLLAR_ENDONLY in Perl. In both PCRE2
and Perl, there is no way to stop newline from matching [^a].
MATCHING A PATTERN
The function pcre2_regexec() is called to match a compiled pattern preg
against a given string, which is by default terminated by a zero byte
(but see REG_STARTEND below), subject to the options in eflags. These
can be:
REG_NOTBOL
The PCRE2_NOTBOL option is set when calling the underlying PCRE2 match-
ing function.
REG_NOTEMPTY
REG_NOTEOL
The PCRE2_NOTEOL option is set when calling the underlying PCRE2 match-
ing function.
REG_STARTEND
If the pattern was compiled with the REG_NOSUB flag, no data about any
matched strings is returned. The nmatch and pmatch arguments of
pcre2_regexec() are ignored (except possibly as input for REG_STAR-
TEND).
The value of nmatch may be zero, and the value pmatch may be NULL (un-
less REG_STARTEND is set); in both these cases no data about any
matched strings is returned.
Otherwise, the portion of the string that was matched, and also any
captured substrings, are returned via the pmatch argument, which points
to an array of nmatch structures of type regmatch_t, containing the
members rm_so and rm_eo. These contain the byte offset to the first
character of each substring and the offset to the first character after
the end of each substring, respectively. The 0th element of the vector
relates to the entire portion of string that was matched; subsequent
elements relate to the capturing subpatterns of the regular expression.
Unused entries in the array have both structure members set to -1.
A successful match yields a zero return; various error codes are de-
fined in the header file, of which REG_NOMATCH is the "expected" fail-
ure code.
ERROR MESSAGES
MEMORY USAGE
AUTHOR
Philip Hazel
University Computing Service
Cambridge, England.
REVISION
NAME
PCRE2 - Perl-compatible regular expressions (revised API)
If the -g option is given on the command line, the program then goes on
to check for further matches of the same regular expression in the same
subject string. The logic is a little bit tricky because of the possi-
bility of matching an empty string. Comments in the code explain what
is going on.
The code in pcre2demo.c is an 8-bit program that uses the PCRE2 8-bit
library. It handles strings and characters that are stored in 8-bit
code units. By default, one character corresponds to one code unit,
but if the pattern starts with "(*UTF)", both it and the subject are
treated as UTF-8 strings, where characters may occupy multiple code
units.
Once you have built the demonstration program, you can run simple tests
like this:
If you try to run pcre2demo when PCRE2 is not installed in the standard
library directory, you may get an error like this on some operating
systems (e.g. Solaris):
This is caused by the way shared library support works on those sys-
tems. You need to add
-R/usr/local/lib
Philip Hazel
University Computing Service
Cambridge, England.
REVISION
NAME
PCRE2 - Perl-compatible regular expressions (revised API)
SECURITY CONCERNS
The facility for saving and restoring compiled patterns is intended for
use within individual applications. As such, the data supplied to
pcre2_serialize_decode() is expected to be trusted data, not data from
arbitrary external sources. There is only some simple consistency
checking, not complete validation of what is being re-loaded. Corrupted
data may cause undefined results. For example, if the length field of a
pattern in the serialized data is corrupted, the deserializing code may
read beyond the end of the byte stream that is passed to it.
Once a set of patterns has been serialized you can save the data in any
appropriate manner. Here is sample code that compiles two patterns and
writes them to a file. It assumes that the variable fd refers to a file
that is open for output. The error checking that should be present in a
real application has been omitted for simplicity.
int errorcode;
uint8_t *bytes;
PCRE2_SIZE erroroffset;
PCRE2_SIZE bytescount;
pcre2_code *list_of_codes[2];
list_of_codes[0] = pcre2_compile("first pattern",
PCRE2_ZERO_TERMINATED, 0, &errorcode, &erroroffset, NULL);
list_of_codes[1] = pcre2_compile("second pattern",
PCRE2_ZERO_TERMINATED, 0, &errorcode, &erroroffset, NULL);
errorcode = pcre2_serialize_encode(list_of_codes, 2, &bytes,
&bytescount, NULL);
errorcode = fwrite(bytes, 1, bytescount, fd);
Note that the serialized data is binary data that may contain any of
the 256 possible byte values. On systems that make a distinction be-
tween binary and non-binary data, be sure that the file is opened for
binary output.
In order to re-use a set of saved patterns you must first make the se-
rialized byte stream available in main memory (for example, by reading
from a file). The management of this memory block is up to the applica-
tion. You can use the pcre2_serialize_get_number_of_codes() function to
find out how many compiled patterns are in the serialized data without
actually decoding the patterns:
int32_t number_of_codes;
pcre2_code *list_of_codes[2];
uint8_t *bytes = <serialized data>;
int32_t number_of_codes =
pcre2_serialize_decode(list_of_codes, 2, bytes, NULL);
If the vector is not large enough for all the patterns in the byte
stream, it is filled with those that fit, and the remainder are ig-
nored. The yield of the function is the number of decoded patterns, or
one of the following negative error codes:
Decoded patterns can be used for matching in the usual way, and must be
freed by calling pcre2_code_free(). However, be aware that there is a
potential race issue if you are using multiple patterns that were de-
coded from a single byte stream in a multithreaded application. A sin-
gle copy of the character tables is used by all the decoded patterns
and a reference count is used to arrange for its memory to be automati-
cally freed when the last pattern is freed, but there is no locking on
this reference count. Therefore, if you want to call pcre2_code_free()
for these patterns in different threads, you must arrange your own
locking, and ensure that pcre2_code_free() cannot be called by two
threads at the same time.
AUTHOR
Philip Hazel
University Computing Service
Cambridge, England.
REVISION
NAME
PCRE2 - Perl-compatible regular expressions (revised API)
The full syntax and semantics of the regular expressions that are sup-
ported by PCRE2 are described in the pcre2pattern documentation. This
document contains a quick-reference summary of the syntax.
QUOTING
ESCAPED CHARACTERS
Note that \0dd is always an octal code. The treatment of backslash fol-
lowed by a non-zero digit is complicated; for details see the section
"Non-printing characters" in the pcre2pattern documentation, where de-
tails of escape processing in EBCDIC environments are also given.
\N{U+hh..} is synonymous with \x{hh..} in PCRE2 but is not supported in
EBCDIC environments. Note that \N not followed by an opening curly
bracket has a different meaning (see below).
CHARACTER TYPES
By default, \d, \s, and \w match only ASCII characters, even in UTF-8
mode or in the 16-bit and 32-bit libraries. However, if locale-specific
matching is happening, \s and \w may also match characters with code
points in the range 128-255. If the PCRE2_UCP option is set, the behav-
iour of these escape sequences is changed to use Unicode properties and
they match many more characters.
C Other
Cc Control
Cf Format
Cn Unassigned
Co Private use
Cs Surrogate
L Letter
Ll Lower case letter
Lm Modifier letter
Lo Other letter
Lt Title case letter
Lu Upper case letter
L& Ll, Lu, or Lt
M Mark
Mc Spacing mark
Me Enclosing mark
Mn Non-spacing mark
N Number
Nd Decimal number
Nl Letter number
No Other number
P Punctuation
Pc Connector punctuation
Pd Dash punctuation
Pe Close punctuation
Pf Final punctuation
Pi Initial punctuation
Po Other punctuation
Ps Open punctuation
S Symbol
Sc Currency symbol
Sk Modifier symbol
Sm Mathematical symbol
So Other symbol
Z Separator
Zl Line separator
Zp Paragraph separator
Zs Space separator
Perl and POSIX space are now the same. Perl added VT to its space char-
acter set at release 5.18.
CHARACTER CLASSES
alnum alphanumeric
alpha alphabetic
ascii 0-127
blank space or tab
cntrl control character
digit decimal digit
graph printing, excluding space
lower lower case letter
print printing, including space
punct printing, excluding alphanumeric
space white space
upper upper case letter
word same as \w
xdigit hexadecimal digit
In PCRE2, POSIX character set names recognize only ASCII characters by
default, but some of them use Unicode properties if PCRE2_UCP is set.
You can use \Q...\E inside a character class.
QUANTIFIERS
? 0 or 1, greedy
?+ 0 or 1, possessive
?? 0 or 1, lazy
* 0 or more, greedy
*+ 0 or more, possessive
*? 0 or more, lazy
+ 1 or more, greedy
++ 1 or more, possessive
+? 1 or more, lazy
{n} exactly n
{n,m} at least n, no more than m, greedy
{n,m}+ at least n, no more than m, possessive
{n,m}? at least n, no more than m, lazy
{n,} n or more, greedy
{n,}+ n or more, possessive
{n,}? n or more, lazy
\b word boundary
\B not a word boundary
^ start of subject
also after an internal newline in multiline mode
(after any newline if PCRE2_ALT_CIRCUMFLEX is set)
\A start of subject
$ end of subject
also before newline at end of subject
also before internal newline in multiline mode
\Z end of subject
also before newline at end of subject
\z end of subject
\G first matching position in subject
ALTERNATION
expr|expr|expr...
CAPTURING
In non-UTF modes, names may contain underscores and ASCII letters and
digits; in UTF modes, any Unicode letters and Unicode decimal digits
are permitted. In both cases, a name must not start with a digit.
ATOMIC GROUPS
COMMENT
OPTION SETTING
Changes of these options within a group are automatically cancelled at
the end of the group.
(?i) caseless
(?J) allow duplicate named groups
(?m) multiline
(?n) no auto capture
(?s) single line (dotall)
(?U) default ungreedy (lazy)
(?x) extended: ignore white space except in classes
(?xx) as (?x) but also ignore space and tab in classes
(?-...) unset option(s)
(?^) unset imnsx options
The following are recognized only at the very start of a pattern or af-
ter one of the newline or \R options with similar syntax. More than one
of them may appear. For the first three, d is a decimal number.
NEWLINE CONVENTION
These are recognized only at the very start of the pattern or after op-
tion settings with a similar syntax.
WHAT \R MATCHES
These are recognized only at the very start of the pattern or after op-
tion setting with a similar syntax.
(?=...) )
(*pla:...) ) positive lookahead
(*positive_lookahead:...) )
(?!...) )
(*nla:...) ) negative lookahead
(*negative_lookahead:...) )
(?<=...) )
(*plb:...) ) positive lookbehind
(*positive_lookbehind:...) )
(?<!...) )
(*nlb:...) ) negative lookbehind
(*negative_lookbehind:...) )
(?*...) )
(*napla:...) ) synonyms
(*non_atomic_positive_lookahead:...) )
(?<*...) )
(*naplb:...) ) synonyms
(*non_atomic_positive_lookbehind:...) )
SCRIPT RUNS
BACKREFERENCES
CONDITIONAL PATTERNS
(?(condition)yes-pattern)
(?(condition)yes-pattern|no-pattern)
Note the ambiguity of (?(R) and (?(Rn) which might be named reference
conditions or recursion tests. Such a condition is interpreted as a
reference condition if the relevant named group exists.
BACKTRACKING CONTROL
The following act only when a subsequent match failure causes a back-
track to reach them. They all force a match failure, but they differ in
what happens afterwards. Those that advance the start-of-match point do
so only if the pattern is not anchored.
CALLOUTS
The allowed string delimiters are ` ' " ^ % # $ (which are the same for
the start and the end), and the starting delimiter { matched with the
ending delimiter }. To encode the ending delimiter within the string,
double it.
SEE ALSO
AUTHOR
Philip Hazel
University Computing Service
Cambridge, England.
REVISION
NAME
PCRE - Perl-compatible regular expressions (revised API)
PCRE2 is normally built with Unicode support, though if you do not need
it, you can build it without, in which case the library will be
smaller. With Unicode support, PCRE2 has knowledge of Unicode character
properties and can process strings of text in UTF-8, UTF-16, and UTF-32
format (depending on the code unit width), but this is not the default.
Unless specifically requested, PCRE2 treats each code unit in a string
as one character.
There are two ways of telling PCRE2 to switch to UTF mode, where char-
acters may consist of more than one code unit and the range of values
is constrained. The program can call pcre2_compile() with the PCRE2_UTF
option, or the pattern may start with the sequence (*UTF). However,
the latter facility can be locked out by the PCRE2_NEVER_UTF option.
That is, the programmer can prevent the supplier of the pattern from
switching to UTF mode.
In UTF mode, both the pattern and any subject strings that are matched
against it are treated as UTF strings instead of strings of individual
one-code-unit characters. There are also some other changes to the way
characters are handled, as documented below.
When PCRE2 is built with Unicode support, the escape sequences \p{..},
\P{..}, and \X can be used. This is not dependent on the PCRE2_UTF set-
ting. The Unicode properties that can be tested are limited to the
general category properties such as Lu for an upper case letter or Nd
for a decimal number, the Unicode script names such as Arabic or Han,
and the derived properties Any and L&. Full lists are given in the
pcre2pattern and pcre2syntax documentation. Only the short names for
properties are supported. For example, \p{L} matches a letter. Its Perl
synonym, \p{Letter}, is not supported. Furthermore, in Perl, many
properties may optionally be prefixed by "Is", for compatibility with
Perl 5.6. PCRE2 does not support this.
Code points less than 256 can be specified in patterns by either braced
or unbraced hexadecimal escape sequences (for example, \x{b3} or \xb3).
Larger values have to use braced sequences. Unbraced octal code points
up to \777 are also recognized; larger ones can be coded using \o{...}.
In UTF mode, the dot metacharacter matches one UTF character instead of
a single code unit.
In UTF mode, capture group names are not restricted to ASCII, and may
contain any Unicode letters and decimal digits, as well as underscore.
The escape sequence \C can be used to match a single code unit in UTF
mode, but its use can lead to some strange effects because it breaks up
multi-unit characters (see the description of \C in the pcre2pattern
documentation). For this reason, there is a build-time option that dis-
ables support for \C completely. There is also a less draconian com-
pile-time option for locking out the use of \C when a pattern is com-
piled.
The character escapes \b, \B, \d, \D, \s, \S, \w, and \W correctly test
characters of any code value, but, by default, the characters that
PCRE2 recognizes as digits, spaces, or word characters remain the same
set as in non-UTF mode, all with code points less than 256. This re-
mains true even when PCRE2 is built to include Unicode support, because
to do otherwise would slow down matching in many common cases. Note
that this also applies to \b and \B, because they are defined in terms
of \w and \W. If you want to test for a wider sense of, say, "digit",
you can use explicit Unicode property tests such as \p{Nd}. Alterna-
tively, if you set the PCRE2_UCP option, the way that the character es-
capes work is changed so that Unicode properties are used to determine
which characters match. There are more details in the section on
generic character types in the pcre2pattern documentation.
Similarly, characters that match the POSIX named character classes are
all low-valued characters, unless the PCRE2_UCP option is set.
However, the special horizontal and vertical white space matching es-
capes (\h, \H, \v, and \V) do match all the appropriate Unicode charac-
ters, whether or not PCRE2_UCP is set.
UNICODE CASE-EQUIVALENCE
SCRIPT RUNS
Every Unicode character has a Script property, mostly with a value cor-
responding to the name of a script, such as Latin, Greek, or Cyrillic.
There are also three special values:
"Unknown" is used for code points that have not been assigned, and also
for the surrogate code points. In the PCRE2 32-bit library, characters
whose code points are greater than the Unicode maximum (U+10FFFF),
which are accessible only in non-UTF mode, are assigned the Unknown
script.
"Common" is used for characters that are used with many scripts. These
include punctuation, emoji, mathematical, musical, and currency sym-
bols, and the ASCII digits 0 to 9.
Some Inherited characters are used with many scripts, but many of them
are only normally used with a small number of scripts. For example,
U+102E0 (Coptic Epact thousands mark) is used only with Arabic and Cop-
tic. In order to make it possible to check this, a Unicode property
called Script Extension exists. Its value is a list of scripts that ap-
ply to the character. For the majority of characters, the list contains
just one script, the same one as the Script property. However, for
characters such as U+102E0 more than one Script is listed. There are
also some Common characters that have a single, non-Common script in
their Script Extension list.
The next section describes the basic rules for deciding whether a given
string of characters is a script run. Note, however, that there are
some special cases involving the Chinese Han script, and an additional
constraint for decimal digits. These are covered in subsequent sec-
tions.
Basic script run rules
A string that is less than two characters long is a script run. This is
the only case in which an Unknown character can be part of a script
run. Longer strings are checked using only the Script Extensions prop-
erty, not the basic Script property.
More interesting examples involve characters with more than one script
in their Script Extension. Consider the following characters:
The first has the Script Extension list Arabic, Hanifi Rohingya, Syr-
iac, and Thaana; the second has just Arabic and Hanifi Rohingya. Both
of them could appear in script runs of either Arabic or Hanifi Ro-
hingya. The first could also appear in Syriac or Thaana script runs,
but the second could not.
Decimal digits
In some situations, you may already know that your strings are valid,
and therefore want to skip these checks in order to improve perfor-
mance, for example in the case of a long subject string that is being
scanned repeatedly. If you set the PCRE2_NO_UTF_CHECK option at com-
pile time or at match time, PCRE2 assumes that the pattern or subject
it is given (respectively) contains only valid UTF code unit sequences.
UTF-16 and UTF-32 strings can indicate their endianness by special code
knows as a byte-order mark (BOM). The PCRE2 functions do not handle
this, expecting strings to be in host byte order.
The following negative error codes are given for invalid UTF-8 strings:
PCRE2_ERROR_UTF8_ERR1
PCRE2_ERROR_UTF8_ERR2
PCRE2_ERROR_UTF8_ERR3
PCRE2_ERROR_UTF8_ERR4
PCRE2_ERROR_UTF8_ERR5
The string ends with a truncated UTF-8 character; the code specifies
how many bytes are missing (1 to 5). Although RFC 3629 restricts UTF-8
characters to be no longer than 4 bytes, the encoding scheme (origi-
nally defined by RFC 2279) allows for up to 6 bytes, and this is
checked first; hence the possibility of 4 or 5 missing bytes.
PCRE2_ERROR_UTF8_ERR6
PCRE2_ERROR_UTF8_ERR7
PCRE2_ERROR_UTF8_ERR8
PCRE2_ERROR_UTF8_ERR9
PCRE2_ERROR_UTF8_ERR10
The two most significant bits of the 2nd, 3rd, 4th, 5th, or 6th byte of
the character do not have the binary value 0b10 (that is, either the
most significant bit is 0, or the next bit is 1).
PCRE2_ERROR_UTF8_ERR11
PCRE2_ERROR_UTF8_ERR12
PCRE2_ERROR_UTF8_ERR13
A 4-byte character has a value greater than 0x10ffff; these code points
are excluded by RFC 3629.
PCRE2_ERROR_UTF8_ERR14
PCRE2_ERROR_UTF8_ERR15
PCRE2_ERROR_UTF8_ERR16
PCRE2_ERROR_UTF8_ERR17
PCRE2_ERROR_UTF8_ERR18
PCRE2_ERROR_UTF8_ERR19
A 2-, 3-, 4-, 5-, or 6-byte character is "overlong", that is, it codes
for a value that can be represented by fewer bytes, which is invalid.
For example, the two bytes 0xc0, 0xae give the value 0x2e, whose cor-
rect coding uses just one byte.
PCRE2_ERROR_UTF8_ERR20
The two most significant bits of the first byte of a character have the
binary value 0b10 (that is, the most significant bit is 1 and the sec-
ond is 0). Such a byte can only validly occur as the second or subse-
quent byte of a multi-byte character.
PCRE2_ERROR_UTF8_ERR21
The first byte of a character has the value 0xfe or 0xff. These values
can never occur in a valid UTF-8 string.
The following negative error codes are given for invalid UTF-16
strings:
The following negative error codes are given for invalid UTF-32
strings:
You can run pattern matches on subject strings that may contain invalid
UTF sequences if you call pcre2_compile() with the PCRE2_MATCH_IN-
VALID_UTF option. This is supported by pcre2_match(), including JIT
matching, but not by pcre2_dfa_match(). When PCRE2_MATCH_INVALID_UTF is
set, it forces PCRE2_UTF to be set as well. Note, however, that the
pattern itself must be a valid UTF string.
You can also think of this as the subject being split up into fragments
of valid UTF, delimited internally by invalid code unit sequences. The
pattern is matched fragment by fragment. The result of a successful
match, however, is given as code unit offsets in the entire subject
string in the usual way. There are a few points to consider:
AUTHOR
Philip Hazel
University Computing Service
Cambridge, England.
REVISION