github的一些开源项目
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

11980 lines
585 KiB

  1. -----------------------------------------------------------------------------
  2. This file contains a concatenation of the PCRE2 man pages, converted to plain
  3. text format for ease of searching with a text editor, or for use on systems
  4. that do not have a man page processor. The small individual files that give
  5. synopses of each function in the library have not been included. Neither has
  6. the pcre2demo program. There are separate text files for the pcre2grep and
  7. pcre2test commands.
  8. -----------------------------------------------------------------------------
  9. PCRE2(3) Library Functions Manual PCRE2(3)
  10. NAME
  11. PCRE2 - Perl-compatible regular expressions (revised API)
  12. INTRODUCTION
  13. PCRE2 is the name used for a revised API for the PCRE library, which is
  14. a set of functions, written in C, that implement regular expression
  15. pattern matching using the same syntax and semantics as Perl, with just
  16. a few differences. After nearly two decades, the limitations of the
  17. original API were making development increasingly difficult. The new
  18. API is more extensible, and it was simplified by abolishing the sepa-
  19. rate "study" optimizing function; in PCRE2, patterns are automatically
  20. optimized where possible. Since forking from PCRE1, the code has been
  21. extensively refactored and new features introduced. The old library is
  22. now obsolete and is no longer maintained.
  23. As well as Perl-style regular expression patterns, some features that
  24. appeared in Python and the original PCRE before they appeared in Perl
  25. are available using the Python syntax. There is also some support for
  26. one or two .NET and Oniguruma syntax items, and there are options for
  27. requesting some minor changes that give better ECMAScript (aka
  28. JavaScript) compatibility.
  29. The source code for PCRE2 can be compiled to support strings of 8-bit,
  30. 16-bit, or 32-bit code units, which means that up to three separate li-
  31. braries may be installed, one for each code unit size. The size of code
  32. unit is not related to the bit size of the underlying hardware. In a
  33. 64-bit environment that also supports 32-bit applications, versions of
  34. PCRE2 that are compiled in both 64-bit and 32-bit modes may be needed.
  35. The original work to extend PCRE to 16-bit and 32-bit code units was
  36. done by Zoltan Herczeg and Christian Persch, respectively. In all three
  37. cases, strings can be interpreted either as one character per code
  38. unit, or as UTF-encoded Unicode, with support for Unicode general cate-
  39. gory properties. Unicode support is optional at build time (but is the
  40. default). However, processing strings as UTF code units must be enabled
  41. explicitly at run time. The version of Unicode in use can be discovered
  42. by running
  43. pcre2test -C
  44. The three libraries contain identical sets of functions, with names
  45. ending in _8, _16, or _32, respectively (for example, pcre2_com-
  46. pile_8()). However, by defining PCRE2_CODE_UNIT_WIDTH to be 8, 16, or
  47. 32, a program that uses just one code unit width can be written using
  48. generic names such as pcre2_compile(), and the documentation is written
  49. assuming that this is the case.
  50. In addition to the Perl-compatible matching function, PCRE2 contains an
  51. alternative function that matches the same compiled patterns in a dif-
  52. ferent way. In certain circumstances, the alternative function has some
  53. advantages. For a discussion of the two matching algorithms, see the
  54. pcre2matching page.
  55. Details of exactly which Perl regular expression features are and are
  56. not supported by PCRE2 are given in separate documents. See the
  57. pcre2pattern and pcre2compat pages. There is a syntax summary in the
  58. pcre2syntax page.
  59. Some features of PCRE2 can be included, excluded, or changed when the
  60. library is built. The pcre2_config() function makes it possible for a
  61. client to discover which features are available. The features them-
  62. selves are described in the pcre2build page. Documentation about build-
  63. ing PCRE2 for various operating systems can be found in the README and
  64. NON-AUTOTOOLS_BUILD files in the source distribution.
  65. The libraries contains a number of undocumented internal functions and
  66. data tables that are used by more than one of the exported external
  67. functions, but which are not intended for use by external callers.
  68. Their names all begin with "_pcre2", which hopefully will not provoke
  69. any name clashes. In some environments, it is possible to control which
  70. external symbols are exported when a shared library is built, and in
  71. these cases the undocumented symbols are not exported.
  72. SECURITY CONSIDERATIONS
  73. If you are using PCRE2 in a non-UTF application that permits users to
  74. supply arbitrary patterns for compilation, you should be aware of a
  75. feature that allows users to turn on UTF support from within a pattern.
  76. For example, an 8-bit pattern that begins with "(*UTF)" turns on UTF-8
  77. mode, which interprets patterns and subjects as strings of UTF-8 code
  78. units instead of individual 8-bit characters. This causes both the pat-
  79. tern and any data against which it is matched to be checked for UTF-8
  80. validity. If the data string is very long, such a check might use suf-
  81. ficiently many resources as to cause your application to lose perfor-
  82. mance.
  83. One way of guarding against this possibility is to use the pcre2_pat-
  84. tern_info() function to check the compiled pattern's options for
  85. PCRE2_UTF. Alternatively, you can set the PCRE2_NEVER_UTF option when
  86. calling pcre2_compile(). This causes a compile time error if the pat-
  87. tern contains a UTF-setting sequence.
  88. The use of Unicode properties for character types such as \d can also
  89. be enabled from within the pattern, by specifying "(*UCP)". This fea-
  90. ture can be disallowed by setting the PCRE2_NEVER_UCP option.
  91. If your application is one that supports UTF, be aware that validity
  92. checking can take time. If the same data string is to be matched many
  93. times, you can use the PCRE2_NO_UTF_CHECK option for the second and
  94. subsequent matches to avoid running redundant checks.
  95. The use of the \C escape sequence in a UTF-8 or UTF-16 pattern can lead
  96. to problems, because it may leave the current matching point in the
  97. middle of a multi-code-unit character. The PCRE2_NEVER_BACKSLASH_C op-
  98. tion can be used by an application to lock out the use of \C, causing a
  99. compile-time error if it is encountered. It is also possible to build
  100. PCRE2 with the use of \C permanently disabled.
  101. Another way that performance can be hit is by running a pattern that
  102. has a very large search tree against a string that will never match.
  103. Nested unlimited repeats in a pattern are a common example. PCRE2 pro-
  104. vides some protection against this: see the pcre2_set_match_limit()
  105. function in the pcre2api page. There is a similar function called
  106. pcre2_set_depth_limit() that can be used to restrict the amount of mem-
  107. ory that is used.
  108. USER DOCUMENTATION
  109. The user documentation for PCRE2 comprises a number of different sec-
  110. tions. In the "man" format, each of these is a separate "man page". In
  111. the HTML format, each is a separate page, linked from the index page.
  112. In the plain text format, the descriptions of the pcre2grep and
  113. pcre2test programs are in files called pcre2grep.txt and pcre2test.txt,
  114. respectively. The remaining sections, except for the pcre2demo section
  115. (which is a program listing), and the short pages for individual func-
  116. tions, are concatenated in pcre2.txt, for ease of searching. The sec-
  117. tions are as follows:
  118. pcre2 this document
  119. pcre2-config show PCRE2 installation configuration information
  120. pcre2api details of PCRE2's native C API
  121. pcre2build building PCRE2
  122. pcre2callout details of the pattern callout feature
  123. pcre2compat discussion of Perl compatibility
  124. pcre2convert details of pattern conversion functions
  125. pcre2demo a demonstration C program that uses PCRE2
  126. pcre2grep description of the pcre2grep command (8-bit only)
  127. pcre2jit discussion of just-in-time optimization support
  128. pcre2limits details of size and other limits
  129. pcre2matching discussion of the two matching algorithms
  130. pcre2partial details of the partial matching facility
  131. pcre2pattern syntax and semantics of supported regular
  132. expression patterns
  133. pcre2perform discussion of performance issues
  134. pcre2posix the POSIX-compatible C API for the 8-bit library
  135. pcre2sample discussion of the pcre2demo program
  136. pcre2serialize details of pattern serialization
  137. pcre2syntax quick syntax reference
  138. pcre2test description of the pcre2test command
  139. pcre2unicode discussion of Unicode and UTF support
  140. In the "man" and HTML formats, there is also a short page for each C
  141. library function, listing its arguments and results.
  142. AUTHOR
  143. Philip Hazel
  144. Retired from University Computing Service
  145. Cambridge, England.
  146. Putting an actual email address here is a spam magnet. If you want to
  147. email me, use my two names separated by a dot at gmail.com.
  148. REVISION
  149. Last updated: 27 August 2021
  150. Copyright (c) 1997-2021 University of Cambridge.
  151. PCRE2 10.38 27 August 2021 PCRE2(3)
  152. ------------------------------------------------------------------------------
  153. PCRE2API(3) Library Functions Manual PCRE2API(3)
  154. NAME
  155. PCRE2 - Perl-compatible regular expressions (revised API)
  156. #include <pcre2.h>
  157. PCRE2 is a new API for PCRE, starting at release 10.0. This document
  158. contains a description of all its native functions. See the pcre2 docu-
  159. ment for an overview of all the PCRE2 documentation.
  160. PCRE2 NATIVE API BASIC FUNCTIONS
  161. pcre2_code *pcre2_compile(PCRE2_SPTR pattern, PCRE2_SIZE length,
  162. uint32_t options, int *errorcode, PCRE2_SIZE *erroroffset,
  163. pcre2_compile_context *ccontext);
  164. void pcre2_code_free(pcre2_code *code);
  165. pcre2_match_data *pcre2_match_data_create(uint32_t ovecsize,
  166. pcre2_general_context *gcontext);
  167. pcre2_match_data *pcre2_match_data_create_from_pattern(
  168. const pcre2_code *code, pcre2_general_context *gcontext);
  169. int pcre2_match(const pcre2_code *code, PCRE2_SPTR subject,
  170. PCRE2_SIZE length, PCRE2_SIZE startoffset,
  171. uint32_t options, pcre2_match_data *match_data,
  172. pcre2_match_context *mcontext);
  173. int pcre2_dfa_match(const pcre2_code *code, PCRE2_SPTR subject,
  174. PCRE2_SIZE length, PCRE2_SIZE startoffset,
  175. uint32_t options, pcre2_match_data *match_data,
  176. pcre2_match_context *mcontext,
  177. int *workspace, PCRE2_SIZE wscount);
  178. void pcre2_match_data_free(pcre2_match_data *match_data);
  179. PCRE2 NATIVE API AUXILIARY MATCH FUNCTIONS
  180. PCRE2_SPTR pcre2_get_mark(pcre2_match_data *match_data);
  181. PCRE2_SIZE pcre2_get_match_data_size(pcre2_match_data *match_data);
  182. PCRE2_SIZE pcre2_get_match_data_heapframes_size(
  183. pcre2_match_data *match_data);
  184. uint32_t pcre2_get_ovector_count(pcre2_match_data *match_data);
  185. PCRE2_SIZE *pcre2_get_ovector_pointer(pcre2_match_data *match_data);
  186. PCRE2_SIZE pcre2_get_startchar(pcre2_match_data *match_data);
  187. PCRE2 NATIVE API GENERAL CONTEXT FUNCTIONS
  188. pcre2_general_context *pcre2_general_context_create(
  189. void *(*private_malloc)(PCRE2_SIZE, void *),
  190. void (*private_free)(void *, void *), void *memory_data);
  191. pcre2_general_context *pcre2_general_context_copy(
  192. pcre2_general_context *gcontext);
  193. void pcre2_general_context_free(pcre2_general_context *gcontext);
  194. PCRE2 NATIVE API COMPILE CONTEXT FUNCTIONS
  195. pcre2_compile_context *pcre2_compile_context_create(
  196. pcre2_general_context *gcontext);
  197. pcre2_compile_context *pcre2_compile_context_copy(
  198. pcre2_compile_context *ccontext);
  199. void pcre2_compile_context_free(pcre2_compile_context *ccontext);
  200. int pcre2_set_bsr(pcre2_compile_context *ccontext,
  201. uint32_t value);
  202. int pcre2_set_character_tables(pcre2_compile_context *ccontext,
  203. const uint8_t *tables);
  204. int pcre2_set_compile_extra_options(pcre2_compile_context *ccontext,
  205. uint32_t extra_options);
  206. int pcre2_set_max_pattern_length(pcre2_compile_context *ccontext,
  207. PCRE2_SIZE value);
  208. int pcre2_set_max_pattern_compiled_length(
  209. pcre2_compile_context *ccontext, PCRE2_SIZE value);
  210. int pcre2_set_max_varlookbehind(pcre2_compile_contest *ccontext,
  211. uint32_t value);
  212. int pcre2_set_newline(pcre2_compile_context *ccontext,
  213. uint32_t value);
  214. int pcre2_set_parens_nest_limit(pcre2_compile_context *ccontext,
  215. uint32_t value);
  216. int pcre2_set_compile_recursion_guard(pcre2_compile_context *ccontext,
  217. int (*guard_function)(uint32_t, void *), void *user_data);
  218. PCRE2 NATIVE API MATCH CONTEXT FUNCTIONS
  219. pcre2_match_context *pcre2_match_context_create(
  220. pcre2_general_context *gcontext);
  221. pcre2_match_context *pcre2_match_context_copy(
  222. pcre2_match_context *mcontext);
  223. void pcre2_match_context_free(pcre2_match_context *mcontext);
  224. int pcre2_set_callout(pcre2_match_context *mcontext,
  225. int (*callout_function)(pcre2_callout_block *, void *),
  226. void *callout_data);
  227. int pcre2_set_substitute_callout(pcre2_match_context *mcontext,
  228. int (*callout_function)(pcre2_substitute_callout_block *, void *),
  229. void *callout_data);
  230. int pcre2_set_offset_limit(pcre2_match_context *mcontext,
  231. PCRE2_SIZE value);
  232. int pcre2_set_heap_limit(pcre2_match_context *mcontext,
  233. uint32_t value);
  234. int pcre2_set_match_limit(pcre2_match_context *mcontext,
  235. uint32_t value);
  236. int pcre2_set_depth_limit(pcre2_match_context *mcontext,
  237. uint32_t value);
  238. PCRE2 NATIVE API STRING EXTRACTION FUNCTIONS
  239. int pcre2_substring_copy_byname(pcre2_match_data *match_data,
  240. PCRE2_SPTR name, PCRE2_UCHAR *buffer, PCRE2_SIZE *bufflen);
  241. int pcre2_substring_copy_bynumber(pcre2_match_data *match_data,
  242. uint32_t number, PCRE2_UCHAR *buffer,
  243. PCRE2_SIZE *bufflen);
  244. void pcre2_substring_free(PCRE2_UCHAR *buffer);
  245. int pcre2_substring_get_byname(pcre2_match_data *match_data,
  246. PCRE2_SPTR name, PCRE2_UCHAR **bufferptr, PCRE2_SIZE *bufflen);
  247. int pcre2_substring_get_bynumber(pcre2_match_data *match_data,
  248. uint32_t number, PCRE2_UCHAR **bufferptr,
  249. PCRE2_SIZE *bufflen);
  250. int pcre2_substring_length_byname(pcre2_match_data *match_data,
  251. PCRE2_SPTR name, PCRE2_SIZE *length);
  252. int pcre2_substring_length_bynumber(pcre2_match_data *match_data,
  253. uint32_t number, PCRE2_SIZE *length);
  254. int pcre2_substring_nametable_scan(const pcre2_code *code,
  255. PCRE2_SPTR name, PCRE2_SPTR *first, PCRE2_SPTR *last);
  256. int pcre2_substring_number_from_name(const pcre2_code *code,
  257. PCRE2_SPTR name);
  258. void pcre2_substring_list_free(PCRE2_UCHAR **list);
  259. int pcre2_substring_list_get(pcre2_match_data *match_data,
  260. PCRE2_UCHAR ***listptr, PCRE2_SIZE **lengthsptr);
  261. PCRE2 NATIVE API STRING SUBSTITUTION FUNCTION
  262. int pcre2_substitute(const pcre2_code *code, PCRE2_SPTR subject,
  263. PCRE2_SIZE length, PCRE2_SIZE startoffset,
  264. uint32_t options, pcre2_match_data *match_data,
  265. pcre2_match_context *mcontext, PCRE2_SPTR replacementz,
  266. PCRE2_SIZE rlength, PCRE2_UCHAR *outputbuffer,
  267. PCRE2_SIZE *outlengthptr);
  268. PCRE2 NATIVE API JIT FUNCTIONS
  269. int pcre2_jit_compile(pcre2_code *code, uint32_t options);
  270. int pcre2_jit_match(const pcre2_code *code, PCRE2_SPTR subject,
  271. PCRE2_SIZE length, PCRE2_SIZE startoffset,
  272. uint32_t options, pcre2_match_data *match_data,
  273. pcre2_match_context *mcontext);
  274. void pcre2_jit_free_unused_memory(pcre2_general_context *gcontext);
  275. pcre2_jit_stack *pcre2_jit_stack_create(size_t startsize,
  276. size_t maxsize, pcre2_general_context *gcontext);
  277. void pcre2_jit_stack_assign(pcre2_match_context *mcontext,
  278. pcre2_jit_callback callback_function, void *callback_data);
  279. void pcre2_jit_stack_free(pcre2_jit_stack *jit_stack);
  280. PCRE2 NATIVE API SERIALIZATION FUNCTIONS
  281. int32_t pcre2_serialize_decode(pcre2_code **codes,
  282. int32_t number_of_codes, const uint8_t *bytes,
  283. pcre2_general_context *gcontext);
  284. int32_t pcre2_serialize_encode(const pcre2_code **codes,
  285. int32_t number_of_codes, uint8_t **serialized_bytes,
  286. PCRE2_SIZE *serialized_size, pcre2_general_context *gcontext);
  287. void pcre2_serialize_free(uint8_t *bytes);
  288. int32_t pcre2_serialize_get_number_of_codes(const uint8_t *bytes);
  289. PCRE2 NATIVE API AUXILIARY FUNCTIONS
  290. pcre2_code *pcre2_code_copy(const pcre2_code *code);
  291. pcre2_code *pcre2_code_copy_with_tables(const pcre2_code *code);
  292. int pcre2_get_error_message(int errorcode, PCRE2_UCHAR *buffer,
  293. PCRE2_SIZE bufflen);
  294. const uint8_t *pcre2_maketables(pcre2_general_context *gcontext);
  295. void pcre2_maketables_free(pcre2_general_context *gcontext,
  296. const uint8_t *tables);
  297. int pcre2_pattern_info(const pcre2_code *code, uint32_t what,
  298. void *where);
  299. int pcre2_callout_enumerate(const pcre2_code *code,
  300. int (*callback)(pcre2_callout_enumerate_block *, void *),
  301. void *user_data);
  302. int pcre2_config(uint32_t what, void *where);
  303. PCRE2 NATIVE API OBSOLETE FUNCTIONS
  304. int pcre2_set_recursion_limit(pcre2_match_context *mcontext,
  305. uint32_t value);
  306. int pcre2_set_recursion_memory_management(
  307. pcre2_match_context *mcontext,
  308. void *(*private_malloc)(size_t, void *),
  309. void (*private_free)(void *, void *), void *memory_data);
  310. These functions became obsolete at release 10.30 and are retained only
  311. for backward compatibility. They should not be used in new code. The
  312. first is replaced by pcre2_set_depth_limit(); the second is no longer
  313. needed and has no effect (it always returns zero).
  314. PCRE2 EXPERIMENTAL PATTERN CONVERSION FUNCTIONS
  315. pcre2_convert_context *pcre2_convert_context_create(
  316. pcre2_general_context *gcontext);
  317. pcre2_convert_context *pcre2_convert_context_copy(
  318. pcre2_convert_context *cvcontext);
  319. void pcre2_convert_context_free(pcre2_convert_context *cvcontext);
  320. int pcre2_set_glob_escape(pcre2_convert_context *cvcontext,
  321. uint32_t escape_char);
  322. int pcre2_set_glob_separator(pcre2_convert_context *cvcontext,
  323. uint32_t separator_char);
  324. int pcre2_pattern_convert(PCRE2_SPTR pattern, PCRE2_SIZE length,
  325. uint32_t options, PCRE2_UCHAR **buffer,
  326. PCRE2_SIZE *blength, pcre2_convert_context *cvcontext);
  327. void pcre2_converted_pattern_free(PCRE2_UCHAR *converted_pattern);
  328. These functions provide a way of converting non-PCRE2 patterns into
  329. patterns that can be processed by pcre2_compile(). This facility is ex-
  330. perimental and may be changed in future releases. At present, "globs"
  331. and POSIX basic and extended patterns can be converted. Details are
  332. given in the pcre2convert documentation.
  333. PCRE2 8-BIT, 16-BIT, AND 32-BIT LIBRARIES
  334. There are three PCRE2 libraries, supporting 8-bit, 16-bit, and 32-bit
  335. code units, respectively. However, there is just one header file,
  336. pcre2.h. This contains the function prototypes and other definitions
  337. for all three libraries. One, two, or all three can be installed simul-
  338. taneously. On Unix-like systems the libraries are called libpcre2-8,
  339. libpcre2-16, and libpcre2-32, and they can also co-exist with the orig-
  340. inal PCRE libraries. Every PCRE2 function comes in three different
  341. forms, one for each library, for example:
  342. pcre2_compile_8()
  343. pcre2_compile_16()
  344. pcre2_compile_32()
  345. There are also three different sets of data types:
  346. PCRE2_UCHAR8, PCRE2_UCHAR16, PCRE2_UCHAR32
  347. PCRE2_SPTR8, PCRE2_SPTR16, PCRE2_SPTR32
  348. The UCHAR types define unsigned code units of the appropriate widths.
  349. For example, PCRE2_UCHAR16 is usually defined as `uint16_t'. The SPTR
  350. types are pointers to constants of the equivalent UCHAR types, that is,
  351. they are pointers to vectors of unsigned code units.
  352. Character strings are passed to a PCRE2 library as sequences of un-
  353. signed integers in code units of the appropriate width. The length of a
  354. string may be given as a number of code units, or the string may be
  355. specified as zero-terminated.
  356. Many applications use only one code unit width. For their convenience,
  357. macros are defined whose names are the generic forms such as pcre2_com-
  358. pile() and PCRE2_SPTR. These macros use the value of the macro
  359. PCRE2_CODE_UNIT_WIDTH to generate the appropriate width-specific func-
  360. tion and macro names. PCRE2_CODE_UNIT_WIDTH is not defined by default.
  361. An application must define it to be 8, 16, or 32 before including
  362. pcre2.h in order to make use of the generic names.
  363. Applications that use more than one code unit width can be linked with
  364. more than one PCRE2 library, but must define PCRE2_CODE_UNIT_WIDTH to
  365. be 0 before including pcre2.h, and then use the real function names.
  366. Any code that is to be included in an environment where the value of
  367. PCRE2_CODE_UNIT_WIDTH is unknown should also use the real function
  368. names. (Unfortunately, it is not possible in C code to save and restore
  369. the value of a macro.)
  370. If PCRE2_CODE_UNIT_WIDTH is not defined before including pcre2.h, a
  371. compiler error occurs.
  372. When using multiple libraries in an application, you must take care
  373. when processing any particular pattern to use only functions from a
  374. single library. For example, if you want to run a match using a pat-
  375. tern that was compiled with pcre2_compile_16(), you must do so with
  376. pcre2_match_16(), not pcre2_match_8() or pcre2_match_32().
  377. In the function summaries above, and in the rest of this document and
  378. other PCRE2 documents, functions and data types are described using
  379. their generic names, without the _8, _16, or _32 suffix.
  380. PCRE2 API OVERVIEW
  381. PCRE2 has its own native API, which is described in this document.
  382. There are also some wrapper functions for the 8-bit library that corre-
  383. spond to the POSIX regular expression API, but they do not give access
  384. to all the functionality of PCRE2 and they are not thread-safe. They
  385. are described in the pcre2posix documentation. Both these APIs define a
  386. set of C function calls.
  387. The native API C data types, function prototypes, option values, and
  388. error codes are defined in the header file pcre2.h, which also contains
  389. definitions of PCRE2_MAJOR and PCRE2_MINOR, the major and minor release
  390. numbers for the library. Applications can use these to include support
  391. for different releases of PCRE2.
  392. In a Windows environment, if you want to statically link an application
  393. program against a non-dll PCRE2 library, you must define PCRE2_STATIC
  394. before including pcre2.h.
  395. The functions pcre2_compile() and pcre2_match() are used for compiling
  396. and matching regular expressions in a Perl-compatible manner. A sample
  397. program that demonstrates the simplest way of using them is provided in
  398. the file called pcre2demo.c in the PCRE2 source distribution. A listing
  399. of this program is given in the pcre2demo documentation, and the
  400. pcre2sample documentation describes how to compile and run it.
  401. The compiling and matching functions recognize various options that are
  402. passed as bits in an options argument. There are also some more compli-
  403. cated parameters such as custom memory management functions and re-
  404. source limits that are passed in "contexts" (which are just memory
  405. blocks, described below). Simple applications do not need to make use
  406. of contexts.
  407. Just-in-time (JIT) compiler support is an optional feature of PCRE2
  408. that can be built in appropriate hardware environments. It greatly
  409. speeds up the matching performance of many patterns. Programs can re-
  410. quest that it be used if available by calling pcre2_jit_compile() after
  411. a pattern has been successfully compiled by pcre2_compile(). This does
  412. nothing if JIT support is not available.
  413. More complicated programs might need to make use of the specialist
  414. functions pcre2_jit_stack_create(), pcre2_jit_stack_free(), and
  415. pcre2_jit_stack_assign() in order to control the JIT code's memory us-
  416. age.
  417. JIT matching is automatically used by pcre2_match() if it is available,
  418. unless the PCRE2_NO_JIT option is set. There is also a direct interface
  419. for JIT matching, which gives improved performance at the expense of
  420. less sanity checking. The JIT-specific functions are discussed in the
  421. pcre2jit documentation.
  422. A second matching function, pcre2_dfa_match(), which is not Perl-com-
  423. patible, is also provided. This uses a different algorithm for the
  424. matching. The alternative algorithm finds all possible matches (at a
  425. given point in the subject), and scans the subject just once (unless
  426. there are lookaround assertions). However, this algorithm does not re-
  427. turn captured substrings. A description of the two matching algorithms
  428. and their advantages and disadvantages is given in the pcre2matching
  429. documentation. There is no JIT support for pcre2_dfa_match().
  430. In addition to the main compiling and matching functions, there are
  431. convenience functions for extracting captured substrings from a subject
  432. string that has been matched by pcre2_match(). They are:
  433. pcre2_substring_copy_byname()
  434. pcre2_substring_copy_bynumber()
  435. pcre2_substring_get_byname()
  436. pcre2_substring_get_bynumber()
  437. pcre2_substring_list_get()
  438. pcre2_substring_length_byname()
  439. pcre2_substring_length_bynumber()
  440. pcre2_substring_nametable_scan()
  441. pcre2_substring_number_from_name()
  442. pcre2_substring_free() and pcre2_substring_list_free() are also pro-
  443. vided, to free memory used for extracted strings. If either of these
  444. functions is called with a NULL argument, the function returns immedi-
  445. ately without doing anything.
  446. The function pcre2_substitute() can be called to match a pattern and
  447. return a copy of the subject string with substitutions for parts that
  448. were matched.
  449. Functions whose names begin with pcre2_serialize_ are used for saving
  450. compiled patterns on disc or elsewhere, and reloading them later.
  451. Finally, there are functions for finding out information about a com-
  452. piled pattern (pcre2_pattern_info()) and about the configuration with
  453. which PCRE2 was built (pcre2_config()).
  454. Functions with names ending with _free() are used for freeing memory
  455. blocks of various sorts. In all cases, if one of these functions is
  456. called with a NULL argument, it does nothing.
  457. STRING LENGTHS AND OFFSETS
  458. The PCRE2 API uses string lengths and offsets into strings of code
  459. units in several places. These values are always of type PCRE2_SIZE,
  460. which is an unsigned integer type, currently always defined as size_t.
  461. The largest value that can be stored in such a type (that is
  462. ~(PCRE2_SIZE)0) is reserved as a special indicator for zero-terminated
  463. strings and unset offsets. Therefore, the longest string that can be
  464. handled is one less than this maximum. Note that string lengths are al-
  465. ways given in code units. Only in the 8-bit library is such a length
  466. the same as the number of bytes in the string.
  467. NEWLINES
  468. PCRE2 supports five different conventions for indicating line breaks in
  469. strings: a single CR (carriage return) character, a single LF (line-
  470. feed) character, the two-character sequence CRLF, any of the three pre-
  471. ceding, or any Unicode newline sequence. The Unicode newline sequences
  472. are the three just mentioned, plus the single characters VT (vertical
  473. tab, U+000B), FF (form feed, U+000C), NEL (next line, U+0085), LS (line
  474. separator, U+2028), and PS (paragraph separator, U+2029).
  475. Each of the first three conventions is used by at least one operating
  476. system as its standard newline sequence. When PCRE2 is built, a default
  477. can be specified. If it is not, the default is set to LF, which is the
  478. Unix standard. However, the newline convention can be changed by an ap-
  479. plication when calling pcre2_compile(), or it can be specified by spe-
  480. cial text at the start of the pattern itself; this overrides any other
  481. settings. See the pcre2pattern page for details of the special charac-
  482. ter sequences.
  483. In the PCRE2 documentation the word "newline" is used to mean "the
  484. character or pair of characters that indicate a line break". The choice
  485. of newline convention affects the handling of the dot, circumflex, and
  486. dollar metacharacters, the handling of #-comments in /x mode, and, when
  487. CRLF is a recognized line ending sequence, the match position advance-
  488. ment for a non-anchored pattern. There is more detail about this in the
  489. section on pcre2_match() options below.
  490. The choice of newline convention does not affect the interpretation of
  491. the \n or \r escape sequences, nor does it affect what \R matches; this
  492. has its own separate convention.
  493. MULTITHREADING
  494. In a multithreaded application it is important to keep thread-specific
  495. data separate from data that can be shared between threads. The PCRE2
  496. library code itself is thread-safe: it contains no static or global
  497. variables. The API is designed to be fairly simple for non-threaded ap-
  498. plications while at the same time ensuring that multithreaded applica-
  499. tions can use it.
  500. There are several different blocks of data that are used to pass infor-
  501. mation between the application and the PCRE2 libraries.
  502. The compiled pattern
  503. A pointer to the compiled form of a pattern is returned to the user
  504. when pcre2_compile() is successful. The data in the compiled pattern is
  505. fixed, and does not change when the pattern is matched. Therefore, it
  506. is thread-safe, that is, the same compiled pattern can be used by more
  507. than one thread simultaneously. For example, an application can compile
  508. all its patterns at the start, before forking off multiple threads that
  509. use them. However, if the just-in-time (JIT) optimization feature is
  510. being used, it needs separate memory stack areas for each thread. See
  511. the pcre2jit documentation for more details.
  512. In a more complicated situation, where patterns are compiled only when
  513. they are first needed, but are still shared between threads, pointers
  514. to compiled patterns must be protected from simultaneous writing by
  515. multiple threads. This is somewhat tricky to do correctly. If you know
  516. that writing to a pointer is atomic in your environment, you can use
  517. logic like this:
  518. Get a read-only (shared) lock (mutex) for pointer
  519. if (pointer == NULL)
  520. {
  521. Get a write (unique) lock for pointer
  522. if (pointer == NULL) pointer = pcre2_compile(...
  523. }
  524. Release the lock
  525. Use pointer in pcre2_match()
  526. Of course, testing for compilation errors should also be included in
  527. the code.
  528. The reason for checking the pointer a second time is as follows: Sev-
  529. eral threads may have acquired the shared lock and tested the pointer
  530. for being NULL, but only one of them will be given the write lock, with
  531. the rest kept waiting. The winning thread will compile the pattern and
  532. store the result. After this thread releases the write lock, another
  533. thread will get it, and if it does not retest pointer for being NULL,
  534. will recompile the pattern and overwrite the pointer, creating a memory
  535. leak and possibly causing other issues.
  536. In an environment where writing to a pointer may not be atomic, the
  537. above logic is not sufficient. The thread that is doing the compiling
  538. may be descheduled after writing only part of the pointer, which could
  539. cause other threads to use an invalid value. Instead of checking the
  540. pointer itself, a separate "pointer is valid" flag (that can be updated
  541. atomically) must be used:
  542. Get a read-only (shared) lock (mutex) for pointer
  543. if (!pointer_is_valid)
  544. {
  545. Get a write (unique) lock for pointer
  546. if (!pointer_is_valid)
  547. {
  548. pointer = pcre2_compile(...
  549. pointer_is_valid = TRUE
  550. }
  551. }
  552. Release the lock
  553. Use pointer in pcre2_match()
  554. If JIT is being used, but the JIT compilation is not being done immedi-
  555. ately (perhaps waiting to see if the pattern is used often enough),
  556. similar logic is required. JIT compilation updates a value within the
  557. compiled code block, so a thread must gain unique write access to the
  558. pointer before calling pcre2_jit_compile(). Alternatively,
  559. pcre2_code_copy() or pcre2_code_copy_with_tables() can be used to ob-
  560. tain a private copy of the compiled code before calling the JIT com-
  561. piler.
  562. Context blocks
  563. The next main section below introduces the idea of "contexts" in which
  564. PCRE2 functions are called. A context is nothing more than a collection
  565. of parameters that control the way PCRE2 operates. Grouping a number of
  566. parameters together in a context is a convenient way of passing them to
  567. a PCRE2 function without using lots of arguments. The parameters that
  568. are stored in contexts are in some sense "advanced features" of the
  569. API. Many straightforward applications will not need to use contexts.
  570. In a multithreaded application, if the parameters in a context are val-
  571. ues that are never changed, the same context can be used by all the
  572. threads. However, if any thread needs to change any value in a context,
  573. it must make its own thread-specific copy.
  574. Match blocks
  575. The matching functions need a block of memory for storing the results
  576. of a match. This includes details of what was matched, as well as addi-
  577. tional information such as the name of a (*MARK) setting. Each thread
  578. must provide its own copy of this memory.
  579. PCRE2 CONTEXTS
  580. Some PCRE2 functions have a lot of parameters, many of which are used
  581. only by specialist applications, for example, those that use custom
  582. memory management or non-standard character tables. To keep function
  583. argument lists at a reasonable size, and at the same time to keep the
  584. API extensible, "uncommon" parameters are passed to certain functions
  585. in a context instead of directly. A context is just a block of memory
  586. that holds the parameter values. Applications that do not need to ad-
  587. just any of the context parameters can pass NULL when a context pointer
  588. is required.
  589. There are three different types of context: a general context that is
  590. relevant for several PCRE2 operations, a compile-time context, and a
  591. match-time context.
  592. The general context
  593. At present, this context just contains pointers to (and data for) ex-
  594. ternal memory management functions that are called from several places
  595. in the PCRE2 library. The context is named `general' rather than
  596. specifically `memory' because in future other fields may be added. If
  597. you do not want to supply your own custom memory management functions,
  598. you do not need to bother with a general context. A general context is
  599. created by:
  600. pcre2_general_context *pcre2_general_context_create(
  601. void *(*private_malloc)(PCRE2_SIZE, void *),
  602. void (*private_free)(void *, void *), void *memory_data);
  603. The two function pointers specify custom memory management functions,
  604. whose prototypes are:
  605. void *private_malloc(PCRE2_SIZE, void *);
  606. void private_free(void *, void *);
  607. Whenever code in PCRE2 calls these functions, the final argument is the
  608. value of memory_data. Either of the first two arguments of the creation
  609. function may be NULL, in which case the system memory management func-
  610. tions malloc() and free() are used. (This is not currently useful, as
  611. there are no other fields in a general context, but in future there
  612. might be.) The private_malloc() function is used (if supplied) to ob-
  613. tain memory for storing the context, and all three values are saved as
  614. part of the context.
  615. Whenever PCRE2 creates a data block of any kind, the block contains a
  616. pointer to the free() function that matches the malloc() function that
  617. was used. When the time comes to free the block, this function is
  618. called.
  619. A general context can be copied by calling:
  620. pcre2_general_context *pcre2_general_context_copy(
  621. pcre2_general_context *gcontext);
  622. The memory used for a general context should be freed by calling:
  623. void pcre2_general_context_free(pcre2_general_context *gcontext);
  624. If this function is passed a NULL argument, it returns immediately
  625. without doing anything.
  626. The compile context
  627. A compile context is required if you want to provide an external func-
  628. tion for stack checking during compilation or to change the default
  629. values of any of the following compile-time parameters:
  630. What \R matches (Unicode newlines or CR, LF, CRLF only)
  631. PCRE2's character tables
  632. The newline character sequence
  633. The compile time nested parentheses limit
  634. The maximum length of the pattern string
  635. The extra options bits (none set by default)
  636. A compile context is also required if you are using custom memory man-
  637. agement. If none of these apply, just pass NULL as the context argu-
  638. ment of pcre2_compile().
  639. A compile context is created, copied, and freed by the following func-
  640. tions:
  641. pcre2_compile_context *pcre2_compile_context_create(
  642. pcre2_general_context *gcontext);
  643. pcre2_compile_context *pcre2_compile_context_copy(
  644. pcre2_compile_context *ccontext);
  645. void pcre2_compile_context_free(pcre2_compile_context *ccontext);
  646. A compile context is created with default values for its parameters.
  647. These can be changed by calling the following functions, which return 0
  648. on success, or PCRE2_ERROR_BADDATA if invalid data is detected.
  649. int pcre2_set_bsr(pcre2_compile_context *ccontext,
  650. uint32_t value);
  651. The value must be PCRE2_BSR_ANYCRLF, to specify that \R matches only
  652. CR, LF, or CRLF, or PCRE2_BSR_UNICODE, to specify that \R matches any
  653. Unicode line ending sequence. The value is used by the JIT compiler and
  654. by the two interpreted matching functions, pcre2_match() and
  655. pcre2_dfa_match().
  656. int pcre2_set_character_tables(pcre2_compile_context *ccontext,
  657. const uint8_t *tables);
  658. The value must be the result of a call to pcre2_maketables(), whose
  659. only argument is a general context. This function builds a set of char-
  660. acter tables in the current locale.
  661. int pcre2_set_compile_extra_options(pcre2_compile_context *ccontext,
  662. uint32_t extra_options);
  663. As PCRE2 has developed, almost all the 32 option bits that are avail-
  664. able in the options argument of pcre2_compile() have been used up. To
  665. avoid running out, the compile context contains a set of extra option
  666. bits which are used for some newer, assumed rarer, options. This func-
  667. tion sets those bits. It always sets all the bits (either on or off).
  668. It does not modify any existing setting. The available options are de-
  669. fined in the section entitled "Extra compile options" below.
  670. int pcre2_set_max_pattern_length(pcre2_compile_context *ccontext,
  671. PCRE2_SIZE value);
  672. This sets a maximum length, in code units, for any pattern string that
  673. is compiled with this context. If the pattern is longer, an error is
  674. generated. This facility is provided so that applications that accept
  675. patterns from external sources can limit their size. The default is the
  676. largest number that a PCRE2_SIZE variable can hold, which is effec-
  677. tively unlimited.
  678. int pcre2_set_max_pattern_compiled_length(
  679. pcre2_compile_context *ccontext, PCRE2_SIZE value);
  680. This sets a maximum size, in bytes, for the memory needed to hold the
  681. compiled version of a pattern that is compiled with this context. If
  682. the pattern needs more memory, an error is generated. This facility is
  683. provided so that applications that accept patterns from external
  684. sources can limit the amount of memory they use. The default is the
  685. largest number that a PCRE2_SIZE variable can hold, which is effec-
  686. tively unlimited.
  687. int pcre2_set_max_varlookbehind(pcre2_compile_contest *ccontext,
  688. uint32_t value);
  689. This sets a maximum length for the number of characters matched by a
  690. variable-length lookbehind assertion. The default is set when PCRE2 is
  691. built, with the ultimate default being 255, the same as Perl. Lookbe-
  692. hind assertions without a bounding length are not supported.
  693. int pcre2_set_newline(pcre2_compile_context *ccontext,
  694. uint32_t value);
  695. This specifies which characters or character sequences are to be recog-
  696. nized as newlines. The value must be one of PCRE2_NEWLINE_CR (carriage
  697. return only), PCRE2_NEWLINE_LF (linefeed only), PCRE2_NEWLINE_CRLF (the
  698. two-character sequence CR followed by LF), PCRE2_NEWLINE_ANYCRLF (any
  699. of the above), PCRE2_NEWLINE_ANY (any Unicode newline sequence), or
  700. PCRE2_NEWLINE_NUL (the NUL character, that is a binary zero).
  701. A pattern can override the value set in the compile context by starting
  702. with a sequence such as (*CRLF). See the pcre2pattern page for details.
  703. When a pattern is compiled with the PCRE2_EXTENDED or PCRE2_EX-
  704. TENDED_MORE option, the newline convention affects the recognition of
  705. the end of internal comments starting with #. The value is saved with
  706. the compiled pattern for subsequent use by the JIT compiler and by the
  707. two interpreted matching functions, pcre2_match() and
  708. pcre2_dfa_match().
  709. int pcre2_set_parens_nest_limit(pcre2_compile_context *ccontext,
  710. uint32_t value);
  711. This parameter adjusts the limit, set when PCRE2 is built (default
  712. 250), on the depth of parenthesis nesting in a pattern. This limit
  713. stops rogue patterns using up too much system stack when being com-
  714. piled. The limit applies to parentheses of all kinds, not just captur-
  715. ing parentheses.
  716. int pcre2_set_compile_recursion_guard(pcre2_compile_context *ccontext,
  717. int (*guard_function)(uint32_t, void *), void *user_data);
  718. There is at least one application that runs PCRE2 in threads with very
  719. limited system stack, where running out of stack is to be avoided at
  720. all costs. The parenthesis limit above cannot take account of how much
  721. stack is actually available during compilation. For a finer control,
  722. you can supply a function that is called whenever pcre2_compile()
  723. starts to compile a parenthesized part of a pattern. This function can
  724. check the actual stack size (or anything else that it wants to, of
  725. course).
  726. The first argument to the callout function gives the current depth of
  727. nesting, and the second is user data that is set up by the last argu-
  728. ment of pcre2_set_compile_recursion_guard(). The callout function
  729. should return zero if all is well, or non-zero to force an error.
  730. The match context
  731. A match context is required if you want to:
  732. Set up a callout function
  733. Set an offset limit for matching an unanchored pattern
  734. Change the limit on the amount of heap used when matching
  735. Change the backtracking match limit
  736. Change the backtracking depth limit
  737. Set custom memory management specifically for the match
  738. If none of these apply, just pass NULL as the context argument of
  739. pcre2_match(), pcre2_dfa_match(), or pcre2_jit_match().
  740. A match context is created, copied, and freed by the following func-
  741. tions:
  742. pcre2_match_context *pcre2_match_context_create(
  743. pcre2_general_context *gcontext);
  744. pcre2_match_context *pcre2_match_context_copy(
  745. pcre2_match_context *mcontext);
  746. void pcre2_match_context_free(pcre2_match_context *mcontext);
  747. A match context is created with default values for its parameters.
  748. These can be changed by calling the following functions, which return 0
  749. on success, or PCRE2_ERROR_BADDATA if invalid data is detected.
  750. int pcre2_set_callout(pcre2_match_context *mcontext,
  751. int (*callout_function)(pcre2_callout_block *, void *),
  752. void *callout_data);
  753. This sets up a callout function for PCRE2 to call at specified points
  754. during a matching operation. Details are given in the pcre2callout doc-
  755. umentation.
  756. int pcre2_set_substitute_callout(pcre2_match_context *mcontext,
  757. int (*callout_function)(pcre2_substitute_callout_block *, void *),
  758. void *callout_data);
  759. This sets up a callout function for PCRE2 to call after each substitu-
  760. tion made by pcre2_substitute(). Details are given in the section enti-
  761. tled "Creating a new string with substitutions" below.
  762. int pcre2_set_offset_limit(pcre2_match_context *mcontext,
  763. PCRE2_SIZE value);
  764. The offset_limit parameter limits how far an unanchored search can ad-
  765. vance in the subject string. The default value is PCRE2_UNSET. The
  766. pcre2_match() and pcre2_dfa_match() functions return PCRE2_ERROR_NO-
  767. MATCH if a match with a starting point before or at the given offset is
  768. not found. The pcre2_substitute() function makes no more substitutions.
  769. For example, if the pattern /abc/ is matched against "123abc" with an
  770. offset limit less than 3, the result is PCRE2_ERROR_NOMATCH. A match
  771. can never be found if the startoffset argument of pcre2_match(),
  772. pcre2_dfa_match(), or pcre2_substitute() is greater than the offset
  773. limit set in the match context.
  774. When using this facility, you must set the PCRE2_USE_OFFSET_LIMIT op-
  775. tion when calling pcre2_compile() so that when JIT is in use, different
  776. code can be compiled. If a match is started with a non-default match
  777. limit when PCRE2_USE_OFFSET_LIMIT is not set, an error is generated.
  778. The offset limit facility can be used to track progress when searching
  779. large subject strings or to limit the extent of global substitutions.
  780. See also the PCRE2_FIRSTLINE option, which requires a match to start
  781. before or at the first newline that follows the start of matching in
  782. the subject. If this is set with an offset limit, a match must occur in
  783. the first line and also within the offset limit. In other words,
  784. whichever limit comes first is used.
  785. int pcre2_set_heap_limit(pcre2_match_context *mcontext,
  786. uint32_t value);
  787. The heap_limit parameter specifies, in units of kibibytes (1024 bytes),
  788. the maximum amount of heap memory that pcre2_match() may use to hold
  789. backtracking information when running an interpretive match. This limit
  790. also applies to pcre2_dfa_match(), which may use the heap when process-
  791. ing patterns with a lot of nested pattern recursion or lookarounds or
  792. atomic groups. This limit does not apply to matching with the JIT opti-
  793. mization, which has its own memory control arrangements (see the
  794. pcre2jit documentation for more details). If the limit is reached, the
  795. negative error code PCRE2_ERROR_HEAPLIMIT is returned. The default
  796. limit can be set when PCRE2 is built; if it is not, the default is set
  797. very large and is essentially unlimited.
  798. A value for the heap limit may also be supplied by an item at the start
  799. of a pattern of the form
  800. (*LIMIT_HEAP=ddd)
  801. where ddd is a decimal number. However, such a setting is ignored un-
  802. less ddd is less than the limit set by the caller of pcre2_match() or,
  803. if no such limit is set, less than the default.
  804. The pcre2_match() function always needs some heap memory, so setting a
  805. value of zero guarantees a "heap limit exceeded" error. Details of how
  806. pcre2_match() uses the heap are given in the pcre2perform documenta-
  807. tion.
  808. For pcre2_dfa_match(), a vector on the system stack is used when pro-
  809. cessing pattern recursions, lookarounds, or atomic groups, and only if
  810. this is not big enough is heap memory used. In this case, setting a
  811. value of zero disables the use of the heap.
  812. int pcre2_set_match_limit(pcre2_match_context *mcontext,
  813. uint32_t value);
  814. The match_limit parameter provides a means of preventing PCRE2 from us-
  815. ing up too many computing resources when processing patterns that are
  816. not going to match, but which have a very large number of possibilities
  817. in their search trees. The classic example is a pattern that uses
  818. nested unlimited repeats.
  819. There is an internal counter in pcre2_match() that is incremented each
  820. time round its main matching loop. If this value reaches the match
  821. limit, pcre2_match() returns the negative value PCRE2_ERROR_MATCHLIMIT.
  822. This has the effect of limiting the amount of backtracking that can
  823. take place. For patterns that are not anchored, the count restarts from
  824. zero for each position in the subject string. This limit also applies
  825. to pcre2_dfa_match(), though the counting is done in a different way.
  826. When pcre2_match() is called with a pattern that was successfully
  827. processed by pcre2_jit_compile(), the way in which matching is executed
  828. is entirely different. However, there is still the possibility of run-
  829. away matching that goes on for a very long time, and so the match_limit
  830. value is also used in this case (but in a different way) to limit how
  831. long the matching can continue.
  832. The default value for the limit can be set when PCRE2 is built; the de-
  833. fault is 10 million, which handles all but the most extreme cases. A
  834. value for the match limit may also be supplied by an item at the start
  835. of a pattern of the form
  836. (*LIMIT_MATCH=ddd)
  837. where ddd is a decimal number. However, such a setting is ignored un-
  838. less ddd is less than the limit set by the caller of pcre2_match() or
  839. pcre2_dfa_match() or, if no such limit is set, less than the default.
  840. int pcre2_set_depth_limit(pcre2_match_context *mcontext,
  841. uint32_t value);
  842. This parameter limits the depth of nested backtracking in
  843. pcre2_match(). Each time a nested backtracking point is passed, a new
  844. memory frame is used to remember the state of matching at that point.
  845. Thus, this parameter indirectly limits the amount of memory that is
  846. used in a match. However, because the size of each memory frame depends
  847. on the number of capturing parentheses, the actual memory limit varies
  848. from pattern to pattern. This limit was more useful in versions before
  849. 10.30, where function recursion was used for backtracking.
  850. The depth limit is not relevant, and is ignored, when matching is done
  851. using JIT compiled code. However, it is supported by pcre2_dfa_match(),
  852. which uses it to limit the depth of nested internal recursive function
  853. calls that implement atomic groups, lookaround assertions, and pattern
  854. recursions. This limits, indirectly, the amount of system stack that is
  855. used. It was more useful in versions before 10.32, when stack memory
  856. was used for local workspace vectors for recursive function calls. From
  857. version 10.32, only local variables are allocated on the stack and as
  858. each call uses only a few hundred bytes, even a small stack can support
  859. quite a lot of recursion.
  860. If the depth of internal recursive function calls is great enough, lo-
  861. cal workspace vectors are allocated on the heap from version 10.32 on-
  862. wards, so the depth limit also indirectly limits the amount of heap
  863. memory that is used. A recursive pattern such as /(.(?2))((?1)|)/, when
  864. matched to a very long string using pcre2_dfa_match(), can use a great
  865. deal of memory. However, it is probably better to limit heap usage di-
  866. rectly by calling pcre2_set_heap_limit().
  867. The default value for the depth limit can be set when PCRE2 is built;
  868. if it is not, the default is set to the same value as the default for
  869. the match limit. If the limit is exceeded, pcre2_match() or
  870. pcre2_dfa_match() returns PCRE2_ERROR_DEPTHLIMIT. A value for the depth
  871. limit may also be supplied by an item at the start of a pattern of the
  872. form
  873. (*LIMIT_DEPTH=ddd)
  874. where ddd is a decimal number. However, such a setting is ignored un-
  875. less ddd is less than the limit set by the caller of pcre2_match() or
  876. pcre2_dfa_match() or, if no such limit is set, less than the default.
  877. CHECKING BUILD-TIME OPTIONS
  878. int pcre2_config(uint32_t what, void *where);
  879. The function pcre2_config() makes it possible for a PCRE2 client to
  880. find the value of certain configuration parameters and to discover
  881. which optional features have been compiled into the PCRE2 library. The
  882. pcre2build documentation has more details about these features.
  883. The first argument for pcre2_config() specifies which information is
  884. required. The second argument is a pointer to memory into which the in-
  885. formation is placed. If NULL is passed, the function returns the amount
  886. of memory that is needed for the requested information. For calls that
  887. return numerical values, the value is in bytes; when requesting these
  888. values, where should point to appropriately aligned memory. For calls
  889. that return strings, the required length is given in code units, not
  890. counting the terminating zero.
  891. When requesting information, the returned value from pcre2_config() is
  892. non-negative on success, or the negative error code PCRE2_ERROR_BADOP-
  893. TION if the value in the first argument is not recognized. The follow-
  894. ing information is available:
  895. PCRE2_CONFIG_BSR
  896. The output is a uint32_t integer whose value indicates what character
  897. sequences the \R escape sequence matches by default. A value of
  898. PCRE2_BSR_UNICODE means that \R matches any Unicode line ending se-
  899. quence; a value of PCRE2_BSR_ANYCRLF means that \R matches only CR, LF,
  900. or CRLF. The default can be overridden when a pattern is compiled.
  901. PCRE2_CONFIG_COMPILED_WIDTHS
  902. The output is a uint32_t integer whose lower bits indicate which code
  903. unit widths were selected when PCRE2 was built. The 1-bit indicates
  904. 8-bit support, and the 2-bit and 4-bit indicate 16-bit and 32-bit sup-
  905. port, respectively.
  906. PCRE2_CONFIG_DEPTHLIMIT
  907. The output is a uint32_t integer that gives the default limit for the
  908. depth of nested backtracking in pcre2_match() or the depth of nested
  909. recursions, lookarounds, and atomic groups in pcre2_dfa_match(). Fur-
  910. ther details are given with pcre2_set_depth_limit() above.
  911. PCRE2_CONFIG_HEAPLIMIT
  912. The output is a uint32_t integer that gives, in kibibytes, the default
  913. limit for the amount of heap memory used by pcre2_match() or
  914. pcre2_dfa_match(). Further details are given with
  915. pcre2_set_heap_limit() above.
  916. PCRE2_CONFIG_JIT
  917. The output is a uint32_t integer that is set to one if support for
  918. just-in-time compiling is included in the library; otherwise it is set
  919. to zero. Note that having the support in the library does not guarantee
  920. that JIT will be used for any given match. See the pcre2jit documenta-
  921. tion for more details.
  922. PCRE2_CONFIG_JITTARGET
  923. The where argument should point to a buffer that is at least 48 code
  924. units long. (The exact length required can be found by calling
  925. pcre2_config() with where set to NULL.) The buffer is filled with a
  926. string that contains the name of the architecture for which the JIT
  927. compiler is configured, for example "x86 32bit (little endian + un-
  928. aligned)". If JIT support is not available, PCRE2_ERROR_BADOPTION is
  929. returned, otherwise the number of code units used is returned. This is
  930. the length of the string, plus one unit for the terminating zero.
  931. PCRE2_CONFIG_LINKSIZE
  932. The output is a uint32_t integer that contains the number of bytes used
  933. for internal linkage in compiled regular expressions. When PCRE2 is
  934. configured, the value can be set to 2, 3, or 4, with the default being
  935. 2. This is the value that is returned by pcre2_config(). However, when
  936. the 16-bit library is compiled, a value of 3 is rounded up to 4, and
  937. when the 32-bit library is compiled, internal linkages always use 4
  938. bytes, so the configured value is not relevant.
  939. The default value of 2 for the 8-bit and 16-bit libraries is sufficient
  940. for all but the most massive patterns, since it allows the size of the
  941. compiled pattern to be up to 65535 code units. Larger values allow
  942. larger regular expressions to be compiled by those two libraries, but
  943. at the expense of slower matching.
  944. PCRE2_CONFIG_MATCHLIMIT
  945. The output is a uint32_t integer that gives the default match limit for
  946. pcre2_match(). Further details are given with pcre2_set_match_limit()
  947. above.
  948. PCRE2_CONFIG_NEWLINE
  949. The output is a uint32_t integer whose value specifies the default
  950. character sequence that is recognized as meaning "newline". The values
  951. are:
  952. PCRE2_NEWLINE_CR Carriage return (CR)
  953. PCRE2_NEWLINE_LF Linefeed (LF)
  954. PCRE2_NEWLINE_CRLF Carriage return, linefeed (CRLF)
  955. PCRE2_NEWLINE_ANY Any Unicode line ending
  956. PCRE2_NEWLINE_ANYCRLF Any of CR, LF, or CRLF
  957. PCRE2_NEWLINE_NUL The NUL character (binary zero)
  958. The default should normally correspond to the standard sequence for
  959. your operating system.
  960. PCRE2_CONFIG_NEVER_BACKSLASH_C
  961. The output is a uint32_t integer that is set to one if the use of \C
  962. was permanently disabled when PCRE2 was built; otherwise it is set to
  963. zero.
  964. PCRE2_CONFIG_PARENSLIMIT
  965. The output is a uint32_t integer that gives the maximum depth of nest-
  966. ing of parentheses (of any kind) in a pattern. This limit is imposed to
  967. cap the amount of system stack used when a pattern is compiled. It is
  968. specified when PCRE2 is built; the default is 250. This limit does not
  969. take into account the stack that may already be used by the calling ap-
  970. plication. For finer control over compilation stack usage, see
  971. pcre2_set_compile_recursion_guard().
  972. PCRE2_CONFIG_STACKRECURSE
  973. This parameter is obsolete and should not be used in new code. The out-
  974. put is a uint32_t integer that is always set to zero.
  975. PCRE2_CONFIG_TABLES_LENGTH
  976. The output is a uint32_t integer that gives the length of PCRE2's char-
  977. acter processing tables in bytes. For details of these tables see the
  978. section on locale support below.
  979. PCRE2_CONFIG_UNICODE_VERSION
  980. The where argument should point to a buffer that is at least 24 code
  981. units long. (The exact length required can be found by calling
  982. pcre2_config() with where set to NULL.) If PCRE2 has been compiled
  983. without Unicode support, the buffer is filled with the text "Unicode
  984. not supported". Otherwise, the Unicode version string (for example,
  985. "8.0.0") is inserted. The number of code units used is returned. This
  986. is the length of the string plus one unit for the terminating zero.
  987. PCRE2_CONFIG_UNICODE
  988. The output is a uint32_t integer that is set to one if Unicode support
  989. is available; otherwise it is set to zero. Unicode support implies UTF
  990. support.
  991. PCRE2_CONFIG_VERSION
  992. The where argument should point to a buffer that is at least 24 code
  993. units long. (The exact length required can be found by calling
  994. pcre2_config() with where set to NULL.) The buffer is filled with the
  995. PCRE2 version string, zero-terminated. The number of code units used is
  996. returned. This is the length of the string plus one unit for the termi-
  997. nating zero.
  998. COMPILING A PATTERN
  999. pcre2_code *pcre2_compile(PCRE2_SPTR pattern, PCRE2_SIZE length,
  1000. uint32_t options, int *errorcode, PCRE2_SIZE *erroroffset,
  1001. pcre2_compile_context *ccontext);
  1002. void pcre2_code_free(pcre2_code *code);
  1003. pcre2_code *pcre2_code_copy(const pcre2_code *code);
  1004. pcre2_code *pcre2_code_copy_with_tables(const pcre2_code *code);
  1005. The pcre2_compile() function compiles a pattern into an internal form.
  1006. The pattern is defined by a pointer to a string of code units and a
  1007. length in code units. If the pattern is zero-terminated, the length can
  1008. be specified as PCRE2_ZERO_TERMINATED. A NULL pattern pointer with a
  1009. length of zero is treated as an empty string (NULL with a non-zero
  1010. length causes an error return). The function returns a pointer to a
  1011. block of memory that contains the compiled pattern and related data, or
  1012. NULL if an error occurred.
  1013. If the compile context argument ccontext is NULL, memory for the com-
  1014. piled pattern is obtained by calling malloc(). Otherwise, it is ob-
  1015. tained from the same memory function that was used for the compile con-
  1016. text. The caller must free the memory by calling pcre2_code_free() when
  1017. it is no longer needed. If pcre2_code_free() is called with a NULL ar-
  1018. gument, it returns immediately, without doing anything.
  1019. The function pcre2_code_copy() makes a copy of the compiled code in new
  1020. memory, using the same memory allocator as was used for the original.
  1021. However, if the code has been processed by the JIT compiler (see be-
  1022. low), the JIT information cannot be copied (because it is position-de-
  1023. pendent). The new copy can initially be used only for non-JIT match-
  1024. ing, though it can be passed to pcre2_jit_compile() if required. If
  1025. pcre2_code_copy() is called with a NULL argument, it returns NULL.
  1026. The pcre2_code_copy() function provides a way for individual threads in
  1027. a multithreaded application to acquire a private copy of shared com-
  1028. piled code. However, it does not make a copy of the character tables
  1029. used by the compiled pattern; the new pattern code points to the same
  1030. tables as the original code. (See "Locale Support" below for details
  1031. of these character tables.) In many applications the same tables are
  1032. used throughout, so this behaviour is appropriate. Nevertheless, there
  1033. are occasions when a copy of a compiled pattern and the relevant tables
  1034. are needed. The pcre2_code_copy_with_tables() provides this facility.
  1035. Copies of both the code and the tables are made, with the new code
  1036. pointing to the new tables. The memory for the new tables is automati-
  1037. cally freed when pcre2_code_free() is called for the new copy of the
  1038. compiled code. If pcre2_code_copy_with_tables() is called with a NULL
  1039. argument, it returns NULL.
  1040. NOTE: When one of the matching functions is called, pointers to the
  1041. compiled pattern and the subject string are set in the match data block
  1042. so that they can be referenced by the substring extraction functions
  1043. after a successful match. After running a match, you must not free a
  1044. compiled pattern or a subject string until after all operations on the
  1045. match data block have taken place, unless, in the case of the subject
  1046. string, you have used the PCRE2_COPY_MATCHED_SUBJECT option, which is
  1047. described in the section entitled "Option bits for pcre2_match()" be-
  1048. low.
  1049. The options argument for pcre2_compile() contains various bit settings
  1050. that affect the compilation. It should be zero if none of them are re-
  1051. quired. The available options are described below. Some of them (in
  1052. particular, those that are compatible with Perl, but some others as
  1053. well) can also be set and unset from within the pattern (see the de-
  1054. tailed description in the pcre2pattern documentation).
  1055. For those options that can be different in different parts of the pat-
  1056. tern, the contents of the options argument specifies their settings at
  1057. the start of compilation. The PCRE2_ANCHORED, PCRE2_ENDANCHORED, and
  1058. PCRE2_NO_UTF_CHECK options can be set at the time of matching as well
  1059. as at compile time.
  1060. Some additional options and less frequently required compile-time para-
  1061. meters (for example, the newline setting) can be provided in a compile
  1062. context (as described above).
  1063. If errorcode or erroroffset is NULL, pcre2_compile() returns NULL imme-
  1064. diately. Otherwise, the variables to which these point are set to an
  1065. error code and an offset (number of code units) within the pattern, re-
  1066. spectively, when pcre2_compile() returns NULL because a compilation er-
  1067. ror has occurred.
  1068. There are nearly 100 positive error codes that pcre2_compile() may re-
  1069. turn if it finds an error in the pattern. There are also some negative
  1070. error codes that are used for invalid UTF strings when validity check-
  1071. ing is in force. These are the same as given by pcre2_match() and
  1072. pcre2_dfa_match(), and are described in the pcre2unicode documentation.
  1073. There is no separate documentation for the positive error codes, be-
  1074. cause the textual error messages that are obtained by calling the
  1075. pcre2_get_error_message() function (see "Obtaining a textual error mes-
  1076. sage" below) should be self-explanatory. Macro names starting with
  1077. PCRE2_ERROR_ are defined for both positive and negative error codes in
  1078. pcre2.h. When compilation is successful errorcode is set to a value
  1079. that returns the message "no error" if passed to pcre2_get_error_mes-
  1080. sage().
  1081. The value returned in erroroffset is an indication of where in the pat-
  1082. tern an error occurred. When there is no error, zero is returned. A
  1083. non-zero value is not necessarily the furthest point in the pattern
  1084. that was read. For example, after the error "lookbehind assertion is
  1085. not fixed length", the error offset points to the start of the failing
  1086. assertion. For an invalid UTF-8 or UTF-16 string, the offset is that of
  1087. the first code unit of the failing character.
  1088. Some errors are not detected until the whole pattern has been scanned;
  1089. in these cases, the offset passed back is the length of the pattern.
  1090. Note that the offset is in code units, not characters, even in a UTF
  1091. mode. It may sometimes point into the middle of a UTF-8 or UTF-16 char-
  1092. acter.
  1093. This code fragment shows a typical straightforward call to pcre2_com-
  1094. pile():
  1095. pcre2_code *re;
  1096. PCRE2_SIZE erroffset;
  1097. int errorcode;
  1098. re = pcre2_compile(
  1099. "^A.*Z", /* the pattern */
  1100. PCRE2_ZERO_TERMINATED, /* the pattern is zero-terminated */
  1101. 0, /* default options */
  1102. &errorcode, /* for error code */
  1103. &erroffset, /* for error offset */
  1104. NULL); /* no compile context */
  1105. Main compile options
  1106. The following names for option bits are defined in the pcre2.h header
  1107. file:
  1108. PCRE2_ANCHORED
  1109. If this bit is set, the pattern is forced to be "anchored", that is, it
  1110. is constrained to match only at the first matching point in the string
  1111. that is being searched (the "subject string"). This effect can also be
  1112. achieved by appropriate constructs in the pattern itself, which is the
  1113. only way to do it in Perl.
  1114. PCRE2_ALLOW_EMPTY_CLASS
  1115. By default, for compatibility with Perl, a closing square bracket that
  1116. immediately follows an opening one is treated as a data character for
  1117. the class. When PCRE2_ALLOW_EMPTY_CLASS is set, it terminates the
  1118. class, which therefore contains no characters and so can never match.
  1119. PCRE2_ALT_BSUX
  1120. This option request alternative handling of three escape sequences,
  1121. which makes PCRE2's behaviour more like ECMAscript (aka JavaScript).
  1122. When it is set:
  1123. (1) \U matches an upper case "U" character; by default \U causes a com-
  1124. pile time error (Perl uses \U to upper case subsequent characters).
  1125. (2) \u matches a lower case "u" character unless it is followed by four
  1126. hexadecimal digits, in which case the hexadecimal number defines the
  1127. code point to match. By default, \u causes a compile time error (Perl
  1128. uses it to upper case the following character).
  1129. (3) \x matches a lower case "x" character unless it is followed by two
  1130. hexadecimal digits, in which case the hexadecimal number defines the
  1131. code point to match. By default, as in Perl, a hexadecimal number is
  1132. always expected after \x, but it may have zero, one, or two digits (so,
  1133. for example, \xz matches a binary zero character followed by z).
  1134. ECMAscript 6 added additional functionality to \u. This can be accessed
  1135. using the PCRE2_EXTRA_ALT_BSUX extra option (see "Extra compile op-
  1136. tions" below). Note that this alternative escape handling applies only
  1137. to patterns. Neither of these options affects the processing of re-
  1138. placement strings passed to pcre2_substitute().
  1139. PCRE2_ALT_CIRCUMFLEX
  1140. In multiline mode (when PCRE2_MULTILINE is set), the circumflex
  1141. metacharacter matches at the start of the subject (unless PCRE2_NOTBOL
  1142. is set), and also after any internal newline. However, it does not
  1143. match after a newline at the end of the subject, for compatibility with
  1144. Perl. If you want a multiline circumflex also to match after a termi-
  1145. nating newline, you must set PCRE2_ALT_CIRCUMFLEX.
  1146. PCRE2_ALT_VERBNAMES
  1147. By default, for compatibility with Perl, the name in any verb sequence
  1148. such as (*MARK:NAME) is any sequence of characters that does not in-
  1149. clude a closing parenthesis. The name is not processed in any way, and
  1150. it is not possible to include a closing parenthesis in the name. How-
  1151. ever, if the PCRE2_ALT_VERBNAMES option is set, normal backslash pro-
  1152. cessing is applied to verb names and only an unescaped closing paren-
  1153. thesis terminates the name. A closing parenthesis can be included in a
  1154. name either as \) or between \Q and \E. If the PCRE2_EXTENDED or
  1155. PCRE2_EXTENDED_MORE option is set with PCRE2_ALT_VERBNAMES, unescaped
  1156. whitespace in verb names is skipped and #-comments are recognized, ex-
  1157. actly as in the rest of the pattern.
  1158. PCRE2_AUTO_CALLOUT
  1159. If this bit is set, pcre2_compile() automatically inserts callout
  1160. items, all with number 255, before each pattern item, except immedi-
  1161. ately before or after an explicit callout in the pattern. For discus-
  1162. sion of the callout facility, see the pcre2callout documentation.
  1163. PCRE2_CASELESS
  1164. If this bit is set, letters in the pattern match both upper and lower
  1165. case letters in the subject. It is equivalent to Perl's /i option, and
  1166. it can be changed within a pattern by a (?i) option setting. If either
  1167. PCRE2_UTF or PCRE2_UCP is set, Unicode properties are used for all
  1168. characters with more than one other case, and for all characters whose
  1169. code points are greater than U+007F. Note that there are two ASCII
  1170. characters, K and S, that, in addition to their lower case ASCII equiv-
  1171. alents, are case-equivalent with U+212A (Kelvin sign) and U+017F (long
  1172. S) respectively. If you do not want this case equivalence, you can sup-
  1173. press it by setting PCRE2_EXTRA_CASELESS_RESTRICT.
  1174. For lower valued characters with only one other case, a lookup table is
  1175. used for speed. When neither PCRE2_UTF nor PCRE2_UCP is set, a lookup
  1176. table is used for all code points less than 256, and higher code points
  1177. (available only in 16-bit or 32-bit mode) are treated as not having an-
  1178. other case.
  1179. PCRE2_DOLLAR_ENDONLY
  1180. If this bit is set, a dollar metacharacter in the pattern matches only
  1181. at the end of the subject string. Without this option, a dollar also
  1182. matches immediately before a newline at the end of the string (but not
  1183. before any other newlines). The PCRE2_DOLLAR_ENDONLY option is ignored
  1184. if PCRE2_MULTILINE is set. There is no equivalent to this option in
  1185. Perl, and no way to set it within a pattern.
  1186. PCRE2_DOTALL
  1187. If this bit is set, a dot metacharacter in the pattern matches any
  1188. character, including one that indicates a newline. However, it only
  1189. ever matches one character, even if newlines are coded as CRLF. Without
  1190. this option, a dot does not match when the current position in the sub-
  1191. ject is at a newline. This option is equivalent to Perl's /s option,
  1192. and it can be changed within a pattern by a (?s) option setting. A neg-
  1193. ative class such as [^a] always matches newline characters, and the \N
  1194. escape sequence always matches a non-newline character, independent of
  1195. the setting of PCRE2_DOTALL.
  1196. PCRE2_DUPNAMES
  1197. If this bit is set, names used to identify capture groups need not be
  1198. unique. This can be helpful for certain types of pattern when it is
  1199. known that only one instance of the named group can ever be matched.
  1200. There are more details of named capture groups below; see also the
  1201. pcre2pattern documentation.
  1202. PCRE2_ENDANCHORED
  1203. If this bit is set, the end of any pattern match must be right at the
  1204. end of the string being searched (the "subject string"). If the pattern
  1205. match succeeds by reaching (*ACCEPT), but does not reach the end of the
  1206. subject, the match fails at the current starting point. For unanchored
  1207. patterns, a new match is then tried at the next starting point. How-
  1208. ever, if the match succeeds by reaching the end of the pattern, but not
  1209. the end of the subject, backtracking occurs and an alternative match
  1210. may be found. Consider these two patterns:
  1211. .(*ACCEPT)|..
  1212. .|..
  1213. If matched against "abc" with PCRE2_ENDANCHORED set, the first matches
  1214. "c" whereas the second matches "bc". The effect of PCRE2_ENDANCHORED
  1215. can also be achieved by appropriate constructs in the pattern itself,
  1216. which is the only way to do it in Perl.
  1217. For DFA matching with pcre2_dfa_match(), PCRE2_ENDANCHORED applies only
  1218. to the first (that is, the longest) matched string. Other parallel
  1219. matches, which are necessarily substrings of the first one, must obvi-
  1220. ously end before the end of the subject.
  1221. PCRE2_EXTENDED
  1222. If this bit is set, most white space characters in the pattern are to-
  1223. tally ignored except when escaped, inside a character class, or inside
  1224. a \Q...\E sequence. However, white space is not allowed within se-
  1225. quences such as (?> that introduce various parenthesized groups, nor
  1226. within numerical quantifiers such as {1,3}. Ignorable white space is
  1227. permitted between an item and a following quantifier and between a
  1228. quantifier and a following + that indicates possessiveness. PCRE2_EX-
  1229. TENDED is equivalent to Perl's /x option, and it can be changed within
  1230. a pattern by a (?x) option setting.
  1231. When PCRE2 is compiled without Unicode support, PCRE2_EXTENDED recog-
  1232. nizes as white space only those characters with code points less than
  1233. 256 that are flagged as white space in its low-character table. The ta-
  1234. ble is normally created by pcre2_maketables(), which uses the isspace()
  1235. function to identify space characters. In most ASCII environments, the
  1236. relevant characters are those with code points 0x0009 (tab), 0x000A
  1237. (linefeed), 0x000B (vertical tab), 0x000C (formfeed), 0x000D (carriage
  1238. return), and 0x0020 (space).
  1239. When PCRE2 is compiled with Unicode support, in addition to these char-
  1240. acters, five more Unicode "Pattern White Space" characters are recog-
  1241. nized by PCRE2_EXTENDED. These are U+0085 (next line), U+200E (left-to-
  1242. right mark), U+200F (right-to-left mark), U+2028 (line separator), and
  1243. U+2029 (paragraph separator). This set of characters is the same as
  1244. recognized by Perl's /x option. Note that the horizontal and vertical
  1245. space characters that are matched by the \h and \v escapes in patterns
  1246. are a much bigger set.
  1247. As well as ignoring most white space, PCRE2_EXTENDED also causes char-
  1248. acters between an unescaped # outside a character class and the next
  1249. newline, inclusive, to be ignored, which makes it possible to include
  1250. comments inside complicated patterns. Note that the end of this type of
  1251. comment is a literal newline sequence in the pattern; escape sequences
  1252. that happen to represent a newline do not count.
  1253. Which characters are interpreted as newlines can be specified by a set-
  1254. ting in the compile context that is passed to pcre2_compile() or by a
  1255. special sequence at the start of the pattern, as described in the sec-
  1256. tion entitled "Newline conventions" in the pcre2pattern documentation.
  1257. A default is defined when PCRE2 is built.
  1258. PCRE2_EXTENDED_MORE
  1259. This option has the effect of PCRE2_EXTENDED, but, in addition, un-
  1260. escaped space and horizontal tab characters are ignored inside a char-
  1261. acter class. Note: only these two characters are ignored, not the full
  1262. set of pattern white space characters that are ignored outside a char-
  1263. acter class. PCRE2_EXTENDED_MORE is equivalent to Perl's /xx option,
  1264. and it can be changed within a pattern by a (?xx) option setting.
  1265. PCRE2_FIRSTLINE
  1266. If this option is set, the start of an unanchored pattern match must be
  1267. before or at the first newline in the subject string following the
  1268. start of matching, though the matched text may continue over the new-
  1269. line. If startoffset is non-zero, the limiting newline is not necessar-
  1270. ily the first newline in the subject. For example, if the subject
  1271. string is "abc\nxyz" (where \n represents a single-character newline) a
  1272. pattern match for "yz" succeeds with PCRE2_FIRSTLINE if startoffset is
  1273. greater than 3. See also PCRE2_USE_OFFSET_LIMIT, which provides a more
  1274. general limiting facility. If PCRE2_FIRSTLINE is set with an offset
  1275. limit, a match must occur in the first line and also within the offset
  1276. limit. In other words, whichever limit comes first is used. This option
  1277. has no effect for anchored patterns.
  1278. PCRE2_LITERAL
  1279. If this option is set, all meta-characters in the pattern are disabled,
  1280. and it is treated as a literal string. Matching literal strings with a
  1281. regular expression engine is not the most efficient way of doing it. If
  1282. you are doing a lot of literal matching and are worried about effi-
  1283. ciency, you should consider using other approaches. The only other main
  1284. options that are allowed with PCRE2_LITERAL are: PCRE2_ANCHORED,
  1285. PCRE2_ENDANCHORED, PCRE2_AUTO_CALLOUT, PCRE2_CASELESS, PCRE2_FIRSTLINE,
  1286. PCRE2_MATCH_INVALID_UTF, PCRE2_NO_START_OPTIMIZE, PCRE2_NO_UTF_CHECK,
  1287. PCRE2_UTF, and PCRE2_USE_OFFSET_LIMIT. The extra options PCRE2_EX-
  1288. TRA_MATCH_LINE and PCRE2_EXTRA_MATCH_WORD are also supported. Any other
  1289. options cause an error.
  1290. PCRE2_MATCH_INVALID_UTF
  1291. This option forces PCRE2_UTF (see below) and also enables support for
  1292. matching by pcre2_match() in subject strings that contain invalid UTF
  1293. sequences. Note, however, that the 16-bit and 32-bit PCRE2 libraries
  1294. process strings as sequences of uint16_t or uint32_t code points. They
  1295. cannot find valid UTF sequences within an arbitrary string of bytes un-
  1296. less such sequences are suitably aligned. This facility is not sup-
  1297. ported for DFA matching. For details, see the pcre2unicode documenta-
  1298. tion.
  1299. PCRE2_MATCH_UNSET_BACKREF
  1300. If this option is set, a backreference to an unset capture group
  1301. matches an empty string (by default this causes the current matching
  1302. alternative to fail). A pattern such as (\1)(a) succeeds when this op-
  1303. tion is set (assuming it can find an "a" in the subject), whereas it
  1304. fails by default, for Perl compatibility. Setting this option makes
  1305. PCRE2 behave more like ECMAscript (aka JavaScript).
  1306. PCRE2_MULTILINE
  1307. By default, for the purposes of matching "start of line" and "end of
  1308. line", PCRE2 treats the subject string as consisting of a single line
  1309. of characters, even if it actually contains newlines. The "start of
  1310. line" metacharacter (^) matches only at the start of the string, and
  1311. the "end of line" metacharacter ($) matches only at the end of the
  1312. string, or before a terminating newline (except when PCRE2_DOLLAR_EN-
  1313. DONLY is set). Note, however, that unless PCRE2_DOTALL is set, the "any
  1314. character" metacharacter (.) does not match at a newline. This behav-
  1315. iour (for ^, $, and dot) is the same as Perl.
  1316. When PCRE2_MULTILINE it is set, the "start of line" and "end of line"
  1317. constructs match immediately following or immediately before internal
  1318. newlines in the subject string, respectively, as well as at the very
  1319. start and end. This is equivalent to Perl's /m option, and it can be
  1320. changed within a pattern by a (?m) option setting. Note that the "start
  1321. of line" metacharacter does not match after a newline at the end of the
  1322. subject, for compatibility with Perl. However, you can change this by
  1323. setting the PCRE2_ALT_CIRCUMFLEX option. If there are no newlines in a
  1324. subject string, or no occurrences of ^ or $ in a pattern, setting
  1325. PCRE2_MULTILINE has no effect.
  1326. PCRE2_NEVER_BACKSLASH_C
  1327. This option locks out the use of \C in the pattern that is being com-
  1328. piled. This escape can cause unpredictable behaviour in UTF-8 or
  1329. UTF-16 modes, because it may leave the current matching point in the
  1330. middle of a multi-code-unit character. This option may be useful in ap-
  1331. plications that process patterns from external sources. Note that there
  1332. is also a build-time option that permanently locks out the use of \C.
  1333. PCRE2_NEVER_UCP
  1334. This option locks out the use of Unicode properties for handling \B,
  1335. \b, \D, \d, \S, \s, \W, \w, and some of the POSIX character classes, as
  1336. described for the PCRE2_UCP option below. In particular, it prevents
  1337. the creator of the pattern from enabling this facility by starting the
  1338. pattern with (*UCP). This option may be useful in applications that
  1339. process patterns from external sources. The option combination PCRE_UCP
  1340. and PCRE_NEVER_UCP causes an error.
  1341. PCRE2_NEVER_UTF
  1342. This option locks out interpretation of the pattern as UTF-8, UTF-16,
  1343. or UTF-32, depending on which library is in use. In particular, it pre-
  1344. vents the creator of the pattern from switching to UTF interpretation
  1345. by starting the pattern with (*UTF). This option may be useful in ap-
  1346. plications that process patterns from external sources. The combination
  1347. of PCRE2_UTF and PCRE2_NEVER_UTF causes an error.
  1348. PCRE2_NO_AUTO_CAPTURE
  1349. If this option is set, it disables the use of numbered capturing paren-
  1350. theses in the pattern. Any opening parenthesis that is not followed by
  1351. ? behaves as if it were followed by ?: but named parentheses can still
  1352. be used for capturing (and they acquire numbers in the usual way). This
  1353. is the same as Perl's /n option. Note that, when this option is set,
  1354. references to capture groups (backreferences or recursion/subroutine
  1355. calls) may only refer to named groups, though the reference can be by
  1356. name or by number.
  1357. PCRE2_NO_AUTO_POSSESS
  1358. If this option is set, it disables "auto-possessification", which is an
  1359. optimization that, for example, turns a+b into a++b in order to avoid
  1360. backtracks into a+ that can never be successful. However, if callouts
  1361. are in use, auto-possessification means that some callouts are never
  1362. taken. You can set this option if you want the matching functions to do
  1363. a full unoptimized search and run all the callouts, but it is mainly
  1364. provided for testing purposes.
  1365. PCRE2_NO_DOTSTAR_ANCHOR
  1366. If this option is set, it disables an optimization that is applied when
  1367. .* is the first significant item in a top-level branch of a pattern,
  1368. and all the other branches also start with .* or with \A or \G or ^.
  1369. The optimization is automatically disabled for .* if it is inside an
  1370. atomic group or a capture group that is the subject of a backreference,
  1371. or if the pattern contains (*PRUNE) or (*SKIP). When the optimization
  1372. is not disabled, such a pattern is automatically anchored if
  1373. PCRE2_DOTALL is set for all the .* items and PCRE2_MULTILINE is not set
  1374. for any ^ items. Otherwise, the fact that any match must start either
  1375. at the start of the subject or following a newline is remembered. Like
  1376. other optimizations, this can cause callouts to be skipped.
  1377. PCRE2_NO_START_OPTIMIZE
  1378. This is an option whose main effect is at matching time. It does not
  1379. change what pcre2_compile() generates, but it does affect the output of
  1380. the JIT compiler.
  1381. There are a number of optimizations that may occur at the start of a
  1382. match, in order to speed up the process. For example, if it is known
  1383. that an unanchored match must start with a specific code unit value,
  1384. the matching code searches the subject for that value, and fails imme-
  1385. diately if it cannot find it, without actually running the main match-
  1386. ing function. This means that a special item such as (*COMMIT) at the
  1387. start of a pattern is not considered until after a suitable starting
  1388. point for the match has been found. Also, when callouts or (*MARK)
  1389. items are in use, these "start-up" optimizations can cause them to be
  1390. skipped if the pattern is never actually used. The start-up optimiza-
  1391. tions are in effect a pre-scan of the subject that takes place before
  1392. the pattern is run.
  1393. The PCRE2_NO_START_OPTIMIZE option disables the start-up optimizations,
  1394. possibly causing performance to suffer, but ensuring that in cases
  1395. where the result is "no match", the callouts do occur, and that items
  1396. such as (*COMMIT) and (*MARK) are considered at every possible starting
  1397. position in the subject string.
  1398. Setting PCRE2_NO_START_OPTIMIZE may change the outcome of a matching
  1399. operation. Consider the pattern
  1400. (*COMMIT)ABC
  1401. When this is compiled, PCRE2 records the fact that a match must start
  1402. with the character "A". Suppose the subject string is "DEFABC". The
  1403. start-up optimization scans along the subject, finds "A" and runs the
  1404. first match attempt from there. The (*COMMIT) item means that the pat-
  1405. tern must match the current starting position, which in this case, it
  1406. does. However, if the same match is run with PCRE2_NO_START_OPTIMIZE
  1407. set, the initial scan along the subject string does not happen. The
  1408. first match attempt is run starting from "D" and when this fails,
  1409. (*COMMIT) prevents any further matches being tried, so the overall re-
  1410. sult is "no match".
  1411. As another start-up optimization makes use of a minimum length for a
  1412. matching subject, which is recorded when possible. Consider the pattern
  1413. (*MARK:1)B(*MARK:2)(X|Y)
  1414. The minimum length for a match is two characters. If the subject is
  1415. "XXBB", the "starting character" optimization skips "XX", then tries to
  1416. match "BB", which is long enough. In the process, (*MARK:2) is encoun-
  1417. tered and remembered. When the match attempt fails, the next "B" is
  1418. found, but there is only one character left, so there are no more at-
  1419. tempts, and "no match" is returned with the "last mark seen" set to
  1420. "2". If NO_START_OPTIMIZE is set, however, matches are tried at every
  1421. possible starting position, including at the end of the subject, where
  1422. (*MARK:1) is encountered, but there is no "B", so the "last mark seen"
  1423. that is returned is "1". In this case, the optimizations do not affect
  1424. the overall match result, which is still "no match", but they do affect
  1425. the auxiliary information that is returned.
  1426. PCRE2_NO_UTF_CHECK
  1427. When PCRE2_UTF is set, the validity of the pattern as a UTF string is
  1428. automatically checked. There are discussions about the validity of
  1429. UTF-8 strings, UTF-16 strings, and UTF-32 strings in the pcre2unicode
  1430. document. If an invalid UTF sequence is found, pcre2_compile() returns
  1431. a negative error code.
  1432. If you know that your pattern is a valid UTF string, and you want to
  1433. skip this check for performance reasons, you can set the
  1434. PCRE2_NO_UTF_CHECK option. When it is set, the effect of passing an in-
  1435. valid UTF string as a pattern is undefined. It may cause your program
  1436. to crash or loop.
  1437. Note that this option can also be passed to pcre2_match() and
  1438. pcre2_dfa_match(), to suppress UTF validity checking of the subject
  1439. string.
  1440. Note also that setting PCRE2_NO_UTF_CHECK at compile time does not dis-
  1441. able the error that is given if an escape sequence for an invalid Uni-
  1442. code code point is encountered in the pattern. In particular, the so-
  1443. called "surrogate" code points (0xd800 to 0xdfff) are invalid. If you
  1444. want to allow escape sequences such as \x{d800} you can set the
  1445. PCRE2_EXTRA_ALLOW_SURROGATE_ESCAPES extra option, as described in the
  1446. section entitled "Extra compile options" below. However, this is pos-
  1447. sible only in UTF-8 and UTF-32 modes, because these values are not rep-
  1448. resentable in UTF-16.
  1449. PCRE2_UCP
  1450. This option has two effects. Firstly, it change the way PCRE2 processes
  1451. \B, \b, \D, \d, \S, \s, \W, \w, and some of the POSIX character
  1452. classes. By default, only ASCII characters are recognized, but if
  1453. PCRE2_UCP is set, Unicode properties are used to classify characters.
  1454. There are some PCRE2_EXTRA options (see below) that add finer control
  1455. to this behaviour. More details are given in the section on generic
  1456. character types in the pcre2pattern page.
  1457. The second effect of PCRE2_UCP is to force the use of Unicode proper-
  1458. ties for upper/lower casing operations, even when PCRE2_UTF is not set.
  1459. This makes it possible to process strings in the 16-bit UCS-2 code.
  1460. This option is available only if PCRE2 has been compiled with Unicode
  1461. support (which is the default). The PCRE2_EXTRA_CASELESS_RESTRICT op-
  1462. tion (see below) restricts caseless matching such that ASCII characters
  1463. match only ASCII characters and non-ASCII characters match only non-
  1464. ASCII characters.
  1465. PCRE2_UNGREEDY
  1466. This option inverts the "greediness" of the quantifiers so that they
  1467. are not greedy by default, but become greedy if followed by "?". It is
  1468. not compatible with Perl. It can also be set by a (?U) option setting
  1469. within the pattern.
  1470. PCRE2_USE_OFFSET_LIMIT
  1471. This option must be set for pcre2_compile() if pcre2_set_offset_limit()
  1472. is going to be used to set a non-default offset limit in a match con-
  1473. text for matches that use this pattern. An error is generated if an
  1474. offset limit is set without this option. For more details, see the de-
  1475. scription of pcre2_set_offset_limit() in the section that describes
  1476. match contexts. See also the PCRE2_FIRSTLINE option above.
  1477. PCRE2_UTF
  1478. This option causes PCRE2 to regard both the pattern and the subject
  1479. strings that are subsequently processed as strings of UTF characters
  1480. instead of single-code-unit strings. It is available when PCRE2 is
  1481. built to include Unicode support (which is the default). If Unicode
  1482. support is not available, the use of this option provokes an error. De-
  1483. tails of how PCRE2_UTF changes the behaviour of PCRE2 are given in the
  1484. pcre2unicode page. In particular, note that it changes the way
  1485. PCRE2_CASELESS works.
  1486. Extra compile options
  1487. The option bits that can be set in a compile context by calling the
  1488. pcre2_set_compile_extra_options() function are as follows:
  1489. PCRE2_EXTRA_ALLOW_LOOKAROUND_BSK
  1490. Since release 10.38 PCRE2 has forbidden the use of \K within lookaround
  1491. assertions, following Perl's lead. This option is provided to re-enable
  1492. the previous behaviour (act in positive lookarounds, ignore in negative
  1493. ones) in case anybody is relying on it.
  1494. PCRE2_EXTRA_ALLOW_SURROGATE_ESCAPES
  1495. This option applies when compiling a pattern in UTF-8 or UTF-32 mode.
  1496. It is forbidden in UTF-16 mode, and ignored in non-UTF modes. Unicode
  1497. "surrogate" code points in the range 0xd800 to 0xdfff are used in pairs
  1498. in UTF-16 to encode code points with values in the range 0x10000 to
  1499. 0x10ffff. The surrogates cannot therefore be represented in UTF-16.
  1500. They can be represented in UTF-8 and UTF-32, but are defined as invalid
  1501. code points, and cause errors if encountered in a UTF-8 or UTF-32
  1502. string that is being checked for validity by PCRE2.
  1503. These values also cause errors if encountered in escape sequences such
  1504. as \x{d912} within a pattern. However, it seems that some applications,
  1505. when using PCRE2 to check for unwanted characters in UTF-8 strings, ex-
  1506. plicitly test for the surrogates using escape sequences. The
  1507. PCRE2_NO_UTF_CHECK option does not disable the error that occurs, be-
  1508. cause it applies only to the testing of input strings for UTF validity.
  1509. If the extra option PCRE2_EXTRA_ALLOW_SURROGATE_ESCAPES is set, surro-
  1510. gate code point values in UTF-8 and UTF-32 patterns no longer provoke
  1511. errors and are incorporated in the compiled pattern. However, they can
  1512. only match subject characters if the matching function is called with
  1513. PCRE2_NO_UTF_CHECK set.
  1514. PCRE2_EXTRA_ALT_BSUX
  1515. The original option PCRE2_ALT_BSUX causes PCRE2 to process \U, \u, and
  1516. \x in the way that ECMAscript (aka JavaScript) does. Additional func-
  1517. tionality was defined by ECMAscript 6; setting PCRE2_EXTRA_ALT_BSUX has
  1518. the effect of PCRE2_ALT_BSUX, but in addition it recognizes \u{hhh..}
  1519. as a hexadecimal character code, where hhh.. is any number of hexadeci-
  1520. mal digits.
  1521. PCRE2_EXTRA_ASCII_BSD
  1522. This option forces \d to match only ASCII digits, even when PCRE2_UCP
  1523. is set. It can be changed within a pattern by means of the (?aD) op-
  1524. tion setting.
  1525. PCRE2_EXTRA_ASCII_BSS
  1526. This option forces \s to match only ASCII space characters, even when
  1527. PCRE2_UCP is set. It can be changed within a pattern by means of the
  1528. (?aS) option setting.
  1529. PCRE2_EXTRA_ASCII_BSW
  1530. This option forces \w to match only ASCII word characters, even when
  1531. PCRE2_UCP is set. It can be changed within a pattern by means of the
  1532. (?aW) option setting.
  1533. PCRE2_EXTRA_ASCII_DIGIT
  1534. This option forces the POSIX character classes [:digit:] and [:xdigit:]
  1535. to match only ASCII digits, even when PCRE2_UCP is set. It can be
  1536. changed within a pattern by means of the (?aT) option setting.
  1537. PCRE2_EXTRA_ASCII_POSIX
  1538. This option forces all the POSIX character classes, including [:digit:]
  1539. and [:xdigit:], to match only ASCII characters, even when PCRE2_UCP is
  1540. set. It can be changed within a pattern by means of the (?aP) option
  1541. setting, but note that this also sets PCRE2_EXTRA_ASCII_DIGIT in order
  1542. to ensure that (?-aP) unsets all ASCII restrictions for POSIX classes.
  1543. PCRE2_EXTRA_BAD_ESCAPE_IS_LITERAL
  1544. This is a dangerous option. Use with care. By default, an unrecognized
  1545. escape such as \j or a malformed one such as \x{2z} causes a compile-
  1546. time error when detected by pcre2_compile(). Perl is somewhat inconsis-
  1547. tent in handling such items: for example, \j is treated as a literal
  1548. "j", and non-hexadecimal digits in \x{} are just ignored, though warn-
  1549. ings are given in both cases if Perl's warning switch is enabled. How-
  1550. ever, a malformed octal number after \o{ always causes an error in
  1551. Perl.
  1552. If the PCRE2_EXTRA_BAD_ESCAPE_IS_LITERAL extra option is passed to
  1553. pcre2_compile(), all unrecognized or malformed escape sequences are
  1554. treated as single-character escapes. For example, \j is a literal "j"
  1555. and \x{2z} is treated as the literal string "x{2z}". Setting this op-
  1556. tion means that typos in patterns may go undetected and have unexpected
  1557. results. Also note that a sequence such as [\N{] is interpreted as a
  1558. malformed attempt at [\N{...}] and so is treated as [N{] whereas [\N]
  1559. gives an error because an unqualified \N is a valid escape sequence but
  1560. is not supported in a character class. To reiterate: this is a danger-
  1561. ous option. Use with great care.
  1562. PCRE2_EXTRA_CASELESS_RESTRICT
  1563. When either PCRE2_UCP or PCRE2_UTF is set, caseless matching follows
  1564. Unicode rules, which allow for more than two cases per character. There
  1565. are two case-equivalent character sets that contain both ASCII and non-
  1566. ASCII characters. The ASCII letter S is case-equivalent to U+017f (long
  1567. S) and the ASCII letter K is case-equivalent to U+212a (Kelvin sign).
  1568. This option disables recognition of case-equivalences that cross the
  1569. ASCII/non-ASCII boundary. In a caseless match, both characters must ei-
  1570. ther be ASCII or non-ASCII. The option can be changed with a pattern by
  1571. the (?r) option setting.
  1572. PCRE2_EXTRA_ESCAPED_CR_IS_LF
  1573. There are some legacy applications where the escape sequence \r in a
  1574. pattern is expected to match a newline. If this option is set, \r in a
  1575. pattern is converted to \n so that it matches a LF (linefeed) instead
  1576. of a CR (carriage return) character. The option does not affect a lit-
  1577. eral CR in the pattern, nor does it affect CR specified as an explicit
  1578. code point such as \x{0D}.
  1579. PCRE2_EXTRA_MATCH_LINE
  1580. This option is provided for use by the -x option of pcre2grep. It
  1581. causes the pattern only to match complete lines. This is achieved by
  1582. automatically inserting the code for "^(?:" at the start of the com-
  1583. piled pattern and ")$" at the end. Thus, when PCRE2_MULTILINE is set,
  1584. the matched line may be in the middle of the subject string. This op-
  1585. tion can be used with PCRE2_LITERAL.
  1586. PCRE2_EXTRA_MATCH_WORD
  1587. This option is provided for use by the -w option of pcre2grep. It
  1588. causes the pattern only to match strings that have a word boundary at
  1589. the start and the end. This is achieved by automatically inserting the
  1590. code for "\b(?:" at the start of the compiled pattern and ")\b" at the
  1591. end. The option may be used with PCRE2_LITERAL. However, it is ignored
  1592. if PCRE2_EXTRA_MATCH_LINE is also set.
  1593. JUST-IN-TIME (JIT) COMPILATION
  1594. int pcre2_jit_compile(pcre2_code *code, uint32_t options);
  1595. int pcre2_jit_match(const pcre2_code *code, PCRE2_SPTR subject,
  1596. PCRE2_SIZE length, PCRE2_SIZE startoffset,
  1597. uint32_t options, pcre2_match_data *match_data,
  1598. pcre2_match_context *mcontext);
  1599. void pcre2_jit_free_unused_memory(pcre2_general_context *gcontext);
  1600. pcre2_jit_stack *pcre2_jit_stack_create(size_t startsize,
  1601. size_t maxsize, pcre2_general_context *gcontext);
  1602. void pcre2_jit_stack_assign(pcre2_match_context *mcontext,
  1603. pcre2_jit_callback callback_function, void *callback_data);
  1604. void pcre2_jit_stack_free(pcre2_jit_stack *jit_stack);
  1605. These functions provide support for JIT compilation, which, if the
  1606. just-in-time compiler is available, further processes a compiled pat-
  1607. tern into machine code that executes much faster than the pcre2_match()
  1608. interpretive matching function. Full details are given in the pcre2jit
  1609. documentation.
  1610. JIT compilation is a heavyweight optimization. It can take some time
  1611. for patterns to be analyzed, and for one-off matches and simple pat-
  1612. terns the benefit of faster execution might be offset by a much slower
  1613. compilation time. Most (but not all) patterns can be optimized by the
  1614. JIT compiler.
  1615. LOCALE SUPPORT
  1616. const uint8_t *pcre2_maketables(pcre2_general_context *gcontext);
  1617. void pcre2_maketables_free(pcre2_general_context *gcontext,
  1618. const uint8_t *tables);
  1619. PCRE2 handles caseless matching, and determines whether characters are
  1620. letters, digits, or whatever, by reference to a set of tables, indexed
  1621. by character code point. However, this applies only to characters whose
  1622. code points are less than 256. By default, higher-valued code points
  1623. never match escapes such as \w or \d.
  1624. When PCRE2 is built with Unicode support (the default), certain Unicode
  1625. character properties can be tested with \p and \P, or, alternatively,
  1626. the PCRE2_UCP option can be set when a pattern is compiled; this causes
  1627. \w and friends to use Unicode property support instead of the built-in
  1628. tables. PCRE2_UCP also causes upper/lower casing operations on charac-
  1629. ters with code points greater than 127 to use Unicode properties. These
  1630. effects apply even when PCRE2_UTF is not set. There are, however, some
  1631. PCRE2_EXTRA options (see above) that can be used to modify or suppress
  1632. them.
  1633. The use of locales with Unicode is discouraged. If you are handling
  1634. characters with code points greater than 127, you should either use
  1635. Unicode support, or use locales, but not try to mix the two.
  1636. PCRE2 contains a built-in set of character tables that are used by de-
  1637. fault. These are sufficient for many applications. Normally, the in-
  1638. ternal tables recognize only ASCII characters. However, when PCRE2 is
  1639. built, it is possible to cause the internal tables to be rebuilt in the
  1640. default "C" locale of the local system, which may cause them to be dif-
  1641. ferent.
  1642. The built-in tables can be overridden by tables supplied by the appli-
  1643. cation that calls PCRE2. These may be created in a different locale
  1644. from the default. As more and more applications change to using Uni-
  1645. code, the need for this locale support is expected to die away.
  1646. External tables are built by calling the pcre2_maketables() function,
  1647. in the relevant locale. The only argument to this function is a general
  1648. context, which can be used to pass a custom memory allocator. If the
  1649. argument is NULL, the system malloc() is used. The result can be passed
  1650. to pcre2_compile() as often as necessary, by creating a compile context
  1651. and calling pcre2_set_character_tables() to set the tables pointer
  1652. therein.
  1653. For example, to build and use tables that are appropriate for the
  1654. French locale (where accented characters with values greater than 127
  1655. are treated as letters), the following code could be used:
  1656. setlocale(LC_CTYPE, "fr_FR");
  1657. tables = pcre2_maketables(NULL);
  1658. ccontext = pcre2_compile_context_create(NULL);
  1659. pcre2_set_character_tables(ccontext, tables);
  1660. re = pcre2_compile(..., ccontext);
  1661. The locale name "fr_FR" is used on Linux and other Unix-like systems;
  1662. if you are using Windows, the name for the French locale is "french".
  1663. The pointer that is passed (via the compile context) to pcre2_compile()
  1664. is saved with the compiled pattern, and the same tables are used by the
  1665. matching functions. Thus, for any single pattern, compilation and
  1666. matching both happen in the same locale, but different patterns can be
  1667. processed in different locales.
  1668. It is the caller's responsibility to ensure that the memory containing
  1669. the tables remains available while they are still in use. When they are
  1670. no longer needed, you can discard them using pcre2_maketables_free(),
  1671. which should pass as its first parameter the same global context that
  1672. was used to create the tables.
  1673. Saving locale tables
  1674. The tables described above are just a sequence of binary bytes, which
  1675. makes them independent of hardware characteristics such as endianness
  1676. or whether the processor is 32-bit or 64-bit. A copy of the result of
  1677. pcre2_maketables() can therefore be saved in a file or elsewhere and
  1678. re-used later, even in a different program or on another computer. The
  1679. size of the tables (number of bytes) must be obtained by calling
  1680. pcre2_config() with the PCRE2_CONFIG_TABLES_LENGTH option because
  1681. pcre2_maketables() does not return this value. Note that the
  1682. pcre2_dftables program, which is part of the PCRE2 build system, can be
  1683. used stand-alone to create a file that contains a set of binary tables.
  1684. See the pcre2build documentation for details.
  1685. INFORMATION ABOUT A COMPILED PATTERN
  1686. int pcre2_pattern_info(const pcre2 *code, uint32_t what, void *where);
  1687. The pcre2_pattern_info() function returns general information about a
  1688. compiled pattern. For information about callouts, see the next section.
  1689. The first argument for pcre2_pattern_info() is a pointer to the com-
  1690. piled pattern. The second argument specifies which piece of information
  1691. is required, and the third argument is a pointer to a variable to re-
  1692. ceive the data. If the third argument is NULL, the first argument is
  1693. ignored, and the function returns the size in bytes of the variable
  1694. that is required for the information requested. Otherwise, the yield of
  1695. the function is zero for success, or one of the following negative num-
  1696. bers:
  1697. PCRE2_ERROR_NULL the argument code was NULL
  1698. PCRE2_ERROR_BADMAGIC the "magic number" was not found
  1699. PCRE2_ERROR_BADOPTION the value of what was invalid
  1700. PCRE2_ERROR_UNSET the requested field is not set
  1701. The "magic number" is placed at the start of each compiled pattern as a
  1702. simple check against passing an arbitrary memory pointer. Here is a
  1703. typical call of pcre2_pattern_info(), to obtain the length of the com-
  1704. piled pattern:
  1705. int rc;
  1706. size_t length;
  1707. rc = pcre2_pattern_info(
  1708. re, /* result of pcre2_compile() */
  1709. PCRE2_INFO_SIZE, /* what is required */
  1710. &length); /* where to put the data */
  1711. The possible values for the second argument are defined in pcre2.h, and
  1712. are as follows:
  1713. PCRE2_INFO_ALLOPTIONS
  1714. PCRE2_INFO_ARGOPTIONS
  1715. PCRE2_INFO_EXTRAOPTIONS
  1716. Return copies of the pattern's options. The third argument should point
  1717. to a uint32_t variable. PCRE2_INFO_ARGOPTIONS returns exactly the op-
  1718. tions that were passed to pcre2_compile(), whereas PCRE2_INFO_ALLOP-
  1719. TIONS returns the compile options as modified by any top-level (*XXX)
  1720. option settings such as (*UTF) at the start of the pattern itself.
  1721. PCRE2_INFO_EXTRAOPTIONS returns the extra options that were set in the
  1722. compile context by calling the pcre2_set_compile_extra_options() func-
  1723. tion.
  1724. For example, if the pattern /(*UTF)abc/ is compiled with the PCRE2_EX-
  1725. TENDED option, the result for PCRE2_INFO_ALLOPTIONS is PCRE2_EXTENDED
  1726. and PCRE2_UTF. Option settings such as (?i) that can change within a
  1727. pattern do not affect the result of PCRE2_INFO_ALLOPTIONS, even if they
  1728. appear right at the start of the pattern. (This was different in some
  1729. earlier releases.)
  1730. A pattern compiled without PCRE2_ANCHORED is automatically anchored by
  1731. PCRE2 if the first significant item in every top-level branch is one of
  1732. the following:
  1733. ^ unless PCRE2_MULTILINE is set
  1734. \A always
  1735. \G always
  1736. .* sometimes - see below
  1737. When .* is the first significant item, anchoring is possible only when
  1738. all the following are true:
  1739. .* is not in an atomic group
  1740. .* is not in a capture group that is the subject
  1741. of a backreference
  1742. PCRE2_DOTALL is in force for .*
  1743. Neither (*PRUNE) nor (*SKIP) appears in the pattern
  1744. PCRE2_NO_DOTSTAR_ANCHOR is not set
  1745. For patterns that are auto-anchored, the PCRE2_ANCHORED bit is set in
  1746. the options returned for PCRE2_INFO_ALLOPTIONS.
  1747. PCRE2_INFO_BACKREFMAX
  1748. Return the number of the highest backreference in the pattern. The
  1749. third argument should point to a uint32_t variable. Named capture
  1750. groups acquire numbers as well as names, and these count towards the
  1751. highest backreference. Backreferences such as \4 or \g{12} match the
  1752. captured characters of the given group, but in addition, the check that
  1753. a capture group is set in a conditional group such as (?(3)a|b) is also
  1754. a backreference. Zero is returned if there are no backreferences.
  1755. PCRE2_INFO_BSR
  1756. The output is a uint32_t integer whose value indicates what character
  1757. sequences the \R escape sequence matches. A value of PCRE2_BSR_UNICODE
  1758. means that \R matches any Unicode line ending sequence; a value of
  1759. PCRE2_BSR_ANYCRLF means that \R matches only CR, LF, or CRLF.
  1760. PCRE2_INFO_CAPTURECOUNT
  1761. Return the highest capture group number in the pattern. In patterns
  1762. where (?| is not used, this is also the total number of capture groups.
  1763. The third argument should point to a uint32_t variable.
  1764. PCRE2_INFO_DEPTHLIMIT
  1765. If the pattern set a backtracking depth limit by including an item of
  1766. the form (*LIMIT_DEPTH=nnnn) at the start, the value is returned. The
  1767. third argument should point to a uint32_t integer. If no such value has
  1768. been set, the call to pcre2_pattern_info() returns the error PCRE2_ER-
  1769. ROR_UNSET. Note that this limit will only be used during matching if it
  1770. is less than the limit set or defaulted by the caller of the match
  1771. function.
  1772. PCRE2_INFO_FIRSTBITMAP
  1773. In the absence of a single first code unit for a non-anchored pattern,
  1774. pcre2_compile() may construct a 256-bit table that defines a fixed set
  1775. of values for the first code unit in any match. For example, a pattern
  1776. that starts with [abc] results in a table with three bits set. When
  1777. code unit values greater than 255 are supported, the flag bit for 255
  1778. means "any code unit of value 255 or above". If such a table was con-
  1779. structed, a pointer to it is returned. Otherwise NULL is returned. The
  1780. third argument should point to a const uint8_t * variable.
  1781. PCRE2_INFO_FIRSTCODETYPE
  1782. Return information about the first code unit of any matched string, for
  1783. a non-anchored pattern. The third argument should point to a uint32_t
  1784. variable. If there is a fixed first value, for example, the letter "c"
  1785. from a pattern such as (cat|cow|coyote), 1 is returned, and the value
  1786. can be retrieved using PCRE2_INFO_FIRSTCODEUNIT. If there is no fixed
  1787. first value, but it is known that a match can occur only at the start
  1788. of the subject or following a newline in the subject, 2 is returned.
  1789. Otherwise, and for anchored patterns, 0 is returned.
  1790. PCRE2_INFO_FIRSTCODEUNIT
  1791. Return the value of the first code unit of any matched string for a
  1792. pattern where PCRE2_INFO_FIRSTCODETYPE returns 1; otherwise return 0.
  1793. The third argument should point to a uint32_t variable. In the 8-bit
  1794. library, the value is always less than 256. In the 16-bit library the
  1795. value can be up to 0xffff. In the 32-bit library in UTF-32 mode the
  1796. value can be up to 0x10ffff, and up to 0xffffffff when not using UTF-32
  1797. mode.
  1798. PCRE2_INFO_FRAMESIZE
  1799. Return the size (in bytes) of the data frames that are used to remember
  1800. backtracking positions when the pattern is processed by pcre2_match()
  1801. without the use of JIT. The third argument should point to a size_t
  1802. variable. The frame size depends on the number of capturing parentheses
  1803. in the pattern. Each additional capture group adds two PCRE2_SIZE vari-
  1804. ables.
  1805. PCRE2_INFO_HASBACKSLASHC
  1806. Return 1 if the pattern contains any instances of \C, otherwise 0. The
  1807. third argument should point to a uint32_t variable.
  1808. PCRE2_INFO_HASCRORLF
  1809. Return 1 if the pattern contains any explicit matches for CR or LF
  1810. characters, otherwise 0. The third argument should point to a uint32_t
  1811. variable. An explicit match is either a literal CR or LF character, or
  1812. \r or \n or one of the equivalent hexadecimal or octal escape se-
  1813. quences.
  1814. PCRE2_INFO_HEAPLIMIT
  1815. If the pattern set a heap memory limit by including an item of the form
  1816. (*LIMIT_HEAP=nnnn) at the start, the value is returned. The third argu-
  1817. ment should point to a uint32_t integer. If no such value has been set,
  1818. the call to pcre2_pattern_info() returns the error PCRE2_ERROR_UNSET.
  1819. Note that this limit will only be used during matching if it is less
  1820. than the limit set or defaulted by the caller of the match function.
  1821. PCRE2_INFO_JCHANGED
  1822. Return 1 if the (?J) or (?-J) option setting is used in the pattern,
  1823. otherwise 0. The third argument should point to a uint32_t variable.
  1824. (?J) and (?-J) set and unset the local PCRE2_DUPNAMES option, respec-
  1825. tively.
  1826. PCRE2_INFO_JITSIZE
  1827. If the compiled pattern was successfully processed by pcre2_jit_com-
  1828. pile(), return the size of the JIT compiled code, otherwise return
  1829. zero. The third argument should point to a size_t variable.
  1830. PCRE2_INFO_LASTCODETYPE
  1831. Returns 1 if there is a rightmost literal code unit that must exist in
  1832. any matched string, other than at its start. The third argument should
  1833. point to a uint32_t variable. If there is no such value, 0 is returned.
  1834. When 1 is returned, the code unit value itself can be retrieved using
  1835. PCRE2_INFO_LASTCODEUNIT. For anchored patterns, a last literal value is
  1836. recorded only if it follows something of variable length. For example,
  1837. for the pattern /^a\d+z\d+/ the returned value is 1 (with "z" returned
  1838. from PCRE2_INFO_LASTCODEUNIT), but for /^a\dz\d/ the returned value is
  1839. 0.
  1840. PCRE2_INFO_LASTCODEUNIT
  1841. Return the value of the rightmost literal code unit that must exist in
  1842. any matched string, other than at its start, for a pattern where
  1843. PCRE2_INFO_LASTCODETYPE returns 1. Otherwise, return 0. The third argu-
  1844. ment should point to a uint32_t variable.
  1845. PCRE2_INFO_MATCHEMPTY
  1846. Return 1 if the pattern might match an empty string, otherwise 0. The
  1847. third argument should point to a uint32_t variable. When a pattern con-
  1848. tains recursive subroutine calls it is not always possible to determine
  1849. whether or not it can match an empty string. PCRE2 takes a cautious ap-
  1850. proach and returns 1 in such cases.
  1851. PCRE2_INFO_MATCHLIMIT
  1852. If the pattern set a match limit by including an item of the form
  1853. (*LIMIT_MATCH=nnnn) at the start, the value is returned. The third ar-
  1854. gument should point to a uint32_t integer. If no such value has been
  1855. set, the call to pcre2_pattern_info() returns the error PCRE2_ERROR_UN-
  1856. SET. Note that this limit will only be used during matching if it is
  1857. less than the limit set or defaulted by the caller of the match func-
  1858. tion.
  1859. PCRE2_INFO_MAXLOOKBEHIND
  1860. A lookbehind assertion moves back a certain number of characters (not
  1861. code units) when it starts to process each of its branches. This re-
  1862. quest returns the largest of these backward moves. The third argument
  1863. should point to a uint32_t integer. The simple assertions \b and \B re-
  1864. quire a one-character lookbehind and cause PCRE2_INFO_MAXLOOKBEHIND to
  1865. return 1 in the absence of anything longer. \A also registers a one-
  1866. character lookbehind, though it does not actually inspect the previous
  1867. character.
  1868. Note that this information is useful for multi-segment matching only if
  1869. the pattern contains no nested lookbehinds. For example, the pattern
  1870. (?<=a(?<=ba)c) returns a maximum lookbehind of 2, but when it is
  1871. processed, the first lookbehind moves back by two characters, matches
  1872. one character, then the nested lookbehind also moves back by two char-
  1873. acters. This puts the matching point three characters earlier than it
  1874. was at the start. PCRE2_INFO_MAXLOOKBEHIND is really only useful as a
  1875. debugging tool. See the pcre2partial documentation for a discussion of
  1876. multi-segment matching.
  1877. PCRE2_INFO_MINLENGTH
  1878. If a minimum length for matching subject strings was computed, its
  1879. value is returned. Otherwise the returned value is 0. This value is not
  1880. computed when PCRE2_NO_START_OPTIMIZE is set. The value is a number of
  1881. characters, which in UTF mode may be different from the number of code
  1882. units. The third argument should point to a uint32_t variable. The
  1883. value is a lower bound to the length of any matching string. There may
  1884. not be any strings of that length that do actually match, but every
  1885. string that does match is at least that long.
  1886. PCRE2_INFO_NAMECOUNT
  1887. PCRE2_INFO_NAMEENTRYSIZE
  1888. PCRE2_INFO_NAMETABLE
  1889. PCRE2 supports the use of named as well as numbered capturing parenthe-
  1890. ses. The names are just an additional way of identifying the parenthe-
  1891. ses, which still acquire numbers. Several convenience functions such as
  1892. pcre2_substring_get_byname() are provided for extracting captured sub-
  1893. strings by name. It is also possible to extract the data directly, by
  1894. first converting the name to a number in order to access the correct
  1895. pointers in the output vector (described with pcre2_match() below). To
  1896. do the conversion, you need to use the name-to-number map, which is de-
  1897. scribed by these three values.
  1898. The map consists of a number of fixed-size entries. PCRE2_INFO_NAME-
  1899. COUNT gives the number of entries, and PCRE2_INFO_NAMEENTRYSIZE gives
  1900. the size of each entry in code units; both of these return a uint32_t
  1901. value. The entry size depends on the length of the longest name.
  1902. PCRE2_INFO_NAMETABLE returns a pointer to the first entry of the table.
  1903. This is a PCRE2_SPTR pointer to a block of code units. In the 8-bit li-
  1904. brary, the first two bytes of each entry are the number of the captur-
  1905. ing parenthesis, most significant byte first. In the 16-bit library,
  1906. the pointer points to 16-bit code units, the first of which contains
  1907. the parenthesis number. In the 32-bit library, the pointer points to
  1908. 32-bit code units, the first of which contains the parenthesis number.
  1909. The rest of the entry is the corresponding name, zero terminated.
  1910. The names are in alphabetical order. If (?| is used to create multiple
  1911. capture groups with the same number, as described in the section on du-
  1912. plicate group numbers in the pcre2pattern page, the groups may be given
  1913. the same name, but there is only one entry in the table. Different
  1914. names for groups of the same number are not permitted.
  1915. Duplicate names for capture groups with different numbers are permit-
  1916. ted, but only if PCRE2_DUPNAMES is set. They appear in the table in the
  1917. order in which they were found in the pattern. In the absence of (?|
  1918. this is the order of increasing number; when (?| is used this is not
  1919. necessarily the case because later capture groups may have lower num-
  1920. bers.
  1921. As a simple example of the name/number table, consider the following
  1922. pattern after compilation by the 8-bit library (assume PCRE2_EXTENDED
  1923. is set, so white space - including newlines - is ignored):
  1924. (?<date> (?<year>(\d\d)?\d\d) -
  1925. (?<month>\d\d) - (?<day>\d\d) )
  1926. There are four named capture groups, so the table has four entries, and
  1927. each entry in the table is eight bytes long. The table is as follows,
  1928. with non-printing bytes shows in hexadecimal, and undefined bytes shown
  1929. as ??:
  1930. 00 01 d a t e 00 ??
  1931. 00 05 d a y 00 ?? ??
  1932. 00 04 m o n t h 00
  1933. 00 02 y e a r 00 ??
  1934. When writing code to extract data from named capture groups using the
  1935. name-to-number map, remember that the length of the entries is likely
  1936. to be different for each compiled pattern.
  1937. PCRE2_INFO_NEWLINE
  1938. The output is one of the following uint32_t values:
  1939. PCRE2_NEWLINE_CR Carriage return (CR)
  1940. PCRE2_NEWLINE_LF Linefeed (LF)
  1941. PCRE2_NEWLINE_CRLF Carriage return, linefeed (CRLF)
  1942. PCRE2_NEWLINE_ANY Any Unicode line ending
  1943. PCRE2_NEWLINE_ANYCRLF Any of CR, LF, or CRLF
  1944. PCRE2_NEWLINE_NUL The NUL character (binary zero)
  1945. This identifies the character sequence that will be recognized as mean-
  1946. ing "newline" while matching.
  1947. PCRE2_INFO_SIZE
  1948. Return the size of the compiled pattern in bytes (for all three li-
  1949. braries). The third argument should point to a size_t variable. This
  1950. value includes the size of the general data block that precedes the
  1951. code units of the compiled pattern itself. The value that is used when
  1952. pcre2_compile() is getting memory in which to place the compiled pat-
  1953. tern may be slightly larger than the value returned by this option, be-
  1954. cause there are cases where the code that calculates the size has to
  1955. over-estimate. Processing a pattern with the JIT compiler does not al-
  1956. ter the value returned by this option.
  1957. INFORMATION ABOUT A PATTERN'S CALLOUTS
  1958. int pcre2_callout_enumerate(const pcre2_code *code,
  1959. int (*callback)(pcre2_callout_enumerate_block *, void *),
  1960. void *user_data);
  1961. A script language that supports the use of string arguments in callouts
  1962. might like to scan all the callouts in a pattern before running the
  1963. match. This can be done by calling pcre2_callout_enumerate(). The first
  1964. argument is a pointer to a compiled pattern, the second points to a
  1965. callback function, and the third is arbitrary user data. The callback
  1966. function is called for every callout in the pattern in the order in
  1967. which they appear. Its first argument is a pointer to a callout enumer-
  1968. ation block, and its second argument is the user_data value that was
  1969. passed to pcre2_callout_enumerate(). The contents of the callout enu-
  1970. meration block are described in the pcre2callout documentation, which
  1971. also gives further details about callouts.
  1972. SERIALIZATION AND PRECOMPILING
  1973. It is possible to save compiled patterns on disc or elsewhere, and re-
  1974. load them later, subject to a number of restrictions. The host on which
  1975. the patterns are reloaded must be running the same version of PCRE2,
  1976. with the same code unit width, and must also have the same endianness,
  1977. pointer width, and PCRE2_SIZE type. Before compiled patterns can be
  1978. saved, they must be converted to a "serialized" form, which in the case
  1979. of PCRE2 is really just a bytecode dump. The functions whose names be-
  1980. gin with pcre2_serialize_ are used for converting to and from the seri-
  1981. alized form. They are described in the pcre2serialize documentation.
  1982. Note that PCRE2 serialization does not convert compiled patterns to an
  1983. abstract format like Java or .NET serialization.
  1984. THE MATCH DATA BLOCK
  1985. pcre2_match_data *pcre2_match_data_create(uint32_t ovecsize,
  1986. pcre2_general_context *gcontext);
  1987. pcre2_match_data *pcre2_match_data_create_from_pattern(
  1988. const pcre2_code *code, pcre2_general_context *gcontext);
  1989. void pcre2_match_data_free(pcre2_match_data *match_data);
  1990. Information about a successful or unsuccessful match is placed in a
  1991. match data block, which is an opaque structure that is accessed by
  1992. function calls. In particular, the match data block contains a vector
  1993. of offsets into the subject string that define the matched parts of the
  1994. subject. This is known as the ovector.
  1995. Before calling pcre2_match(), pcre2_dfa_match(), or pcre2_jit_match()
  1996. you must create a match data block by calling one of the creation func-
  1997. tions above. For pcre2_match_data_create(), the first argument is the
  1998. number of pairs of offsets in the ovector.
  1999. When using pcre2_match(), one pair of offsets is required to identify
  2000. the string that matched the whole pattern, with an additional pair for
  2001. each captured substring. For example, a value of 4 creates enough space
  2002. to record the matched portion of the subject plus three captured sub-
  2003. strings.
  2004. When using pcre2_dfa_match() there may be multiple matched substrings
  2005. of different lengths at the same point in the subject. The ovector
  2006. should be made large enough to hold as many as are expected.
  2007. A minimum of at least 1 pair is imposed by pcre2_match_data_create(),
  2008. so it is always possible to return the overall matched string in the
  2009. case of pcre2_match() or the longest match in the case of
  2010. pcre2_dfa_match(). The maximum number of pairs is 65535; if the first
  2011. argument of pcre2_match_data_create() is greater than this, 65535 is
  2012. used.
  2013. The second argument of pcre2_match_data_create() is a pointer to a gen-
  2014. eral context, which can specify custom memory management for obtaining
  2015. the memory for the match data block. If you are not using custom memory
  2016. management, pass NULL, which causes malloc() to be used.
  2017. For pcre2_match_data_create_from_pattern(), the first argument is a
  2018. pointer to a compiled pattern. The ovector is created to be exactly the
  2019. right size to hold all the substrings a pattern might capture when
  2020. matched using pcre2_match(). You should not use this call when matching
  2021. with pcre2_dfa_match(). The second argument is again a pointer to a
  2022. general context, but in this case if NULL is passed, the memory is ob-
  2023. tained using the same allocator that was used for the compiled pattern
  2024. (custom or default).
  2025. A match data block can be used many times, with the same or different
  2026. compiled patterns. You can extract information from a match data block
  2027. after a match operation has finished, using functions that are de-
  2028. scribed in the sections on matched strings and other match data below.
  2029. When a call of pcre2_match() fails, valid data is available in the
  2030. match block only when the error is PCRE2_ERROR_NOMATCH, PCRE2_ER-
  2031. ROR_PARTIAL, or one of the error codes for an invalid UTF string. Ex-
  2032. actly what is available depends on the error, and is detailed below.
  2033. When one of the matching functions is called, pointers to the compiled
  2034. pattern and the subject string are set in the match data block so that
  2035. they can be referenced by the extraction functions after a successful
  2036. match. After running a match, you must not free a compiled pattern or a
  2037. subject string until after all operations on the match data block (for
  2038. that match) have taken place, unless, in the case of the subject
  2039. string, you have used the PCRE2_COPY_MATCHED_SUBJECT option, which is
  2040. described in the section entitled "Option bits for pcre2_match()" be-
  2041. low.
  2042. When a match data block itself is no longer needed, it should be freed
  2043. by calling pcre2_match_data_free(). If this function is called with a
  2044. NULL argument, it returns immediately, without doing anything.
  2045. MEMORY USE FOR MATCH DATA BLOCKS
  2046. PCRE2_SIZE pcre2_get_match_data_size(pcre2_match_data *match_data);
  2047. PCRE2_SIZE pcre2_get_match_data_heapframes_size(
  2048. pcre2_match_data *match_data);
  2049. The size of a match data block depends on the size of the ovector that
  2050. it contains. The function pcre2_get_match_data_size() returns the size,
  2051. in bytes, of the block that is its argument.
  2052. When pcre2_match() runs interpretively (that is, without using JIT), it
  2053. makes use of a vector of data frames for remembering backtracking posi-
  2054. tions. The size of each individual frame depends on the number of cap-
  2055. turing parentheses in the pattern and can be obtained by calling
  2056. pcre2_pattern_info() with the PCRE2_INFO_FRAMESIZE option (see the sec-
  2057. tion entitled "Information about a compiled pattern" above).
  2058. Heap memory is used for the frames vector; if the initial memory block
  2059. turns out to be too small during matching, it is automatically ex-
  2060. panded. When pcre2_match() returns, the memory is not freed, but re-
  2061. mains attached to the match data block, for use by any subsequent
  2062. matches that use the same block. It is automatically freed when the
  2063. match data block itself is freed.
  2064. You can find the current size of the frames vector that a match data
  2065. block owns by calling pcre2_get_match_data_heapframes_size(). For a
  2066. newly created match data block the size will be zero. Some types of
  2067. match may require a lot of frames and thus a large vector; applications
  2068. that run in environments where memory is constrained can check this and
  2069. free the match data block if the heap frames vector has become too big.
  2070. MATCHING A PATTERN: THE TRADITIONAL FUNCTION
  2071. int pcre2_match(const pcre2_code *code, PCRE2_SPTR subject,
  2072. PCRE2_SIZE length, PCRE2_SIZE startoffset,
  2073. uint32_t options, pcre2_match_data *match_data,
  2074. pcre2_match_context *mcontext);
  2075. The function pcre2_match() is called to match a subject string against
  2076. a compiled pattern, which is passed in the code argument. You can call
  2077. pcre2_match() with the same code argument as many times as you like, in
  2078. order to find multiple matches in the subject string or to match dif-
  2079. ferent subject strings with the same pattern.
  2080. This function is the main matching facility of the library, and it op-
  2081. erates in a Perl-like manner. For specialist use there is also an al-
  2082. ternative matching function, which is described below in the section
  2083. about the pcre2_dfa_match() function.
  2084. Here is an example of a simple call to pcre2_match():
  2085. pcre2_match_data *md = pcre2_match_data_create(4, NULL);
  2086. int rc = pcre2_match(
  2087. re, /* result of pcre2_compile() */
  2088. "some string", /* the subject string */
  2089. 11, /* the length of the subject string */
  2090. 0, /* start at offset 0 in the subject */
  2091. 0, /* default options */
  2092. md, /* the match data block */
  2093. NULL); /* a match context; NULL means use defaults */
  2094. If the subject string is zero-terminated, the length can be given as
  2095. PCRE2_ZERO_TERMINATED. A match context must be provided if certain less
  2096. common matching parameters are to be changed. For details, see the sec-
  2097. tion on the match context above.
  2098. The string to be matched by pcre2_match()
  2099. The subject string is passed to pcre2_match() as a pointer in subject,
  2100. a length in length, and a starting offset in startoffset. The length
  2101. and offset are in code units, not characters. That is, they are in
  2102. bytes for the 8-bit library, 16-bit code units for the 16-bit library,
  2103. and 32-bit code units for the 32-bit library, whether or not UTF pro-
  2104. cessing is enabled. As a special case, if subject is NULL and length is
  2105. zero, the subject is assumed to be an empty string. If length is non-
  2106. zero, an error occurs if subject is NULL.
  2107. If startoffset is greater than the length of the subject, pcre2_match()
  2108. returns PCRE2_ERROR_BADOFFSET. When the starting offset is zero, the
  2109. search for a match starts at the beginning of the subject, and this is
  2110. by far the most common case. In UTF-8 or UTF-16 mode, the starting off-
  2111. set must point to the start of a character, or to the end of the sub-
  2112. ject (in UTF-32 mode, one code unit equals one character, so all off-
  2113. sets are valid). Like the pattern string, the subject may contain bi-
  2114. nary zeros.
  2115. A non-zero starting offset is useful when searching for another match
  2116. in the same subject by calling pcre2_match() again after a previous
  2117. success. Setting startoffset differs from passing over a shortened
  2118. string and setting PCRE2_NOTBOL in the case of a pattern that begins
  2119. with any kind of lookbehind. For example, consider the pattern
  2120. \Biss\B
  2121. which finds occurrences of "iss" in the middle of words. (\B matches
  2122. only if the current position in the subject is not a word boundary.)
  2123. When applied to the string "Mississippi" the first call to
  2124. pcre2_match() finds the first occurrence. If pcre2_match() is called
  2125. again with just the remainder of the subject, namely "issippi", it does
  2126. not match, because \B is always false at the start of the subject,
  2127. which is deemed to be a word boundary. However, if pcre2_match() is
  2128. passed the entire string again, but with startoffset set to 4, it finds
  2129. the second occurrence of "iss" because it is able to look behind the
  2130. starting point to discover that it is preceded by a letter.
  2131. Finding all the matches in a subject is tricky when the pattern can
  2132. match an empty string. It is possible to emulate Perl's /g behaviour by
  2133. first trying the match again at the same offset, with the
  2134. PCRE2_NOTEMPTY_ATSTART and PCRE2_ANCHORED options, and then if that
  2135. fails, advancing the starting offset and trying an ordinary match
  2136. again. There is some code that demonstrates how to do this in the
  2137. pcre2demo sample program. In the most general case, you have to check
  2138. to see if the newline convention recognizes CRLF as a newline, and if
  2139. so, and the current character is CR followed by LF, advance the start-
  2140. ing offset by two characters instead of one.
  2141. If a non-zero starting offset is passed when the pattern is anchored, a
  2142. single attempt to match at the given offset is made. This can only suc-
  2143. ceed if the pattern does not require the match to be at the start of
  2144. the subject. In other words, the anchoring must be the result of set-
  2145. ting the PCRE2_ANCHORED option or the use of .* with PCRE2_DOTALL, not
  2146. by starting the pattern with ^ or \A.
  2147. Option bits for pcre2_match()
  2148. The unused bits of the options argument for pcre2_match() must be zero.
  2149. The only bits that may be set are PCRE2_ANCHORED,
  2150. PCRE2_COPY_MATCHED_SUBJECT, PCRE2_DISABLE_RECURSELOOP_CHECK, PCRE2_EN-
  2151. DANCHORED, PCRE2_NOTBOL, PCRE2_NOTEOL, PCRE2_NOTEMPTY,
  2152. PCRE2_NOTEMPTY_ATSTART, PCRE2_NO_JIT, PCRE2_NO_UTF_CHECK, PCRE2_PAR-
  2153. TIAL_HARD, and PCRE2_PARTIAL_SOFT. Their action is described below.
  2154. Setting PCRE2_ANCHORED or PCRE2_ENDANCHORED at match time is not sup-
  2155. ported by the just-in-time (JIT) compiler. If it is set, JIT matching
  2156. is disabled and the interpretive code in pcre2_match() is run.
  2157. PCRE2_DISABLE_RECURSELOOP_CHECK is ignored by JIT, but apart from
  2158. PCRE2_NO_JIT (obviously), the remaining options are supported for JIT
  2159. matching.
  2160. PCRE2_ANCHORED
  2161. The PCRE2_ANCHORED option limits pcre2_match() to matching at the first
  2162. matching position. If a pattern was compiled with PCRE2_ANCHORED, or
  2163. turned out to be anchored by virtue of its contents, it cannot be made
  2164. unachored at matching time. Note that setting the option at match time
  2165. disables JIT matching.
  2166. PCRE2_COPY_MATCHED_SUBJECT
  2167. By default, a pointer to the subject is remembered in the match data
  2168. block so that, after a successful match, it can be referenced by the
  2169. substring extraction functions. This means that the subject's memory
  2170. must not be freed until all such operations are complete. For some ap-
  2171. plications where the lifetime of the subject string is not guaranteed,
  2172. it may be necessary to make a copy of the subject string, but it is
  2173. wasteful to do this unless the match is successful. After a successful
  2174. match, if PCRE2_COPY_MATCHED_SUBJECT is set, the subject is copied and
  2175. the new pointer is remembered in the match data block instead of the
  2176. original subject pointer. The memory allocator that was used for the
  2177. match block itself is used. The copy is automatically freed when
  2178. pcre2_match_data_free() is called to free the match data block. It is
  2179. also automatically freed if the match data block is re-used for another
  2180. match operation.
  2181. PCRE2_DISABLE_RECURSELOOP_CHECK
  2182. This option is relevant only to pcre2_match() for interpretive match-
  2183. ing. It is ignored when JIT is used, and is forbidden for
  2184. pcre2_dfa_match().
  2185. The use of recursion in patterns can lead to infinite loops. In the in-
  2186. terpretive matcher these would be eventually caught by the match or
  2187. heap limits, but this could take a long time and/or use a lot of memory
  2188. if the limits are large. There is therefore a check at the start of
  2189. each recursion. If the same group is still active from a previous
  2190. call, and the current subject pointer is the same as it was at the
  2191. start of that group, and the furthest inspected character of the sub-
  2192. ject has not changed, an error is generated.
  2193. There are rare cases of matches that would complete, but nevertheless
  2194. trigger this error. This option disables the check. It is provided
  2195. mainly for testing when comparing JIT and interpretive behaviour.
  2196. PCRE2_ENDANCHORED
  2197. If the PCRE2_ENDANCHORED option is set, any string that pcre2_match()
  2198. matches must be right at the end of the subject string. Note that set-
  2199. ting the option at match time disables JIT matching.
  2200. PCRE2_NOTBOL
  2201. This option specifies that first character of the subject string is not
  2202. the beginning of a line, so the circumflex metacharacter should not
  2203. match before it. Setting this without having set PCRE2_MULTILINE at
  2204. compile time causes circumflex never to match. This option affects only
  2205. the behaviour of the circumflex metacharacter. It does not affect \A.
  2206. PCRE2_NOTEOL
  2207. This option specifies that the end of the subject string is not the end
  2208. of a line, so the dollar metacharacter should not match it nor (except
  2209. in multiline mode) a newline immediately before it. Setting this with-
  2210. out having set PCRE2_MULTILINE at compile time causes dollar never to
  2211. match. This option affects only the behaviour of the dollar metacharac-
  2212. ter. It does not affect \Z or \z.
  2213. PCRE2_NOTEMPTY
  2214. An empty string is not considered to be a valid match if this option is
  2215. set. If there are alternatives in the pattern, they are tried. If all
  2216. the alternatives match the empty string, the entire match fails. For
  2217. example, if the pattern
  2218. a?b?
  2219. is applied to a string not beginning with "a" or "b", it matches an
  2220. empty string at the start of the subject. With PCRE2_NOTEMPTY set, this
  2221. match is not valid, so pcre2_match() searches further into the string
  2222. for occurrences of "a" or "b".
  2223. PCRE2_NOTEMPTY_ATSTART
  2224. This is like PCRE2_NOTEMPTY, except that it locks out an empty string
  2225. match only at the first matching position, that is, at the start of the
  2226. subject plus the starting offset. An empty string match later in the
  2227. subject is permitted. If the pattern is anchored, such a match can oc-
  2228. cur only if the pattern contains \K.
  2229. PCRE2_NO_JIT
  2230. By default, if a pattern has been successfully processed by
  2231. pcre2_jit_compile(), JIT is automatically used when pcre2_match() is
  2232. called with options that JIT supports. Setting PCRE2_NO_JIT disables
  2233. the use of JIT; it forces matching to be done by the interpreter.
  2234. PCRE2_NO_UTF_CHECK
  2235. When PCRE2_UTF is set at compile time, the validity of the subject as a
  2236. UTF string is checked unless PCRE2_NO_UTF_CHECK is passed to
  2237. pcre2_match() or PCRE2_MATCH_INVALID_UTF was passed to pcre2_compile().
  2238. The latter special case is discussed in detail in the pcre2unicode doc-
  2239. umentation.
  2240. In the default case, if a non-zero starting offset is given, the check
  2241. is applied only to that part of the subject that could be inspected
  2242. during matching, and there is a check that the starting offset points
  2243. to the first code unit of a character or to the end of the subject. If
  2244. there are no lookbehind assertions in the pattern, the check starts at
  2245. the starting offset. Otherwise, it starts at the length of the longest
  2246. lookbehind before the starting offset, or at the start of the subject
  2247. if there are not that many characters before the starting offset. Note
  2248. that the sequences \b and \B are one-character lookbehinds.
  2249. The check is carried out before any other processing takes place, and a
  2250. negative error code is returned if the check fails. There are several
  2251. UTF error codes for each code unit width, corresponding to different
  2252. problems with the code unit sequence. There are discussions about the
  2253. validity of UTF-8 strings, UTF-16 strings, and UTF-32 strings in the
  2254. pcre2unicode documentation.
  2255. If you know that your subject is valid, and you want to skip this check
  2256. for performance reasons, you can set the PCRE2_NO_UTF_CHECK option when
  2257. calling pcre2_match(). You might want to do this for the second and
  2258. subsequent calls to pcre2_match() if you are making repeated calls to
  2259. find multiple matches in the same subject string.
  2260. Warning: Unless PCRE2_MATCH_INVALID_UTF was set at compile time, when
  2261. PCRE2_NO_UTF_CHECK is set at match time the effect of passing an in-
  2262. valid string as a subject, or an invalid value of startoffset, is unde-
  2263. fined. Your program may crash or loop indefinitely or give wrong re-
  2264. sults.
  2265. PCRE2_PARTIAL_HARD
  2266. PCRE2_PARTIAL_SOFT
  2267. These options turn on the partial matching feature. A partial match oc-
  2268. curs if the end of the subject string is reached successfully, but
  2269. there are not enough subject characters to complete the match. In addi-
  2270. tion, either at least one character must have been inspected or the
  2271. pattern must contain a lookbehind, or the pattern must be one that
  2272. could match an empty string.
  2273. If this situation arises when PCRE2_PARTIAL_SOFT (but not PCRE2_PAR-
  2274. TIAL_HARD) is set, matching continues by testing any remaining alterna-
  2275. tives. Only if no complete match can be found is PCRE2_ERROR_PARTIAL
  2276. returned instead of PCRE2_ERROR_NOMATCH. In other words, PCRE2_PAR-
  2277. TIAL_SOFT specifies that the caller is prepared to handle a partial
  2278. match, but only if no complete match can be found.
  2279. If PCRE2_PARTIAL_HARD is set, it overrides PCRE2_PARTIAL_SOFT. In this
  2280. case, if a partial match is found, pcre2_match() immediately returns
  2281. PCRE2_ERROR_PARTIAL, without considering any other alternatives. In
  2282. other words, when PCRE2_PARTIAL_HARD is set, a partial match is consid-
  2283. ered to be more important that an alternative complete match.
  2284. There is a more detailed discussion of partial and multi-segment match-
  2285. ing, with examples, in the pcre2partial documentation.
  2286. NEWLINE HANDLING WHEN MATCHING
  2287. When PCRE2 is built, a default newline convention is set; this is usu-
  2288. ally the standard convention for the operating system. The default can
  2289. be overridden in a compile context by calling pcre2_set_newline(). It
  2290. can also be overridden by starting a pattern string with, for example,
  2291. (*CRLF), as described in the section on newline conventions in the
  2292. pcre2pattern page. During matching, the newline choice affects the be-
  2293. haviour of the dot, circumflex, and dollar metacharacters. It may also
  2294. alter the way the match starting position is advanced after a match
  2295. failure for an unanchored pattern.
  2296. When PCRE2_NEWLINE_CRLF, PCRE2_NEWLINE_ANYCRLF, or PCRE2_NEWLINE_ANY is
  2297. set as the newline convention, and a match attempt for an unanchored
  2298. pattern fails when the current starting position is at a CRLF sequence,
  2299. and the pattern contains no explicit matches for CR or LF characters,
  2300. the match position is advanced by two characters instead of one, in
  2301. other words, to after the CRLF.
  2302. The above rule is a compromise that makes the most common cases work as
  2303. expected. For example, if the pattern is .+A (and the PCRE2_DOTALL op-
  2304. tion is not set), it does not match the string "\r\nA" because, after
  2305. failing at the start, it skips both the CR and the LF before retrying.
  2306. However, the pattern [\r\n]A does match that string, because it con-
  2307. tains an explicit CR or LF reference, and so advances only by one char-
  2308. acter after the first failure.
  2309. An explicit match for CR of LF is either a literal appearance of one of
  2310. those characters in the pattern, or one of the \r or \n or equivalent
  2311. octal or hexadecimal escape sequences. Implicit matches such as [^X] do
  2312. not count, nor does \s, even though it includes CR and LF in the char-
  2313. acters that it matches.
  2314. Notwithstanding the above, anomalous effects may still occur when CRLF
  2315. is a valid newline sequence and explicit \r or \n escapes appear in the
  2316. pattern.
  2317. HOW PCRE2_MATCH() RETURNS A STRING AND CAPTURED SUBSTRINGS
  2318. uint32_t pcre2_get_ovector_count(pcre2_match_data *match_data);
  2319. PCRE2_SIZE *pcre2_get_ovector_pointer(pcre2_match_data *match_data);
  2320. In general, a pattern matches a certain portion of the subject, and in
  2321. addition, further substrings from the subject may be picked out by
  2322. parenthesized parts of the pattern. Following the usage in Jeffrey
  2323. Friedl's book, this is called "capturing" in what follows, and the
  2324. phrase "capture group" (Perl terminology) is used for a fragment of a
  2325. pattern that picks out a substring. PCRE2 supports several other kinds
  2326. of parenthesized group that do not cause substrings to be captured. The
  2327. pcre2_pattern_info() function can be used to find out how many capture
  2328. groups there are in a compiled pattern.
  2329. You can use auxiliary functions for accessing captured substrings by
  2330. number or by name, as described in sections below.
  2331. Alternatively, you can make direct use of the vector of PCRE2_SIZE val-
  2332. ues, called the ovector, which contains the offsets of captured
  2333. strings. It is part of the match data block. The function
  2334. pcre2_get_ovector_pointer() returns the address of the ovector, and
  2335. pcre2_get_ovector_count() returns the number of pairs of values it con-
  2336. tains.
  2337. Within the ovector, the first in each pair of values is set to the off-
  2338. set of the first code unit of a substring, and the second is set to the
  2339. offset of the first code unit after the end of a substring. These val-
  2340. ues are always code unit offsets, not character offsets. That is, they
  2341. are byte offsets in the 8-bit library, 16-bit offsets in the 16-bit li-
  2342. brary, and 32-bit offsets in the 32-bit library.
  2343. After a partial match (error return PCRE2_ERROR_PARTIAL), only the
  2344. first pair of offsets (that is, ovector[0] and ovector[1]) are set.
  2345. They identify the part of the subject that was partially matched. See
  2346. the pcre2partial documentation for details of partial matching.
  2347. After a fully successful match, the first pair of offsets identifies
  2348. the portion of the subject string that was matched by the entire pat-
  2349. tern. The next pair is used for the first captured substring, and so
  2350. on. The value returned by pcre2_match() is one more than the highest
  2351. numbered pair that has been set. For example, if two substrings have
  2352. been captured, the returned value is 3. If there are no captured sub-
  2353. strings, the return value from a successful match is 1, indicating that
  2354. just the first pair of offsets has been set.
  2355. If a pattern uses the \K escape sequence within a positive assertion,
  2356. the reported start of a successful match can be greater than the end of
  2357. the match. For example, if the pattern (?=ab\K) is matched against
  2358. "ab", the start and end offset values for the match are 2 and 0.
  2359. If a capture group is matched repeatedly within a single match opera-
  2360. tion, it is the last portion of the subject that it matched that is re-
  2361. turned.
  2362. If the ovector is too small to hold all the captured substring offsets,
  2363. as much as possible is filled in, and the function returns a value of
  2364. zero. If captured substrings are not of interest, pcre2_match() may be
  2365. called with a match data block whose ovector is of minimum length (that
  2366. is, one pair).
  2367. It is possible for capture group number n+1 to match some part of the
  2368. subject when group n has not been used at all. For example, if the
  2369. string "abc" is matched against the pattern (a|(z))(bc) the return from
  2370. the function is 4, and groups 1 and 3 are matched, but 2 is not. When
  2371. this happens, both values in the offset pairs corresponding to unused
  2372. groups are set to PCRE2_UNSET.
  2373. Offset values that correspond to unused groups at the end of the ex-
  2374. pression are also set to PCRE2_UNSET. For example, if the string "abc"
  2375. is matched against the pattern (abc)(x(yz)?)? groups 2 and 3 are not
  2376. matched. The return from the function is 2, because the highest used
  2377. capture group number is 1. The offsets for the second and third capture
  2378. groups (assuming the vector is large enough, of course) are set to
  2379. PCRE2_UNSET.
  2380. Elements in the ovector that do not correspond to capturing parentheses
  2381. in the pattern are never changed. That is, if a pattern contains n cap-
  2382. turing parentheses, no more than ovector[0] to ovector[2n+1] are set by
  2383. pcre2_match(). The other elements retain whatever values they previ-
  2384. ously had. After a failed match attempt, the contents of the ovector
  2385. are unchanged.
  2386. OTHER INFORMATION ABOUT A MATCH
  2387. PCRE2_SPTR pcre2_get_mark(pcre2_match_data *match_data);
  2388. PCRE2_SIZE pcre2_get_startchar(pcre2_match_data *match_data);
  2389. As well as the offsets in the ovector, other information about a match
  2390. is retained in the match data block and can be retrieved by the above
  2391. functions in appropriate circumstances. If they are called at other
  2392. times, the result is undefined.
  2393. After a successful match, a partial match (PCRE2_ERROR_PARTIAL), or a
  2394. failure to match (PCRE2_ERROR_NOMATCH), a mark name may be available.
  2395. The function pcre2_get_mark() can be called to access this name, which
  2396. can be specified in the pattern by any of the backtracking control
  2397. verbs, not just (*MARK). The same function applies to all the verbs. It
  2398. returns a pointer to the zero-terminated name, which is within the com-
  2399. piled pattern. If no name is available, NULL is returned. The length of
  2400. the name (excluding the terminating zero) is stored in the code unit
  2401. that precedes the name. You should use this length instead of relying
  2402. on the terminating zero if the name might contain a binary zero.
  2403. After a successful match, the name that is returned is the last mark
  2404. name encountered on the matching path through the pattern. Instances of
  2405. backtracking verbs without names do not count. Thus, for example, if
  2406. the matching path contains (*MARK:A)(*PRUNE), the name "A" is returned.
  2407. After a "no match" or a partial match, the last encountered name is re-
  2408. turned. For example, consider this pattern:
  2409. ^(*MARK:A)((*MARK:B)a|b)c
  2410. When it matches "bc", the returned name is A. The B mark is "seen" in
  2411. the first branch of the group, but it is not on the matching path. On
  2412. the other hand, when this pattern fails to match "bx", the returned
  2413. name is B.
  2414. Warning: By default, certain start-of-match optimizations are used to
  2415. give a fast "no match" result in some situations. For example, if the
  2416. anchoring is removed from the pattern above, there is an initial check
  2417. for the presence of "c" in the subject before running the matching en-
  2418. gine. This check fails for "bx", causing a match failure without seeing
  2419. any marks. You can disable the start-of-match optimizations by setting
  2420. the PCRE2_NO_START_OPTIMIZE option for pcre2_compile() or by starting
  2421. the pattern with (*NO_START_OPT).
  2422. After a successful match, a partial match, or one of the invalid UTF
  2423. errors (for example, PCRE2_ERROR_UTF8_ERR5), pcre2_get_startchar() can
  2424. be called. After a successful or partial match it returns the code unit
  2425. offset of the character at which the match started. For a non-partial
  2426. match, this can be different to the value of ovector[0] if the pattern
  2427. contains the \K escape sequence. After a partial match, however, this
  2428. value is always the same as ovector[0] because \K does not affect the
  2429. result of a partial match.
  2430. After a UTF check failure, pcre2_get_startchar() can be used to obtain
  2431. the code unit offset of the invalid UTF character. Details are given in
  2432. the pcre2unicode page.
  2433. ERROR RETURNS FROM pcre2_match()
  2434. If pcre2_match() fails, it returns a negative number. This can be con-
  2435. verted to a text string by calling the pcre2_get_error_message() func-
  2436. tion (see "Obtaining a textual error message" below). Negative error
  2437. codes are also returned by other functions, and are documented with
  2438. them. The codes are given names in the header file. If UTF checking is
  2439. in force and an invalid UTF subject string is detected, one of a number
  2440. of UTF-specific negative error codes is returned. Details are given in
  2441. the pcre2unicode page. The following are the other errors that may be
  2442. returned by pcre2_match():
  2443. PCRE2_ERROR_NOMATCH
  2444. The subject string did not match the pattern.
  2445. PCRE2_ERROR_PARTIAL
  2446. The subject string did not match, but it did match partially. See the
  2447. pcre2partial documentation for details of partial matching.
  2448. PCRE2_ERROR_BADMAGIC
  2449. PCRE2 stores a 4-byte "magic number" at the start of the compiled code,
  2450. to catch the case when it is passed a junk pointer. This is the error
  2451. that is returned when the magic number is not present.
  2452. PCRE2_ERROR_BADMODE
  2453. This error is given when a compiled pattern is passed to a function in
  2454. a library of a different code unit width, for example, a pattern com-
  2455. piled by the 8-bit library is passed to a 16-bit or 32-bit library
  2456. function.
  2457. PCRE2_ERROR_BADOFFSET
  2458. The value of startoffset was greater than the length of the subject.
  2459. PCRE2_ERROR_BADOPTION
  2460. An unrecognized bit was set in the options argument.
  2461. PCRE2_ERROR_BADUTFOFFSET
  2462. The UTF code unit sequence that was passed as a subject was checked and
  2463. found to be valid (the PCRE2_NO_UTF_CHECK option was not set), but the
  2464. value of startoffset did not point to the beginning of a UTF character
  2465. or the end of the subject.
  2466. PCRE2_ERROR_CALLOUT
  2467. This error is never generated by pcre2_match() itself. It is provided
  2468. for use by callout functions that want to cause pcre2_match() or
  2469. pcre2_callout_enumerate() to return a distinctive error code. See the
  2470. pcre2callout documentation for details.
  2471. PCRE2_ERROR_DEPTHLIMIT
  2472. The nested backtracking depth limit was reached.
  2473. PCRE2_ERROR_HEAPLIMIT
  2474. The heap limit was reached.
  2475. PCRE2_ERROR_INTERNAL
  2476. An unexpected internal error has occurred. This error could be caused
  2477. by a bug in PCRE2 or by overwriting of the compiled pattern.
  2478. PCRE2_ERROR_JIT_STACKLIMIT
  2479. This error is returned when a pattern that was successfully studied us-
  2480. ing JIT is being matched, but the memory available for the just-in-time
  2481. processing stack is not large enough. See the pcre2jit documentation
  2482. for more details.
  2483. PCRE2_ERROR_MATCHLIMIT
  2484. The backtracking match limit was reached.
  2485. PCRE2_ERROR_NOMEMORY
  2486. Heap memory is used to remember backtracking points. This error is
  2487. given when the memory allocation function (default or custom) fails.
  2488. Note that a different error, PCRE2_ERROR_HEAPLIMIT, is given if the
  2489. amount of memory needed exceeds the heap limit. PCRE2_ERROR_NOMEMORY is
  2490. also returned if PCRE2_COPY_MATCHED_SUBJECT is set and memory alloca-
  2491. tion fails.
  2492. PCRE2_ERROR_NULL
  2493. Either the code, subject, or match_data argument was passed as NULL.
  2494. PCRE2_ERROR_RECURSELOOP
  2495. This error is returned when pcre2_match() detects a recursion loop
  2496. within the pattern. Specifically, it means that either the whole pat-
  2497. tern or a capture group has been called recursively for the second time
  2498. at the same position in the subject string. Some simple patterns that
  2499. might do this are detected and faulted at compile time, but more com-
  2500. plicated cases, in particular mutual recursions between two different
  2501. groups, cannot be detected until matching is attempted.
  2502. OBTAINING A TEXTUAL ERROR MESSAGE
  2503. int pcre2_get_error_message(int errorcode, PCRE2_UCHAR *buffer,
  2504. PCRE2_SIZE bufflen);
  2505. A text message for an error code from any PCRE2 function (compile,
  2506. match, or auxiliary) can be obtained by calling pcre2_get_error_mes-
  2507. sage(). The code is passed as the first argument, with the remaining
  2508. two arguments specifying a code unit buffer and its length in code
  2509. units, into which the text message is placed. The message is returned
  2510. in code units of the appropriate width for the library that is being
  2511. used.
  2512. The returned message is terminated with a trailing zero, and the func-
  2513. tion returns the number of code units used, excluding the trailing
  2514. zero. If the error number is unknown, the negative error code PCRE2_ER-
  2515. ROR_BADDATA is returned. If the buffer is too small, the message is
  2516. truncated (but still with a trailing zero), and the negative error code
  2517. PCRE2_ERROR_NOMEMORY is returned. None of the messages are very long;
  2518. a buffer size of 120 code units is ample.
  2519. EXTRACTING CAPTURED SUBSTRINGS BY NUMBER
  2520. int pcre2_substring_length_bynumber(pcre2_match_data *match_data,
  2521. uint32_t number, PCRE2_SIZE *length);
  2522. int pcre2_substring_copy_bynumber(pcre2_match_data *match_data,
  2523. uint32_t number, PCRE2_UCHAR *buffer,
  2524. PCRE2_SIZE *bufflen);
  2525. int pcre2_substring_get_bynumber(pcre2_match_data *match_data,
  2526. uint32_t number, PCRE2_UCHAR **bufferptr,
  2527. PCRE2_SIZE *bufflen);
  2528. void pcre2_substring_free(PCRE2_UCHAR *buffer);
  2529. Captured substrings can be accessed directly by using the ovector as
  2530. described above. For convenience, auxiliary functions are provided for
  2531. extracting captured substrings as new, separate, zero-terminated
  2532. strings. A substring that contains a binary zero is correctly extracted
  2533. and has a further zero added on the end, but the result is not, of
  2534. course, a C string.
  2535. The functions in this section identify substrings by number. The number
  2536. zero refers to the entire matched substring, with higher numbers refer-
  2537. ring to substrings captured by parenthesized groups. After a partial
  2538. match, only substring zero is available. An attempt to extract any
  2539. other substring gives the error PCRE2_ERROR_PARTIAL. The next section
  2540. describes similar functions for extracting captured substrings by name.
  2541. If a pattern uses the \K escape sequence within a positive assertion,
  2542. the reported start of a successful match can be greater than the end of
  2543. the match. For example, if the pattern (?=ab\K) is matched against
  2544. "ab", the start and end offset values for the match are 2 and 0. In
  2545. this situation, calling these functions with a zero substring number
  2546. extracts a zero-length empty string.
  2547. You can find the length in code units of a captured substring without
  2548. extracting it by calling pcre2_substring_length_bynumber(). The first
  2549. argument is a pointer to the match data block, the second is the group
  2550. number, and the third is a pointer to a variable into which the length
  2551. is placed. If you just want to know whether or not the substring has
  2552. been captured, you can pass the third argument as NULL.
  2553. The pcre2_substring_copy_bynumber() function copies a captured sub-
  2554. string into a supplied buffer, whereas pcre2_substring_get_bynumber()
  2555. copies it into new memory, obtained using the same memory allocation
  2556. function that was used for the match data block. The first two argu-
  2557. ments of these functions are a pointer to the match data block and a
  2558. capture group number.
  2559. The final arguments of pcre2_substring_copy_bynumber() are a pointer to
  2560. the buffer and a pointer to a variable that contains its length in code
  2561. units. This is updated to contain the actual number of code units used
  2562. for the extracted substring, excluding the terminating zero.
  2563. For pcre2_substring_get_bynumber() the third and fourth arguments point
  2564. to variables that are updated with a pointer to the new memory and the
  2565. number of code units that comprise the substring, again excluding the
  2566. terminating zero. When the substring is no longer needed, the memory
  2567. should be freed by calling pcre2_substring_free().
  2568. The return value from all these functions is zero for success, or a
  2569. negative error code. If the pattern match failed, the match failure
  2570. code is returned. If a substring number greater than zero is used af-
  2571. ter a partial match, PCRE2_ERROR_PARTIAL is returned. Other possible
  2572. error codes are:
  2573. PCRE2_ERROR_NOMEMORY
  2574. The buffer was too small for pcre2_substring_copy_bynumber(), or the
  2575. attempt to get memory failed for pcre2_substring_get_bynumber().
  2576. PCRE2_ERROR_NOSUBSTRING
  2577. There is no substring with that number in the pattern, that is, the
  2578. number is greater than the number of capturing parentheses.
  2579. PCRE2_ERROR_UNAVAILABLE
  2580. The substring number, though not greater than the number of captures in
  2581. the pattern, is greater than the number of slots in the ovector, so the
  2582. substring could not be captured.
  2583. PCRE2_ERROR_UNSET
  2584. The substring did not participate in the match. For example, if the
  2585. pattern is (abc)|(def) and the subject is "def", and the ovector con-
  2586. tains at least two capturing slots, substring number 1 is unset.
  2587. EXTRACTING A LIST OF ALL CAPTURED SUBSTRINGS
  2588. int pcre2_substring_list_get(pcre2_match_data *match_data,
  2589. PCRE2_UCHAR ***listptr, PCRE2_SIZE **lengthsptr);
  2590. void pcre2_substring_list_free(PCRE2_UCHAR **list);
  2591. The pcre2_substring_list_get() function extracts all available sub-
  2592. strings and builds a list of pointers to them. It also (optionally)
  2593. builds a second list that contains their lengths (in code units), ex-
  2594. cluding a terminating zero that is added to each of them. All this is
  2595. done in a single block of memory that is obtained using the same memory
  2596. allocation function that was used to get the match data block.
  2597. This function must be called only after a successful match. If called
  2598. after a partial match, the error code PCRE2_ERROR_PARTIAL is returned.
  2599. The address of the memory block is returned via listptr, which is also
  2600. the start of the list of string pointers. The end of the list is marked
  2601. by a NULL pointer. The address of the list of lengths is returned via
  2602. lengthsptr. If your strings do not contain binary zeros and you do not
  2603. therefore need the lengths, you may supply NULL as the lengthsptr argu-
  2604. ment to disable the creation of a list of lengths. The yield of the
  2605. function is zero if all went well, or PCRE2_ERROR_NOMEMORY if the mem-
  2606. ory block could not be obtained. When the list is no longer needed, it
  2607. should be freed by calling pcre2_substring_list_free().
  2608. If this function encounters a substring that is unset, which can happen
  2609. when capture group number n+1 matches some part of the subject, but
  2610. group n has not been used at all, it returns an empty string. This can
  2611. be distinguished from a genuine zero-length substring by inspecting the
  2612. appropriate offset in the ovector, which contain PCRE2_UNSET for unset
  2613. substrings, or by calling pcre2_substring_length_bynumber().
  2614. EXTRACTING CAPTURED SUBSTRINGS BY NAME
  2615. int pcre2_substring_number_from_name(const pcre2_code *code,
  2616. PCRE2_SPTR name);
  2617. int pcre2_substring_length_byname(pcre2_match_data *match_data,
  2618. PCRE2_SPTR name, PCRE2_SIZE *length);
  2619. int pcre2_substring_copy_byname(pcre2_match_data *match_data,
  2620. PCRE2_SPTR name, PCRE2_UCHAR *buffer, PCRE2_SIZE *bufflen);
  2621. int pcre2_substring_get_byname(pcre2_match_data *match_data,
  2622. PCRE2_SPTR name, PCRE2_UCHAR **bufferptr, PCRE2_SIZE *bufflen);
  2623. void pcre2_substring_free(PCRE2_UCHAR *buffer);
  2624. To extract a substring by name, you first have to find associated num-
  2625. ber. For example, for this pattern:
  2626. (a+)b(?<xxx>\d+)...
  2627. the number of the capture group called "xxx" is 2. If the name is known
  2628. to be unique (PCRE2_DUPNAMES was not set), you can find the number from
  2629. the name by calling pcre2_substring_number_from_name(). The first argu-
  2630. ment is the compiled pattern, and the second is the name. The yield of
  2631. the function is the group number, PCRE2_ERROR_NOSUBSTRING if there is
  2632. no group with that name, or PCRE2_ERROR_NOUNIQUESUBSTRING if there is
  2633. more than one group with that name. Given the number, you can extract
  2634. the substring directly from the ovector, or use one of the "bynumber"
  2635. functions described above.
  2636. For convenience, there are also "byname" functions that correspond to
  2637. the "bynumber" functions, the only difference being that the second ar-
  2638. gument is a name instead of a number. If PCRE2_DUPNAMES is set and
  2639. there are duplicate names, these functions scan all the groups with the
  2640. given name, and return the captured substring from the first named
  2641. group that is set.
  2642. If there are no groups with the given name, PCRE2_ERROR_NOSUBSTRING is
  2643. returned. If all groups with the name have numbers that are greater
  2644. than the number of slots in the ovector, PCRE2_ERROR_UNAVAILABLE is re-
  2645. turned. If there is at least one group with a slot in the ovector, but
  2646. no group is found to be set, PCRE2_ERROR_UNSET is returned.
  2647. Warning: If the pattern uses the (?| feature to set up multiple capture
  2648. groups with the same number, as described in the section on duplicate
  2649. group numbers in the pcre2pattern page, you cannot use names to distin-
  2650. guish the different capture groups, because names are not included in
  2651. the compiled code. The matching process uses only numbers. For this
  2652. reason, the use of different names for groups with the same number
  2653. causes an error at compile time.
  2654. CREATING A NEW STRING WITH SUBSTITUTIONS
  2655. int pcre2_substitute(const pcre2_code *code, PCRE2_SPTR subject,
  2656. PCRE2_SIZE length, PCRE2_SIZE startoffset,
  2657. uint32_t options, pcre2_match_data *match_data,
  2658. pcre2_match_context *mcontext, PCRE2_SPTR replacement,
  2659. PCRE2_SIZE rlength, PCRE2_UCHAR *outputbuffer,
  2660. PCRE2_SIZE *outlengthptr);
  2661. This function optionally calls pcre2_match() and then makes a copy of
  2662. the subject string in outputbuffer, replacing parts that were matched
  2663. with the replacement string, whose length is supplied in rlength, which
  2664. can be given as PCRE2_ZERO_TERMINATED for a zero-terminated string. As
  2665. a special case, if replacement is NULL and rlength is zero, the re-
  2666. placement is assumed to be an empty string. If rlength is non-zero, an
  2667. error occurs if replacement is NULL.
  2668. There is an option (see PCRE2_SUBSTITUTE_REPLACEMENT_ONLY below) to re-
  2669. turn just the replacement string(s). The default action is to perform
  2670. just one replacement if the pattern matches, but there is an option
  2671. that requests multiple replacements (see PCRE2_SUBSTITUTE_GLOBAL be-
  2672. low).
  2673. If successful, pcre2_substitute() returns the number of substitutions
  2674. that were carried out. This may be zero if no match was found, and is
  2675. never greater than one unless PCRE2_SUBSTITUTE_GLOBAL is set. A nega-
  2676. tive value is returned if an error is detected.
  2677. Matches in which a \K item in a lookahead in the pattern causes the
  2678. match to end before it starts are not supported, and give rise to an
  2679. error return. For global replacements, matches in which \K in a lookbe-
  2680. hind causes the match to start earlier than the point that was reached
  2681. in the previous iteration are also not supported.
  2682. The first seven arguments of pcre2_substitute() are the same as for
  2683. pcre2_match(), except that the partial matching options are not permit-
  2684. ted, and match_data may be passed as NULL, in which case a match data
  2685. block is obtained and freed within this function, using memory manage-
  2686. ment functions from the match context, if provided, or else those that
  2687. were used to allocate memory for the compiled code.
  2688. If match_data is not NULL and PCRE2_SUBSTITUTE_MATCHED is not set, the
  2689. provided block is used for all calls to pcre2_match(), and its contents
  2690. afterwards are the result of the final call. For global changes, this
  2691. will always be a no-match error. The contents of the ovector within the
  2692. match data block may or may not have been changed.
  2693. As well as the usual options for pcre2_match(), a number of additional
  2694. options can be set in the options argument of pcre2_substitute(). One
  2695. such option is PCRE2_SUBSTITUTE_MATCHED. When this is set, an external
  2696. match_data block must be provided, and it must have already been used
  2697. for an external call to pcre2_match() with the same pattern and subject
  2698. arguments. The data in the match_data block (return code, offset vec-
  2699. tor) is then used for the first substitution instead of calling
  2700. pcre2_match() from within pcre2_substitute(). This allows an applica-
  2701. tion to check for a match before choosing to substitute, without having
  2702. to repeat the match.
  2703. The contents of the externally supplied match data block are not
  2704. changed when PCRE2_SUBSTITUTE_MATCHED is set. If PCRE2_SUBSTI-
  2705. TUTE_GLOBAL is also set, pcre2_match() is called after the first sub-
  2706. stitution to check for further matches, but this is done using an in-
  2707. ternally obtained match data block, thus always leaving the external
  2708. block unchanged.
  2709. The code argument is not used for matching before the first substitu-
  2710. tion when PCRE2_SUBSTITUTE_MATCHED is set, but it must be provided,
  2711. even when PCRE2_SUBSTITUTE_GLOBAL is not set, because it contains in-
  2712. formation such as the UTF setting and the number of capturing parenthe-
  2713. ses in the pattern.
  2714. The default action of pcre2_substitute() is to return a copy of the
  2715. subject string with matched substrings replaced. However, if PCRE2_SUB-
  2716. STITUTE_REPLACEMENT_ONLY is set, only the replacement substrings are
  2717. returned. In the global case, multiple replacements are concatenated in
  2718. the output buffer. Substitution callouts (see below) can be used to
  2719. separate them if necessary.
  2720. The outlengthptr argument of pcre2_substitute() must point to a vari-
  2721. able that contains the length, in code units, of the output buffer. If
  2722. the function is successful, the value is updated to contain the length
  2723. in code units of the new string, excluding the trailing zero that is
  2724. automatically added.
  2725. If the function is not successful, the value set via outlengthptr de-
  2726. pends on the type of error. For syntax errors in the replacement
  2727. string, the value is the offset in the replacement string where the er-
  2728. ror was detected. For other errors, the value is PCRE2_UNSET by de-
  2729. fault. This includes the case of the output buffer being too small, un-
  2730. less PCRE2_SUBSTITUTE_OVERFLOW_LENGTH is set.
  2731. PCRE2_SUBSTITUTE_OVERFLOW_LENGTH changes what happens when the output
  2732. buffer is too small. The default action is to return PCRE2_ERROR_NOMEM-
  2733. ORY immediately. If this option is set, however, pcre2_substitute()
  2734. continues to go through the motions of matching and substituting (with-
  2735. out, of course, writing anything) in order to compute the size of
  2736. buffer that is needed. This value is passed back via the outlengthptr
  2737. variable, with the result of the function still being PCRE2_ER-
  2738. ROR_NOMEMORY.
  2739. Passing a buffer size of zero is a permitted way of finding out how
  2740. much memory is needed for given substitution. However, this does mean
  2741. that the entire operation is carried out twice. Depending on the appli-
  2742. cation, it may be more efficient to allocate a large buffer and free
  2743. the excess afterwards, instead of using PCRE2_SUBSTITUTE_OVER-
  2744. FLOW_LENGTH.
  2745. The replacement string, which is interpreted as a UTF string in UTF
  2746. mode, is checked for UTF validity unless PCRE2_NO_UTF_CHECK is set. An
  2747. invalid UTF replacement string causes an immediate return with the rel-
  2748. evant UTF error code.
  2749. If PCRE2_SUBSTITUTE_LITERAL is set, the replacement string is not in-
  2750. terpreted in any way. By default, however, a dollar character is an es-
  2751. cape character that can specify the insertion of characters from cap-
  2752. ture groups and names from (*MARK) or other control verbs in the pat-
  2753. tern. Dollar is the only escape character (backslash is treated as lit-
  2754. eral). The following forms are always recognized:
  2755. $$ insert a dollar character
  2756. $<n> or ${<n>} insert the contents of group <n>
  2757. $*MARK or ${*MARK} insert a control verb name
  2758. Either a group number or a group name can be given for <n>. Curly
  2759. brackets are required only if the following character would be inter-
  2760. preted as part of the number or name. The number may be zero to include
  2761. the entire matched string. For example, if the pattern a(b)c is
  2762. matched with "=abc=" and the replacement string "+$1$0$1+", the result
  2763. is "=+babcb+=".
  2764. $*MARK inserts the name from the last encountered backtracking control
  2765. verb on the matching path that has a name. (*MARK) must always include
  2766. a name, but the other verbs need not. For example, in the case of
  2767. (*MARK:A)(*PRUNE) the name inserted is "A", but for (*MARK:A)(*PRUNE:B)
  2768. the relevant name is "B". This facility can be used to perform simple
  2769. simultaneous substitutions, as this pcre2test example shows:
  2770. /(*MARK:pear)apple|(*MARK:orange)lemon/g,replace=${*MARK}
  2771. apple lemon
  2772. 2: pear orange
  2773. PCRE2_SUBSTITUTE_GLOBAL causes the function to iterate over the subject
  2774. string, replacing every matching substring. If this option is not set,
  2775. only the first matching substring is replaced. The search for matches
  2776. takes place in the original subject string (that is, previous replace-
  2777. ments do not affect it). Iteration is implemented by advancing the
  2778. startoffset value for each search, which is always passed the entire
  2779. subject string. If an offset limit is set in the match context, search-
  2780. ing stops when that limit is reached.
  2781. You can restrict the effect of a global substitution to a portion of
  2782. the subject string by setting either or both of startoffset and an off-
  2783. set limit. Here is a pcre2test example:
  2784. /B/g,replace=!,use_offset_limit
  2785. ABC ABC ABC ABC\=offset=3,offset_limit=12
  2786. 2: ABC A!C A!C ABC
  2787. When continuing with global substitutions after matching a substring
  2788. with zero length, an attempt to find a non-empty match at the same off-
  2789. set is performed. If this is not successful, the offset is advanced by
  2790. one character except when CRLF is a valid newline sequence and the next
  2791. two characters are CR, LF. In this case, the offset is advanced by two
  2792. characters.
  2793. PCRE2_SUBSTITUTE_UNKNOWN_UNSET causes references to capture groups that
  2794. do not appear in the pattern to be treated as unset groups. This option
  2795. should be used with care, because it means that a typo in a group name
  2796. or number no longer causes the PCRE2_ERROR_NOSUBSTRING error.
  2797. PCRE2_SUBSTITUTE_UNSET_EMPTY causes unset capture groups (including un-
  2798. known groups when PCRE2_SUBSTITUTE_UNKNOWN_UNSET is set) to be treated
  2799. as empty strings when inserted as described above. If this option is
  2800. not set, an attempt to insert an unset group causes the PCRE2_ERROR_UN-
  2801. SET error. This option does not influence the extended substitution
  2802. syntax described below.
  2803. PCRE2_SUBSTITUTE_EXTENDED causes extra processing to be applied to the
  2804. replacement string. Without this option, only the dollar character is
  2805. special, and only the group insertion forms listed above are valid.
  2806. When PCRE2_SUBSTITUTE_EXTENDED is set, two things change:
  2807. Firstly, backslash in a replacement string is interpreted as an escape
  2808. character. The usual forms such as \n or \x{ddd} can be used to specify
  2809. particular character codes, and backslash followed by any non-alphanu-
  2810. meric character quotes that character. Extended quoting can be coded
  2811. using \Q...\E, exactly as in pattern strings.
  2812. There are also four escape sequences for forcing the case of inserted
  2813. letters. The insertion mechanism has three states: no case forcing,
  2814. force upper case, and force lower case. The escape sequences change the
  2815. current state: \U and \L change to upper or lower case forcing, respec-
  2816. tively, and \E (when not terminating a \Q quoted sequence) reverts to
  2817. no case forcing. The sequences \u and \l force the next character (if
  2818. it is a letter) to upper or lower case, respectively, and then the
  2819. state automatically reverts to no case forcing. Case forcing applies to
  2820. all inserted characters, including those from capture groups and let-
  2821. ters within \Q...\E quoted sequences. If either PCRE2_UTF or PCRE2_UCP
  2822. was set when the pattern was compiled, Unicode properties are used for
  2823. case forcing characters whose code points are greater than 127.
  2824. Note that case forcing sequences such as \U...\E do not nest. For exam-
  2825. ple, the result of processing "\Uaa\LBB\Ecc\E" is "AAbbcc"; the final
  2826. \E has no effect. Note also that the PCRE2_ALT_BSUX and PCRE2_EX-
  2827. TRA_ALT_BSUX options do not apply to replacement strings.
  2828. The second effect of setting PCRE2_SUBSTITUTE_EXTENDED is to add more
  2829. flexibility to capture group substitution. The syntax is similar to
  2830. that used by Bash:
  2831. ${<n>:-<string>}
  2832. ${<n>:+<string1>:<string2>}
  2833. As before, <n> may be a group number or a name. The first form speci-
  2834. fies a default value. If group <n> is set, its value is inserted; if
  2835. not, <string> is expanded and the result inserted. The second form
  2836. specifies strings that are expanded and inserted when group <n> is set
  2837. or unset, respectively. The first form is just a convenient shorthand
  2838. for
  2839. ${<n>:+${<n>}:<string>}
  2840. Backslash can be used to escape colons and closing curly brackets in
  2841. the replacement strings. A change of the case forcing state within a
  2842. replacement string remains in force afterwards, as shown in this
  2843. pcre2test example:
  2844. /(some)?(body)/substitute_extended,replace=${1:+\U:\L}HeLLo
  2845. body
  2846. 1: hello
  2847. somebody
  2848. 1: HELLO
  2849. The PCRE2_SUBSTITUTE_UNSET_EMPTY option does not affect these extended
  2850. substitutions. However, PCRE2_SUBSTITUTE_UNKNOWN_UNSET does cause un-
  2851. known groups in the extended syntax forms to be treated as unset.
  2852. If PCRE2_SUBSTITUTE_LITERAL is set, PCRE2_SUBSTITUTE_UNKNOWN_UNSET,
  2853. PCRE2_SUBSTITUTE_UNSET_EMPTY, and PCRE2_SUBSTITUTE_EXTENDED are irrele-
  2854. vant and are ignored.
  2855. Substitution errors
  2856. In the event of an error, pcre2_substitute() returns a negative error
  2857. code. Except for PCRE2_ERROR_NOMATCH (which is never returned), errors
  2858. from pcre2_match() are passed straight back.
  2859. PCRE2_ERROR_NOSUBSTRING is returned for a non-existent substring inser-
  2860. tion, unless PCRE2_SUBSTITUTE_UNKNOWN_UNSET is set.
  2861. PCRE2_ERROR_UNSET is returned for an unset substring insertion (includ-
  2862. ing an unknown substring when PCRE2_SUBSTITUTE_UNKNOWN_UNSET is set)
  2863. when the simple (non-extended) syntax is used and PCRE2_SUBSTITUTE_UN-
  2864. SET_EMPTY is not set.
  2865. PCRE2_ERROR_NOMEMORY is returned if the output buffer is not big
  2866. enough. If the PCRE2_SUBSTITUTE_OVERFLOW_LENGTH option is set, the size
  2867. of buffer that is needed is returned via outlengthptr. Note that this
  2868. does not happen by default.
  2869. PCRE2_ERROR_NULL is returned if PCRE2_SUBSTITUTE_MATCHED is set but the
  2870. match_data argument is NULL or if the subject or replacement arguments
  2871. are NULL. For backward compatibility reasons an exception is made for
  2872. the replacement argument if the rlength argument is also 0.
  2873. PCRE2_ERROR_BADREPLACEMENT is used for miscellaneous syntax errors in
  2874. the replacement string, with more particular errors being PCRE2_ER-
  2875. ROR_BADREPESCAPE (invalid escape sequence), PCRE2_ERROR_REPMISSINGBRACE
  2876. (closing curly bracket not found), PCRE2_ERROR_BADSUBSTITUTION (syntax
  2877. error in extended group substitution), and PCRE2_ERROR_BADSUBSPATTERN
  2878. (the pattern match ended before it started or the match started earlier
  2879. than the current position in the subject, which can happen if \K is
  2880. used in an assertion).
  2881. As for all PCRE2 errors, a text message that describes the error can be
  2882. obtained by calling the pcre2_get_error_message() function (see "Ob-
  2883. taining a textual error message" above).
  2884. Substitution callouts
  2885. int pcre2_set_substitute_callout(pcre2_match_context *mcontext,
  2886. int (*callout_function)(pcre2_substitute_callout_block *, void *),
  2887. void *callout_data);
  2888. The pcre2_set_substitution_callout() function can be used to specify a
  2889. callout function for pcre2_substitute(). This information is passed in
  2890. a match context. The callout function is called after each substitution
  2891. has been processed, but it can cause the replacement not to happen. The
  2892. callout function is not called for simulated substitutions that happen
  2893. as a result of the PCRE2_SUBSTITUTE_OVERFLOW_LENGTH option.
  2894. The first argument of the callout function is a pointer to a substitute
  2895. callout block structure, which contains the following fields, not nec-
  2896. essarily in this order:
  2897. uint32_t version;
  2898. uint32_t subscount;
  2899. PCRE2_SPTR input;
  2900. PCRE2_SPTR output;
  2901. PCRE2_SIZE *ovector;
  2902. uint32_t oveccount;
  2903. PCRE2_SIZE output_offsets[2];
  2904. The version field contains the version number of the block format. The
  2905. current version is 0. The version number will increase in future if
  2906. more fields are added, but the intention is never to remove any of the
  2907. existing fields.
  2908. The subscount field is the number of the current match. It is 1 for the
  2909. first callout, 2 for the second, and so on. The input and output point-
  2910. ers are copies of the values passed to pcre2_substitute().
  2911. The ovector field points to the ovector, which contains the result of
  2912. the most recent match. The oveccount field contains the number of pairs
  2913. that are set in the ovector, and is always greater than zero.
  2914. The output_offsets vector contains the offsets of the replacement in
  2915. the output string. This has already been processed for dollar and (if
  2916. requested) backslash substitutions as described above.
  2917. The second argument of the callout function is the value passed as
  2918. callout_data when the function was registered. The value returned by
  2919. the callout function is interpreted as follows:
  2920. If the value is zero, the replacement is accepted, and, if PCRE2_SUB-
  2921. STITUTE_GLOBAL is set, processing continues with a search for the next
  2922. match. If the value is not zero, the current replacement is not ac-
  2923. cepted. If the value is greater than zero, processing continues when
  2924. PCRE2_SUBSTITUTE_GLOBAL is set. Otherwise (the value is less than zero
  2925. or PCRE2_SUBSTITUTE_GLOBAL is not set), the rest of the input is copied
  2926. to the output and the call to pcre2_substitute() exits, returning the
  2927. number of matches so far.
  2928. DUPLICATE CAPTURE GROUP NAMES
  2929. int pcre2_substring_nametable_scan(const pcre2_code *code,
  2930. PCRE2_SPTR name, PCRE2_SPTR *first, PCRE2_SPTR *last);
  2931. When a pattern is compiled with the PCRE2_DUPNAMES option, names for
  2932. capture groups are not required to be unique. Duplicate names are al-
  2933. ways allowed for groups with the same number, created by using the (?|
  2934. feature. Indeed, if such groups are named, they are required to use the
  2935. same names.
  2936. Normally, patterns that use duplicate names are such that in any one
  2937. match, only one of each set of identically-named groups participates.
  2938. An example is shown in the pcre2pattern documentation.
  2939. When duplicates are present, pcre2_substring_copy_byname() and
  2940. pcre2_substring_get_byname() return the first substring corresponding
  2941. to the given name that is set. Only if none are set is PCRE2_ERROR_UN-
  2942. SET is returned. The pcre2_substring_number_from_name() function re-
  2943. turns the error PCRE2_ERROR_NOUNIQUESUBSTRING when there are duplicate
  2944. names.
  2945. If you want to get full details of all captured substrings for a given
  2946. name, you must use the pcre2_substring_nametable_scan() function. The
  2947. first argument is the compiled pattern, and the second is the name. If
  2948. the third and fourth arguments are NULL, the function returns a group
  2949. number for a unique name, or PCRE2_ERROR_NOUNIQUESUBSTRING otherwise.
  2950. When the third and fourth arguments are not NULL, they must be pointers
  2951. to variables that are updated by the function. After it has run, they
  2952. point to the first and last entries in the name-to-number table for the
  2953. given name, and the function returns the length of each entry in code
  2954. units. In both cases, PCRE2_ERROR_NOSUBSTRING is returned if there are
  2955. no entries for the given name.
  2956. The format of the name table is described above in the section entitled
  2957. Information about a pattern. Given all the relevant entries for the
  2958. name, you can extract each of their numbers, and hence the captured
  2959. data.
  2960. FINDING ALL POSSIBLE MATCHES AT ONE POSITION
  2961. The traditional matching function uses a similar algorithm to Perl,
  2962. which stops when it finds the first match at a given point in the sub-
  2963. ject. If you want to find all possible matches, or the longest possible
  2964. match at a given position, consider using the alternative matching
  2965. function (see below) instead. If you cannot use the alternative func-
  2966. tion, you can kludge it up by making use of the callout facility, which
  2967. is described in the pcre2callout documentation.
  2968. What you have to do is to insert a callout right at the end of the pat-
  2969. tern. When your callout function is called, extract and save the cur-
  2970. rent matched substring. Then return 1, which forces pcre2_match() to
  2971. backtrack and try other alternatives. Ultimately, when it runs out of
  2972. matches, pcre2_match() will yield PCRE2_ERROR_NOMATCH.
  2973. MATCHING A PATTERN: THE ALTERNATIVE FUNCTION
  2974. int pcre2_dfa_match(const pcre2_code *code, PCRE2_SPTR subject,
  2975. PCRE2_SIZE length, PCRE2_SIZE startoffset,
  2976. uint32_t options, pcre2_match_data *match_data,
  2977. pcre2_match_context *mcontext,
  2978. int *workspace, PCRE2_SIZE wscount);
  2979. The function pcre2_dfa_match() is called to match a subject string
  2980. against a compiled pattern, using a matching algorithm that scans the
  2981. subject string just once (not counting lookaround assertions), and does
  2982. not backtrack (except when processing lookaround assertions). This has
  2983. different characteristics to the normal algorithm, and is not compati-
  2984. ble with Perl. Some of the features of PCRE2 patterns are not sup-
  2985. ported. Nevertheless, there are times when this kind of matching can be
  2986. useful. For a discussion of the two matching algorithms, and a list of
  2987. features that pcre2_dfa_match() does not support, see the pcre2matching
  2988. documentation.
  2989. The arguments for the pcre2_dfa_match() function are the same as for
  2990. pcre2_match(), plus two extras. The ovector within the match data block
  2991. is used in a different way, and this is described below. The other com-
  2992. mon arguments are used in the same way as for pcre2_match(), so their
  2993. description is not repeated here.
  2994. The two additional arguments provide workspace for the function. The
  2995. workspace vector should contain at least 20 elements. It is used for
  2996. keeping track of multiple paths through the pattern tree. More work-
  2997. space is needed for patterns and subjects where there are a lot of po-
  2998. tential matches.
  2999. Here is an example of a simple call to pcre2_dfa_match():
  3000. int wspace[20];
  3001. pcre2_match_data *md = pcre2_match_data_create(4, NULL);
  3002. int rc = pcre2_dfa_match(
  3003. re, /* result of pcre2_compile() */
  3004. "some string", /* the subject string */
  3005. 11, /* the length of the subject string */
  3006. 0, /* start at offset 0 in the subject */
  3007. 0, /* default options */
  3008. md, /* the match data block */
  3009. NULL, /* a match context; NULL means use defaults */
  3010. wspace, /* working space vector */
  3011. 20); /* number of elements (NOT size in bytes) */
  3012. Option bits for pcre2_dfa_match()
  3013. The unused bits of the options argument for pcre2_dfa_match() must be
  3014. zero. The only bits that may be set are PCRE2_ANCHORED,
  3015. PCRE2_COPY_MATCHED_SUBJECT, PCRE2_ENDANCHORED, PCRE2_NOTBOL, PCRE2_NO-
  3016. TEOL, PCRE2_NOTEMPTY, PCRE2_NOTEMPTY_ATSTART, PCRE2_NO_UTF_CHECK,
  3017. PCRE2_PARTIAL_HARD, PCRE2_PARTIAL_SOFT, PCRE2_DFA_SHORTEST, and
  3018. PCRE2_DFA_RESTART. All but the last four of these are exactly the same
  3019. as for pcre2_match(), so their description is not repeated here.
  3020. PCRE2_PARTIAL_HARD
  3021. PCRE2_PARTIAL_SOFT
  3022. These have the same general effect as they do for pcre2_match(), but
  3023. the details are slightly different. When PCRE2_PARTIAL_HARD is set for
  3024. pcre2_dfa_match(), it returns PCRE2_ERROR_PARTIAL if the end of the
  3025. subject is reached and there is still at least one matching possibility
  3026. that requires additional characters. This happens even if some complete
  3027. matches have already been found. When PCRE2_PARTIAL_SOFT is set, the
  3028. return code PCRE2_ERROR_NOMATCH is converted into PCRE2_ERROR_PARTIAL
  3029. if the end of the subject is reached, there have been no complete
  3030. matches, but there is still at least one matching possibility. The por-
  3031. tion of the string that was inspected when the longest partial match
  3032. was found is set as the first matching string in both cases. There is a
  3033. more detailed discussion of partial and multi-segment matching, with
  3034. examples, in the pcre2partial documentation.
  3035. PCRE2_DFA_SHORTEST
  3036. Setting the PCRE2_DFA_SHORTEST option causes the matching algorithm to
  3037. stop as soon as it has found one match. Because of the way the alterna-
  3038. tive algorithm works, this is necessarily the shortest possible match
  3039. at the first possible matching point in the subject string.
  3040. PCRE2_DFA_RESTART
  3041. When pcre2_dfa_match() returns a partial match, it is possible to call
  3042. it again, with additional subject characters, and have it continue with
  3043. the same match. The PCRE2_DFA_RESTART option requests this action; when
  3044. it is set, the workspace and wscount options must reference the same
  3045. vector as before because data about the match so far is left in them
  3046. after a partial match. There is more discussion of this facility in the
  3047. pcre2partial documentation.
  3048. Successful returns from pcre2_dfa_match()
  3049. When pcre2_dfa_match() succeeds, it may have matched more than one sub-
  3050. string in the subject. Note, however, that all the matches from one run
  3051. of the function start at the same point in the subject. The shorter
  3052. matches are all initial substrings of the longer matches. For example,
  3053. if the pattern
  3054. <.*>
  3055. is matched against the string
  3056. This is <something> <something else> <something further> no more
  3057. the three matched strings are
  3058. <something> <something else> <something further>
  3059. <something> <something else>
  3060. <something>
  3061. On success, the yield of the function is a number greater than zero,
  3062. which is the number of matched substrings. The offsets of the sub-
  3063. strings are returned in the ovector, and can be extracted by number in
  3064. the same way as for pcre2_match(), but the numbers bear no relation to
  3065. any capture groups that may exist in the pattern, because DFA matching
  3066. does not support capturing.
  3067. Calls to the convenience functions that extract substrings by name re-
  3068. turn the error PCRE2_ERROR_DFA_UFUNC (unsupported function) if used af-
  3069. ter a DFA match. The convenience functions that extract substrings by
  3070. number never return PCRE2_ERROR_NOSUBSTRING.
  3071. The matched strings are stored in the ovector in reverse order of
  3072. length; that is, the longest matching string is first. If there were
  3073. too many matches to fit into the ovector, the yield of the function is
  3074. zero, and the vector is filled with the longest matches.
  3075. NOTE: PCRE2's "auto-possessification" optimization usually applies to
  3076. character repeats at the end of a pattern (as well as internally). For
  3077. example, the pattern "a\d+" is compiled as if it were "a\d++". For DFA
  3078. matching, this means that only one possible match is found. If you re-
  3079. ally do want multiple matches in such cases, either use an ungreedy re-
  3080. peat such as "a\d+?" or set the PCRE2_NO_AUTO_POSSESS option when com-
  3081. piling.
  3082. Error returns from pcre2_dfa_match()
  3083. The pcre2_dfa_match() function returns a negative number when it fails.
  3084. Many of the errors are the same as for pcre2_match(), as described
  3085. above. There are in addition the following errors that are specific to
  3086. pcre2_dfa_match():
  3087. PCRE2_ERROR_DFA_UITEM
  3088. This return is given if pcre2_dfa_match() encounters an item in the
  3089. pattern that it does not support, for instance, the use of \C in a UTF
  3090. mode or a backreference.
  3091. PCRE2_ERROR_DFA_UCOND
  3092. This return is given if pcre2_dfa_match() encounters a condition item
  3093. that uses a backreference for the condition, or a test for recursion in
  3094. a specific capture group. These are not supported.
  3095. PCRE2_ERROR_DFA_UINVALID_UTF
  3096. This return is given if pcre2_dfa_match() is called for a pattern that
  3097. was compiled with PCRE2_MATCH_INVALID_UTF. This is not supported for
  3098. DFA matching.
  3099. PCRE2_ERROR_DFA_WSSIZE
  3100. This return is given if pcre2_dfa_match() runs out of space in the
  3101. workspace vector.
  3102. PCRE2_ERROR_DFA_RECURSE
  3103. When a recursion or subroutine call is processed, the matching function
  3104. calls itself recursively, using private memory for the ovector and
  3105. workspace. This error is given if the internal ovector is not large
  3106. enough. This should be extremely rare, as a vector of size 1000 is
  3107. used.
  3108. PCRE2_ERROR_DFA_BADRESTART
  3109. When pcre2_dfa_match() is called with the PCRE2_DFA_RESTART option,
  3110. some plausibility checks are made on the contents of the workspace,
  3111. which should contain data about the previous partial match. If any of
  3112. these checks fail, this error is given.
  3113. SEE ALSO
  3114. pcre2build(3), pcre2callout(3), pcre2demo(3), pcre2matching(3),
  3115. pcre2partial(3), pcre2posix(3), pcre2sample(3), pcre2unicode(3).
  3116. AUTHOR
  3117. Philip Hazel
  3118. Retired from University Computing Service
  3119. Cambridge, England.
  3120. REVISION
  3121. Last updated: 24 April 2024
  3122. Copyright (c) 1997-2024 University of Cambridge.
  3123. PCRE2 10.44 24 April 2024 PCRE2API(3)
  3124. ------------------------------------------------------------------------------
  3125. PCRE2BUILD(3) Library Functions Manual PCRE2BUILD(3)
  3126. NAME
  3127. PCRE2 - Perl-compatible regular expressions (revised API)
  3128. BUILDING PCRE2
  3129. PCRE2 is distributed with a configure script that can be used to build
  3130. the library in Unix-like environments using the applications known as
  3131. Autotools. Also in the distribution are files to support building using
  3132. CMake instead of configure. The text file README contains general in-
  3133. formation about building with Autotools (some of which is repeated be-
  3134. low), and also has some comments about building on various operating
  3135. systems. The files in the vms directory support building under OpenVMS.
  3136. There is a lot more information about building PCRE2 without using Au-
  3137. totools (including information about using CMake and building "by
  3138. hand") in the text file called NON-AUTOTOOLS-BUILD. You should consult
  3139. this file as well as the README file if you are building in a non-Unix-
  3140. like environment.
  3141. PCRE2 BUILD-TIME OPTIONS
  3142. The rest of this document describes the optional features of PCRE2 that
  3143. can be selected when the library is compiled. It assumes use of the
  3144. configure script, where the optional features are selected or dese-
  3145. lected by providing options to configure before running the make com-
  3146. mand. However, the same options can be selected in both Unix-like and
  3147. non-Unix-like environments if you are using CMake instead of configure
  3148. to build PCRE2.
  3149. If you are not using Autotools or CMake, option selection can be done
  3150. by editing the config.h file, or by passing parameter settings to the
  3151. compiler, as described in NON-AUTOTOOLS-BUILD.
  3152. The complete list of options for configure (which includes the standard
  3153. ones such as the selection of the installation directory) can be ob-
  3154. tained by running
  3155. ./configure --help
  3156. The following sections include descriptions of "on/off" options whose
  3157. names begin with --enable or --disable. Because of the way that config-
  3158. ure works, --enable and --disable always come in pairs, so the comple-
  3159. mentary option always exists as well, but as it specifies the default,
  3160. it is not described. Options that specify values have names that start
  3161. with --with. At the end of a configure run, a summary of the configura-
  3162. tion is output.
  3163. BUILDING 8-BIT, 16-BIT AND 32-BIT LIBRARIES
  3164. By default, a library called libpcre2-8 is built, containing functions
  3165. that take string arguments contained in arrays of bytes, interpreted
  3166. either as single-byte characters, or UTF-8 strings. You can also build
  3167. two other libraries, called libpcre2-16 and libpcre2-32, which process
  3168. strings that are contained in arrays of 16-bit and 32-bit code units,
  3169. respectively. These can be interpreted either as single-unit characters
  3170. or UTF-16/UTF-32 strings. To build these additional libraries, add one
  3171. or both of the following to the configure command:
  3172. --enable-pcre2-16
  3173. --enable-pcre2-32
  3174. If you do not want the 8-bit library, add
  3175. --disable-pcre2-8
  3176. as well. At least one of the three libraries must be built. Note that
  3177. the POSIX wrapper is for the 8-bit library only, and that pcre2grep is
  3178. an 8-bit program. Neither of these are built if you select only the
  3179. 16-bit or 32-bit libraries.
  3180. BUILDING SHARED AND STATIC LIBRARIES
  3181. The Autotools PCRE2 building process uses libtool to build both shared
  3182. and static libraries by default. You can suppress an unwanted library
  3183. by adding one of
  3184. --disable-shared
  3185. --disable-static
  3186. to the configure command. Setting --disable-shared ensures that PCRE2
  3187. libraries are built as static libraries. The binaries that are then
  3188. created as part of the build process (for example, pcre2test and
  3189. pcre2grep) are linked statically with one or more PCRE2 libraries, but
  3190. may also be dynamically linked with other libraries such as libc. If
  3191. you want these binaries to be fully statically linked, you can set LD-
  3192. FLAGS like this:
  3193. LDFLAGS=--static ./configure --disable-shared
  3194. Note the two hyphens in --static. Of course, this works only if static
  3195. versions of all the relevant libraries are available for linking.
  3196. UNICODE AND UTF SUPPORT
  3197. By default, PCRE2 is built with support for Unicode and UTF character
  3198. strings. To build it without Unicode support, add
  3199. --disable-unicode
  3200. to the configure command. This setting applies to all three libraries.
  3201. It is not possible to build one library with Unicode support and an-
  3202. other without in the same configuration.
  3203. Of itself, Unicode support does not make PCRE2 treat strings as UTF-8,
  3204. UTF-16 or UTF-32. To do that, applications that use the library can set
  3205. the PCRE2_UTF option when they call pcre2_compile() to compile a pat-
  3206. tern. Alternatively, patterns may be started with (*UTF) unless the
  3207. application has locked this out by setting PCRE2_NEVER_UTF.
  3208. UTF support allows the libraries to process character code points up to
  3209. 0x10ffff in the strings that they handle. Unicode support also gives
  3210. access to the Unicode properties of characters, using pattern escapes
  3211. such as \P, \p, and \X. Only the general category properties such as Lu
  3212. and Nd, script names, and some bi-directional properties are supported.
  3213. Details are given in the pcre2pattern documentation.
  3214. Pattern escapes such as \d and \w do not by default make use of Unicode
  3215. properties. The application can request that they do by setting the
  3216. PCRE2_UCP option. Unless the application has set PCRE2_NEVER_UCP, a
  3217. pattern may also request this by starting with (*UCP).
  3218. DISABLING THE USE OF \C
  3219. The \C escape sequence, which matches a single code unit, even in a UTF
  3220. mode, can cause unpredictable behaviour because it may leave the cur-
  3221. rent matching point in the middle of a multi-code-unit character. The
  3222. application can lock it out by setting the PCRE2_NEVER_BACKSLASH_C op-
  3223. tion when calling pcre2_compile(). There is also a build-time option
  3224. --enable-never-backslash-C
  3225. (note the upper case C) which locks out the use of \C entirely.
  3226. JUST-IN-TIME COMPILER SUPPORT
  3227. Just-in-time (JIT) compiler support is included in the build by speci-
  3228. fying
  3229. --enable-jit
  3230. This support is available only for certain hardware architectures. If
  3231. this option is set for an unsupported architecture, a building error
  3232. occurs. If in doubt, use
  3233. --enable-jit=auto
  3234. which enables JIT only if the current hardware is supported. You can
  3235. check if JIT is enabled in the configuration summary that is output at
  3236. the end of a configure run. If you are enabling JIT under SELinux you
  3237. may also want to add
  3238. --enable-jit-sealloc
  3239. which enables the use of an execmem allocator in JIT that is compatible
  3240. with SELinux. This has no effect if JIT is not enabled. See the
  3241. pcre2jit documentation for a discussion of JIT usage. When JIT support
  3242. is enabled, pcre2grep automatically makes use of it, unless you add
  3243. --disable-pcre2grep-jit
  3244. to the configure command.
  3245. NEWLINE RECOGNITION
  3246. By default, PCRE2 interprets the linefeed (LF) character as indicating
  3247. the end of a line. This is the normal newline character on Unix-like
  3248. systems. You can compile PCRE2 to use carriage return (CR) instead, by
  3249. adding
  3250. --enable-newline-is-cr
  3251. to the configure command. There is also an --enable-newline-is-lf op-
  3252. tion, which explicitly specifies linefeed as the newline character.
  3253. Alternatively, you can specify that line endings are to be indicated by
  3254. the two-character sequence CRLF (CR immediately followed by LF). If you
  3255. want this, add
  3256. --enable-newline-is-crlf
  3257. to the configure command. There is a fourth option, specified by
  3258. --enable-newline-is-anycrlf
  3259. which causes PCRE2 to recognize any of the three sequences CR, LF, or
  3260. CRLF as indicating a line ending. A fifth option, specified by
  3261. --enable-newline-is-any
  3262. causes PCRE2 to recognize any Unicode newline sequence. The Unicode
  3263. newline sequences are the three just mentioned, plus the single charac-
  3264. ters VT (vertical tab, U+000B), FF (form feed, U+000C), NEL (next line,
  3265. U+0085), LS (line separator, U+2028), and PS (paragraph separator,
  3266. U+2029). The final option is
  3267. --enable-newline-is-nul
  3268. which causes NUL (binary zero) to be set as the default line-ending
  3269. character.
  3270. Whatever default line ending convention is selected when PCRE2 is built
  3271. can be overridden by applications that use the library. At build time
  3272. it is recommended to use the standard for your operating system.
  3273. WHAT \R MATCHES
  3274. By default, the sequence \R in a pattern matches any Unicode newline
  3275. sequence, independently of what has been selected as the line ending
  3276. sequence. If you specify
  3277. --enable-bsr-anycrlf
  3278. the default is changed so that \R matches only CR, LF, or CRLF. What-
  3279. ever is selected when PCRE2 is built can be overridden by applications
  3280. that use the library.
  3281. HANDLING VERY LARGE PATTERNS
  3282. Within a compiled pattern, offset values are used to point from one
  3283. part to another (for example, from an opening parenthesis to an alter-
  3284. nation metacharacter). By default, in the 8-bit and 16-bit libraries,
  3285. two-byte values are used for these offsets, leading to a maximum size
  3286. for a compiled pattern of around 64 thousand code units. This is suffi-
  3287. cient to handle all but the most gigantic patterns. Nevertheless, some
  3288. people do want to process truly enormous patterns, so it is possible to
  3289. compile PCRE2 to use three-byte or four-byte offsets by adding a set-
  3290. ting such as
  3291. --with-link-size=3
  3292. to the configure command. The value given must be 2, 3, or 4. For the
  3293. 16-bit library, a value of 3 is rounded up to 4. In these libraries,
  3294. using longer offsets slows down the operation of PCRE2 because it has
  3295. to load additional data when handling them. For the 32-bit library the
  3296. value is always 4 and cannot be overridden; the value of --with-link-
  3297. size is ignored.
  3298. LIMITING PCRE2 RESOURCE USAGE
  3299. The pcre2_match() function increments a counter each time it goes round
  3300. its main loop. Putting a limit on this counter controls the amount of
  3301. computing resource used by a single call to pcre2_match(). The limit
  3302. can be changed at run time, as described in the pcre2api documentation.
  3303. The default is 10 million, but this can be changed by adding a setting
  3304. such as
  3305. --with-match-limit=500000
  3306. to the configure command. This setting also applies to the
  3307. pcre2_dfa_match() matching function, and to JIT matching (though the
  3308. counting is done differently).
  3309. The pcre2_match() function uses heap memory to record backtracking
  3310. points. The more nested backtracking points there are (that is, the
  3311. deeper the search tree), the more memory is needed. There is an upper
  3312. limit, specified in kibibytes (units of 1024 bytes). This limit can be
  3313. changed at run time, as described in the pcre2api documentation. The
  3314. default limit (in effect unlimited) is 20 million. You can change this
  3315. by a setting such as
  3316. --with-heap-limit=500
  3317. which limits the amount of heap to 500 KiB. This limit applies only to
  3318. interpretive matching in pcre2_match() and pcre2_dfa_match(), which may
  3319. also use the heap for internal workspace when processing complicated
  3320. patterns. This limit does not apply when JIT (which has its own memory
  3321. arrangements) is used.
  3322. You can also explicitly limit the depth of nested backtracking in the
  3323. pcre2_match() interpreter. This limit defaults to the value that is set
  3324. for --with-match-limit. You can set a lower default limit by adding,
  3325. for example,
  3326. --with-match-limit-depth=10000
  3327. to the configure command. This value can be overridden at run time.
  3328. This depth limit indirectly limits the amount of heap memory that is
  3329. used, but because the size of each backtracking "frame" depends on the
  3330. number of capturing parentheses in a pattern, the amount of heap that
  3331. is used before the limit is reached varies from pattern to pattern.
  3332. This limit was more useful in versions before 10.30, where function re-
  3333. cursion was used for backtracking.
  3334. As well as applying to pcre2_match(), the depth limit also controls the
  3335. depth of recursive function calls in pcre2_dfa_match(). These are used
  3336. for lookaround assertions, atomic groups, and recursion within pat-
  3337. terns. The limit does not apply to JIT matching.
  3338. LIMITING VARIABLE-LENGTH LOOKBEHIND ASSERTIONS
  3339. Lookbehind assertions in which one or more branches can match a vari-
  3340. able number of characters are supported only if there is a maximum
  3341. matching length for each top-level branch. There is a limit to this
  3342. maximum that defaults to 255 characters. You can alter this default by
  3343. a setting such as
  3344. --with-max-varlookbehind=100
  3345. The limit can be changed at runtime by calling pcre2_set_max_varlookbe-
  3346. hind(). Lookbehind assertions in which every branch matches a fixed
  3347. number of characters (not necessarily all the same) are not constrained
  3348. by this limit.
  3349. CREATING CHARACTER TABLES AT BUILD TIME
  3350. PCRE2 uses fixed tables for processing characters whose code points are
  3351. less than 256. By default, PCRE2 is built with a set of tables that are
  3352. distributed in the file src/pcre2_chartables.c.dist. These tables are
  3353. for ASCII codes only. If you add
  3354. --enable-rebuild-chartables
  3355. to the configure command, the distributed tables are no longer used.
  3356. Instead, a program called pcre2_dftables is compiled and run. This out-
  3357. puts the source for new set of tables, created in the default locale of
  3358. your C run-time system. This method of replacing the tables does not
  3359. work if you are cross compiling, because pcre2_dftables needs to be run
  3360. on the local host and therefore not compiled with the cross compiler.
  3361. If you need to create alternative tables when cross compiling, you will
  3362. have to do so "by hand". There may also be other reasons for creating
  3363. tables manually. To cause pcre2_dftables to be built on the local
  3364. host, run a normal compiling command, and then run the program with the
  3365. output file as its argument, for example:
  3366. cc src/pcre2_dftables.c -o pcre2_dftables
  3367. ./pcre2_dftables src/pcre2_chartables.c
  3368. This builds the tables in the default locale of the local host. If you
  3369. want to specify a locale, you must use the -L option:
  3370. LC_ALL=fr_FR ./pcre2_dftables -L src/pcre2_chartables.c
  3371. You can also specify -b (with or without -L). This causes the tables to
  3372. be written in binary instead of as source code. A set of binary tables
  3373. can be loaded into memory by an application and passed to pcre2_com-
  3374. pile() in the same way as tables created by calling pcre2_maketables().
  3375. The tables are just a string of bytes, independent of hardware charac-
  3376. teristics such as endianness. This means they can be bundled with an
  3377. application that runs in different environments, to ensure consistent
  3378. behaviour.
  3379. USING EBCDIC CODE
  3380. PCRE2 assumes by default that it will run in an environment where the
  3381. character code is ASCII or Unicode, which is a superset of ASCII. This
  3382. is the case for most computer operating systems. PCRE2 can, however, be
  3383. compiled to run in an 8-bit EBCDIC environment by adding
  3384. --enable-ebcdic --disable-unicode
  3385. to the configure command. This setting implies --enable-rebuild-charta-
  3386. bles. You should only use it if you know that you are in an EBCDIC en-
  3387. vironment (for example, an IBM mainframe operating system).
  3388. It is not possible to support both EBCDIC and UTF-8 codes in the same
  3389. version of the library. Consequently, --enable-unicode and --enable-
  3390. ebcdic are mutually exclusive.
  3391. The EBCDIC character that corresponds to an ASCII LF is assumed to have
  3392. the value 0x15 by default. However, in some EBCDIC environments, 0x25
  3393. is used. In such an environment you should use
  3394. --enable-ebcdic-nl25
  3395. as well as, or instead of, --enable-ebcdic. The EBCDIC character for CR
  3396. has the same value as in ASCII, namely, 0x0d. Whichever of 0x15 and
  3397. 0x25 is not chosen as LF is made to correspond to the Unicode NEL char-
  3398. acter (which, in Unicode, is 0x85).
  3399. The options that select newline behaviour, such as --enable-newline-is-
  3400. cr, and equivalent run-time options, refer to these character values in
  3401. an EBCDIC environment.
  3402. PCRE2GREP SUPPORT FOR EXTERNAL SCRIPTS
  3403. By default pcre2grep supports the use of callouts with string arguments
  3404. within the patterns it is matching. There are two kinds: one that gen-
  3405. erates output using local code, and another that calls an external pro-
  3406. gram or script. If --disable-pcre2grep-callout-fork is added to the
  3407. configure command, only the first kind of callout is supported; if
  3408. --disable-pcre2grep-callout is used, all callouts are completely ig-
  3409. nored. For more details of pcre2grep callouts, see the pcre2grep docu-
  3410. mentation.
  3411. PCRE2GREP OPTIONS FOR COMPRESSED FILE SUPPORT
  3412. By default, pcre2grep reads all files as plain text. You can build it
  3413. so that it recognizes files whose names end in .gz or .bz2, and reads
  3414. them with libz or libbz2, respectively, by adding one or both of
  3415. --enable-pcre2grep-libz
  3416. --enable-pcre2grep-libbz2
  3417. to the configure command. These options naturally require that the rel-
  3418. evant libraries are installed on your system. Configuration will fail
  3419. if they are not.
  3420. PCRE2GREP BUFFER SIZE
  3421. pcre2grep uses an internal buffer to hold a "window" on the file it is
  3422. scanning, in order to be able to output "before" and "after" lines when
  3423. it finds a match. The default starting size of the buffer is 20KiB. The
  3424. buffer itself is three times this size, but because of the way it is
  3425. used for holding "before" lines, the longest line that is guaranteed to
  3426. be processable is the notional buffer size. If a longer line is encoun-
  3427. tered, pcre2grep automatically expands the buffer, up to a specified
  3428. maximum size, whose default is 1MiB or the starting size, whichever is
  3429. the larger. You can change the default parameter values by adding, for
  3430. example,
  3431. --with-pcre2grep-bufsize=51200
  3432. --with-pcre2grep-max-bufsize=2097152
  3433. to the configure command. The caller of pcre2grep can override these
  3434. values by using --buffer-size and --max-buffer-size on the command
  3435. line.
  3436. PCRE2TEST OPTION FOR LIBREADLINE SUPPORT
  3437. If you add one of
  3438. --enable-pcre2test-libreadline
  3439. --enable-pcre2test-libedit
  3440. to the configure command, pcre2test is linked with the libreadline or-
  3441. libedit library, respectively, and when its input is from a terminal,
  3442. it reads it using the readline() function. This provides line-editing
  3443. and history facilities. Note that libreadline is GPL-licensed, so if
  3444. you distribute a binary of pcre2test linked in this way, there may be
  3445. licensing issues. These can be avoided by linking instead with libedit,
  3446. which has a BSD licence.
  3447. Setting --enable-pcre2test-libreadline causes the -lreadline option to
  3448. be added to the pcre2test build. In many operating environments with a
  3449. system-installed readline library this is sufficient. However, in some
  3450. environments (e.g. if an unmodified distribution version of readline is
  3451. in use), some extra configuration may be necessary. The INSTALL file
  3452. for libreadline says this:
  3453. "Readline uses the termcap functions, but does not link with
  3454. the termcap or curses library itself, allowing applications
  3455. which link with readline the to choose an appropriate library."
  3456. If your environment has not been set up so that an appropriate library
  3457. is automatically included, you may need to add something like
  3458. LIBS="-ncurses"
  3459. immediately before the configure command.
  3460. INCLUDING DEBUGGING CODE
  3461. If you add
  3462. --enable-debug
  3463. to the configure command, additional debugging code is included in the
  3464. build. This feature is intended for use by the PCRE2 maintainers.
  3465. DEBUGGING WITH VALGRIND SUPPORT
  3466. If you add
  3467. --enable-valgrind
  3468. to the configure command, PCRE2 will use valgrind annotations to mark
  3469. certain memory regions as unaddressable. This allows it to detect in-
  3470. valid memory accesses, and is mostly useful for debugging PCRE2 itself.
  3471. CODE COVERAGE REPORTING
  3472. If your C compiler is gcc, you can build a version of PCRE2 that can
  3473. generate a code coverage report for its test suite. To enable this, you
  3474. must install lcov version 1.6 or above. Then specify
  3475. --enable-coverage
  3476. to the configure command and build PCRE2 in the usual way.
  3477. Note that using ccache (a caching C compiler) is incompatible with code
  3478. coverage reporting. If you have configured ccache to run automatically
  3479. on your system, you must set the environment variable
  3480. CCACHE_DISABLE=1
  3481. before running make to build PCRE2, so that ccache is not used.
  3482. When --enable-coverage is used, the following addition targets are
  3483. added to the Makefile:
  3484. make coverage
  3485. This creates a fresh coverage report for the PCRE2 test suite. It is
  3486. equivalent to running "make coverage-reset", "make coverage-baseline",
  3487. "make check", and then "make coverage-report".
  3488. make coverage-reset
  3489. This zeroes the coverage counters, but does nothing else.
  3490. make coverage-baseline
  3491. This captures baseline coverage information.
  3492. make coverage-report
  3493. This creates the coverage report.
  3494. make coverage-clean-report
  3495. This removes the generated coverage report without cleaning the cover-
  3496. age data itself.
  3497. make coverage-clean-data
  3498. This removes the captured coverage data without removing the coverage
  3499. files created at compile time (*.gcno).
  3500. make coverage-clean
  3501. This cleans all coverage data including the generated coverage report.
  3502. For more information about code coverage, see the gcov and lcov docu-
  3503. mentation.
  3504. DISABLING THE Z AND T FORMATTING MODIFIERS
  3505. The C99 standard defines formatting modifiers z and t for size_t and
  3506. ptrdiff_t values, respectively. By default, PCRE2 uses these modifiers
  3507. in environments other than old versions of Microsoft Visual Studio when
  3508. __STDC_VERSION__ is defined and has a value greater than or equal to
  3509. 199901L (indicating support for C99). However, there is at least one
  3510. environment that claims to be C99 but does not support these modifiers.
  3511. If
  3512. --disable-percent-zt
  3513. is specified, no use is made of the z or t modifiers. Instead of %td or
  3514. %zu, a suitable format is used depending in the size of long for the
  3515. platform.
  3516. SUPPORT FOR FUZZERS
  3517. There is a special option for use by people who want to run fuzzing
  3518. tests on PCRE2:
  3519. --enable-fuzz-support
  3520. At present this applies only to the 8-bit library. If set, it causes an
  3521. extra library called libpcre2-fuzzsupport.a to be built, but not in-
  3522. stalled. This contains a single function called LLVMFuzzerTestOneIn-
  3523. put() whose arguments are a pointer to a string and the length of the
  3524. string. When called, this function tries to compile the string as a
  3525. pattern, and if that succeeds, to match it. This is done both with no
  3526. options and with some random options bits that are generated from the
  3527. string.
  3528. Setting --enable-fuzz-support also causes a binary called pcre2fuz-
  3529. zcheck to be created. This is normally run under valgrind or used when
  3530. PCRE2 is compiled with address sanitizing enabled. It calls the fuzzing
  3531. function and outputs information about what it is doing. The input
  3532. strings are specified by arguments: if an argument starts with "=" the
  3533. rest of it is a literal input string. Otherwise, it is assumed to be a
  3534. file name, and the contents of the file are the test string.
  3535. OBSOLETE OPTION
  3536. In versions of PCRE2 prior to 10.30, there were two ways of handling
  3537. backtracking in the pcre2_match() function. The default was to use the
  3538. system stack, but if
  3539. --disable-stack-for-recursion
  3540. was set, memory on the heap was used. From release 10.30 onwards this
  3541. has changed (the stack is no longer used) and this option now does
  3542. nothing except give a warning.
  3543. SEE ALSO
  3544. pcre2api(3), pcre2-config(3).
  3545. AUTHOR
  3546. Philip Hazel
  3547. Retired from University Computing Service
  3548. Cambridge, England.
  3549. REVISION
  3550. Last updated: 15 April 2024
  3551. Copyright (c) 1997-2024 University of Cambridge.
  3552. PCRE2 10.44 15 April 2024 PCRE2BUILD(3)
  3553. ------------------------------------------------------------------------------
  3554. PCRE2CALLOUT(3) Library Functions Manual PCRE2CALLOUT(3)
  3555. NAME
  3556. PCRE2 - Perl-compatible regular expressions (revised API)
  3557. SYNOPSIS
  3558. #include <pcre2.h>
  3559. int (*pcre2_callout)(pcre2_callout_block *, void *);
  3560. int pcre2_callout_enumerate(const pcre2_code *code,
  3561. int (*callback)(pcre2_callout_enumerate_block *, void *),
  3562. void *user_data);
  3563. DESCRIPTION
  3564. PCRE2 provides a feature called "callout", which is a means of tem-
  3565. porarily passing control to the caller of PCRE2 in the middle of pat-
  3566. tern matching. The caller of PCRE2 provides an external function by
  3567. putting its entry point in a match context (see pcre2_set_callout() in
  3568. the pcre2api documentation).
  3569. When using the pcre2_substitute() function, an additional callout fea-
  3570. ture is available. This does a callout after each change to the subject
  3571. string and is described in the pcre2api documentation; the rest of this
  3572. document is concerned with callouts during pattern matching.
  3573. Within a regular expression, (?C<arg>) indicates a point at which the
  3574. external function is to be called. Different callout points can be
  3575. identified by putting a number less than 256 after the letter C. The
  3576. default value is zero. Alternatively, the argument may be a delimited
  3577. string. The starting delimiter must be one of ` ' " ^ % # $ { and the
  3578. ending delimiter is the same as the start, except for {, where the end-
  3579. ing delimiter is }. If the ending delimiter is needed within the
  3580. string, it must be doubled. For example, this pattern has two callout
  3581. points:
  3582. (?C1)abc(?C"some ""arbitrary"" text")def
  3583. If the PCRE2_AUTO_CALLOUT option bit is set when a pattern is compiled,
  3584. PCRE2 automatically inserts callouts, all with number 255, before each
  3585. item in the pattern except for immediately before or after an explicit
  3586. callout. For example, if PCRE2_AUTO_CALLOUT is used with the pattern
  3587. A(?C3)B
  3588. it is processed as if it were
  3589. (?C255)A(?C3)B(?C255)
  3590. Here is a more complicated example:
  3591. A(\d{2}|--)
  3592. With PCRE2_AUTO_CALLOUT, this pattern is processed as if it were
  3593. (?C255)A(?C255)((?C255)\d{2}(?C255)|(?C255)-(?C255)-(?C255))(?C255)
  3594. Notice that there is a callout before and after each parenthesis and
  3595. alternation bar. If the pattern contains a conditional group whose con-
  3596. dition is an assertion, an automatic callout is inserted immediately
  3597. before the condition. Such a callout may also be inserted explicitly,
  3598. for example:
  3599. (?(?C9)(?=a)ab|de) (?(?C%text%)(?!=d)ab|de)
  3600. This applies only to assertion conditions (because they are themselves
  3601. independent groups).
  3602. Callouts can be useful for tracking the progress of pattern matching.
  3603. The pcre2test program has a pattern qualifier (/auto_callout) that sets
  3604. automatic callouts. When any callouts are present, the output from
  3605. pcre2test indicates how the pattern is being matched. This is useful
  3606. information when you are trying to optimize the performance of a par-
  3607. ticular pattern.
  3608. MISSING CALLOUTS
  3609. You should be aware that, because of optimizations in the way PCRE2
  3610. compiles and matches patterns, callouts sometimes do not happen exactly
  3611. as you might expect.
  3612. Auto-possessification
  3613. At compile time, PCRE2 "auto-possessifies" repeated items when it knows
  3614. that what follows cannot be part of the repeat. For example, a+[bc] is
  3615. compiled as if it were a++[bc]. The pcre2test output when this pattern
  3616. is compiled with PCRE2_ANCHORED and PCRE2_AUTO_CALLOUT and then applied
  3617. to the string "aaaa" is:
  3618. --->aaaa
  3619. +0 ^ a+
  3620. +2 ^ ^ [bc]
  3621. No match
  3622. This indicates that when matching [bc] fails, there is no backtracking
  3623. into a+ (because it is being treated as a++) and therefore the callouts
  3624. that would be taken for the backtracks do not occur. You can disable
  3625. the auto-possessify feature by passing PCRE2_NO_AUTO_POSSESS to
  3626. pcre2_compile(), or starting the pattern with (*NO_AUTO_POSSESS). In
  3627. this case, the output changes to this:
  3628. --->aaaa
  3629. +0 ^ a+
  3630. +2 ^ ^ [bc]
  3631. +2 ^ ^ [bc]
  3632. +2 ^ ^ [bc]
  3633. +2 ^^ [bc]
  3634. No match
  3635. This time, when matching [bc] fails, the matcher backtracks into a+ and
  3636. tries again, repeatedly, until a+ itself fails.
  3637. Automatic .* anchoring
  3638. By default, an optimization is applied when .* is the first significant
  3639. item in a pattern. If PCRE2_DOTALL is set, so that the dot can match
  3640. any character, the pattern is automatically anchored. If PCRE2_DOTALL
  3641. is not set, a match can start only after an internal newline or at the
  3642. beginning of the subject, and pcre2_compile() remembers this. If a pat-
  3643. tern has more than one top-level branch, automatic anchoring occurs if
  3644. all branches are anchorable.
  3645. This optimization is disabled, however, if .* is in an atomic group or
  3646. if there is a backreference to the capture group in which it appears.
  3647. It is also disabled if the pattern contains (*PRUNE) or (*SKIP). How-
  3648. ever, the presence of callouts does not affect it.
  3649. For example, if the pattern .*\d is compiled with PCRE2_AUTO_CALLOUT
  3650. and applied to the string "aa", the pcre2test output is:
  3651. --->aa
  3652. +0 ^ .*
  3653. +2 ^ ^ \d
  3654. +2 ^^ \d
  3655. +2 ^ \d
  3656. No match
  3657. This shows that all match attempts start at the beginning of the sub-
  3658. ject. In other words, the pattern is anchored. You can disable this op-
  3659. timization by passing PCRE2_NO_DOTSTAR_ANCHOR to pcre2_compile(), or
  3660. starting the pattern with (*NO_DOTSTAR_ANCHOR). In this case, the out-
  3661. put changes to:
  3662. --->aa
  3663. +0 ^ .*
  3664. +2 ^ ^ \d
  3665. +2 ^^ \d
  3666. +2 ^ \d
  3667. +0 ^ .*
  3668. +2 ^^ \d
  3669. +2 ^ \d
  3670. No match
  3671. This shows more match attempts, starting at the second subject charac-
  3672. ter. Another optimization, described in the next section, means that
  3673. there is no subsequent attempt to match with an empty subject.
  3674. Other optimizations
  3675. Other optimizations that provide fast "no match" results also affect
  3676. callouts. For example, if the pattern is
  3677. ab(?C4)cd
  3678. PCRE2 knows that any matching string must contain the letter "d". If
  3679. the subject string is "abyz", the lack of "d" means that matching
  3680. doesn't ever start, and the callout is never reached. However, with
  3681. "abyd", though the result is still no match, the callout is obeyed.
  3682. For most patterns PCRE2 also knows the minimum length of a matching
  3683. string, and will immediately give a "no match" return without actually
  3684. running a match if the subject is not long enough, or, for unanchored
  3685. patterns, if it has been scanned far enough.
  3686. You can disable these optimizations by passing the PCRE2_NO_START_OPTI-
  3687. MIZE option to pcre2_compile(), or by starting the pattern with
  3688. (*NO_START_OPT). This slows down the matching process, but does ensure
  3689. that callouts such as the example above are obeyed.
  3690. THE CALLOUT INTERFACE
  3691. During matching, when PCRE2 reaches a callout point, if an external
  3692. function is provided in the match context, it is called. This applies
  3693. to both normal, DFA, and JIT matching. The first argument to the call-
  3694. out function is a pointer to a pcre2_callout block. The second argument
  3695. is the void * callout data that was supplied when the callout was set
  3696. up by calling pcre2_set_callout() (see the pcre2api documentation). The
  3697. callout block structure contains the following fields, not necessarily
  3698. in this order:
  3699. uint32_t version;
  3700. uint32_t callout_number;
  3701. uint32_t capture_top;
  3702. uint32_t capture_last;
  3703. uint32_t callout_flags;
  3704. PCRE2_SIZE *offset_vector;
  3705. PCRE2_SPTR mark;
  3706. PCRE2_SPTR subject;
  3707. PCRE2_SIZE subject_length;
  3708. PCRE2_SIZE start_match;
  3709. PCRE2_SIZE current_position;
  3710. PCRE2_SIZE pattern_position;
  3711. PCRE2_SIZE next_item_length;
  3712. PCRE2_SIZE callout_string_offset;
  3713. PCRE2_SIZE callout_string_length;
  3714. PCRE2_SPTR callout_string;
  3715. The version field contains the version number of the block format. The
  3716. current version is 2; the three callout string fields were added for
  3717. version 1, and the callout_flags field for version 2. If you are writ-
  3718. ing an application that might use an earlier release of PCRE2, you
  3719. should check the version number before accessing any of these fields.
  3720. The version number will increase in future if more fields are added,
  3721. but the intention is never to remove any of the existing fields.
  3722. Fields for numerical callouts
  3723. For a numerical callout, callout_string is NULL, and callout_number
  3724. contains the number of the callout, in the range 0-255. This is the
  3725. number that follows (?C for callouts that part of the pattern; it is
  3726. 255 for automatically generated callouts.
  3727. Fields for string callouts
  3728. For callouts with string arguments, callout_number is always zero, and
  3729. callout_string points to the string that is contained within the com-
  3730. piled pattern. Its length is given by callout_string_length. Duplicated
  3731. ending delimiters that were present in the original pattern string have
  3732. been turned into single characters, but there is no other processing of
  3733. the callout string argument. An additional code unit containing binary
  3734. zero is present after the string, but is not included in the length.
  3735. The delimiter that was used to start the string is also stored within
  3736. the pattern, immediately before the string itself. You can access this
  3737. delimiter as callout_string[-1] if you need it.
  3738. The callout_string_offset field is the code unit offset to the start of
  3739. the callout argument string within the original pattern string. This is
  3740. provided for the benefit of applications such as script languages that
  3741. might need to report errors in the callout string within the pattern.
  3742. Fields for all callouts
  3743. The remaining fields in the callout block are the same for both kinds
  3744. of callout.
  3745. The offset_vector field is a pointer to a vector of capturing offsets
  3746. (the "ovector"). You may read the elements in this vector, but you must
  3747. not change any of them.
  3748. For calls to pcre2_match(), the offset_vector field is not (since re-
  3749. lease 10.30) a pointer to the actual ovector that was passed to the
  3750. matching function in the match data block. Instead it points to an in-
  3751. ternal ovector of a size large enough to hold all possible captured
  3752. substrings in the pattern. Note that whenever a recursion or subroutine
  3753. call within a pattern completes, the capturing state is reset to what
  3754. it was before.
  3755. The capture_last field contains the number of the most recently cap-
  3756. tured substring, and the capture_top field contains one more than the
  3757. number of the highest numbered captured substring so far. If no sub-
  3758. strings have yet been captured, the value of capture_last is 0 and the
  3759. value of capture_top is 1. The values of these fields do not always
  3760. differ by one; for example, when the callout in the pattern
  3761. ((a)(b))(?C2) is taken, capture_last is 1 but capture_top is 4.
  3762. The contents of ovector[2] to ovector[<capture_top>*2-1] can be in-
  3763. spected in order to extract substrings that have been matched so far,
  3764. in the same way as extracting substrings after a match has completed.
  3765. The values in ovector[0] and ovector[1] are always PCRE2_UNSET because
  3766. the match is by definition not complete. Substrings that have not been
  3767. captured but whose numbers are less than capture_top also have both of
  3768. their ovector slots set to PCRE2_UNSET.
  3769. For DFA matching, the offset_vector field points to the ovector that
  3770. was passed to the matching function in the match data block for call-
  3771. outs at the top level, but to an internal ovector during the processing
  3772. of pattern recursions, lookarounds, and atomic groups. However, these
  3773. ovectors hold no useful information because pcre2_dfa_match() does not
  3774. support substring capturing. The value of capture_top is always 1 and
  3775. the value of capture_last is always 0 for DFA matching.
  3776. The subject and subject_length fields contain copies of the values that
  3777. were passed to the matching function.
  3778. The start_match field normally contains the offset within the subject
  3779. at which the current match attempt started. However, if the escape se-
  3780. quence \K has been encountered, this value is changed to reflect the
  3781. modified starting point. If the pattern is not anchored, the callout
  3782. function may be called several times from the same point in the pattern
  3783. for different starting points in the subject.
  3784. The current_position field contains the offset within the subject of
  3785. the current match pointer.
  3786. The pattern_position field contains the offset in the pattern string to
  3787. the next item to be matched.
  3788. The next_item_length field contains the length of the next item to be
  3789. processed in the pattern string. When the callout is at the end of the
  3790. pattern, the length is zero. When the callout precedes an opening
  3791. parenthesis, the length includes meta characters that follow the paren-
  3792. thesis. For example, in a callout before an assertion such as (?=ab)
  3793. the length is 3. For an alternation bar or a closing parenthesis, the
  3794. length is one, unless a closing parenthesis is followed by a quanti-
  3795. fier, in which case its length is included. (This changed in release
  3796. 10.23. In earlier releases, before an opening parenthesis the length
  3797. was that of the entire group, and before an alternation bar or a clos-
  3798. ing parenthesis the length was zero.)
  3799. The pattern_position and next_item_length fields are intended to help
  3800. in distinguishing between different automatic callouts, which all have
  3801. the same callout number. However, they are set for all callouts, and
  3802. are used by pcre2test to show the next item to be matched when display-
  3803. ing callout information.
  3804. In callouts from pcre2_match() the mark field contains a pointer to the
  3805. zero-terminated name of the most recently passed (*MARK), (*PRUNE), or
  3806. (*THEN) item in the match, or NULL if no such items have been passed.
  3807. Instances of (*PRUNE) or (*THEN) without a name do not obliterate a
  3808. previous (*MARK). In callouts from the DFA matching function this field
  3809. always contains NULL.
  3810. The callout_flags field is always zero in callouts from
  3811. pcre2_dfa_match() or when JIT is being used. When pcre2_match() without
  3812. JIT is used, the following bits may be set:
  3813. PCRE2_CALLOUT_STARTMATCH
  3814. This is set for the first callout after the start of matching for each
  3815. new starting position in the subject.
  3816. PCRE2_CALLOUT_BACKTRACK
  3817. This is set if there has been a matching backtrack since the previous
  3818. callout, or since the start of matching if this is the first callout
  3819. from a pcre2_match() run.
  3820. Both bits are set when a backtrack has caused a "bumpalong" to a new
  3821. starting position in the subject. Output from pcre2test does not indi-
  3822. cate the presence of these bits unless the callout_extra modifier is
  3823. set.
  3824. The information in the callout_flags field is provided so that applica-
  3825. tions can track and tell their users how matching with backtracking is
  3826. done. This can be useful when trying to optimize patterns, or just to
  3827. understand how PCRE2 works. There is no support in pcre2_dfa_match()
  3828. because there is no backtracking in DFA matching, and there is no sup-
  3829. port in JIT because JIT is all about maximimizing matching performance.
  3830. In both these cases the callout_flags field is always zero.
  3831. RETURN VALUES FROM CALLOUTS
  3832. The external callout function returns an integer to PCRE2. If the value
  3833. is zero, matching proceeds as normal. If the value is greater than
  3834. zero, matching fails at the current point, but the testing of other
  3835. matching possibilities goes ahead, just as if a lookahead assertion had
  3836. failed. If the value is less than zero, the match is abandoned, and the
  3837. matching function returns the negative value.
  3838. Negative values should normally be chosen from the set of PCRE2_ER-
  3839. ROR_xxx values. In particular, PCRE2_ERROR_NOMATCH forces a standard
  3840. "no match" failure. The error number PCRE2_ERROR_CALLOUT is reserved
  3841. for use by callout functions; it will never be used by PCRE2 itself.
  3842. CALLOUT ENUMERATION
  3843. int pcre2_callout_enumerate(const pcre2_code *code,
  3844. int (*callback)(pcre2_callout_enumerate_block *, void *),
  3845. void *user_data);
  3846. A script language that supports the use of string arguments in callouts
  3847. might like to scan all the callouts in a pattern before running the
  3848. match. This can be done by calling pcre2_callout_enumerate(). The first
  3849. argument is a pointer to a compiled pattern, the second points to a
  3850. callback function, and the third is arbitrary user data. The callback
  3851. function is called for every callout in the pattern in the order in
  3852. which they appear. Its first argument is a pointer to a callout enumer-
  3853. ation block, and its second argument is the user_data value that was
  3854. passed to pcre2_callout_enumerate(). The data block contains the fol-
  3855. lowing fields:
  3856. version Block version number
  3857. pattern_position Offset to next item in pattern
  3858. next_item_length Length of next item in pattern
  3859. callout_number Number for numbered callouts
  3860. callout_string_offset Offset to string within pattern
  3861. callout_string_length Length of callout string
  3862. callout_string Points to callout string or is NULL
  3863. The version number is currently 0. It will increase if new fields are
  3864. ever added to the block. The remaining fields are the same as their
  3865. namesakes in the pcre2_callout block that is used for callouts during
  3866. matching, as described above.
  3867. Note that the value of pattern_position is unique for each callout.
  3868. However, if a callout occurs inside a group that is quantified with a
  3869. non-zero minimum or a fixed maximum, the group is replicated inside the
  3870. compiled pattern. For example, a pattern such as /(a){2}/ is compiled
  3871. as if it were /(a)(a)/. This means that the callout will be enumerated
  3872. more than once, but with the same value for pattern_position in each
  3873. case.
  3874. The callback function should normally return zero. If it returns a non-
  3875. zero value, scanning the pattern stops, and that value is returned from
  3876. pcre2_callout_enumerate().
  3877. AUTHOR
  3878. Philip Hazel
  3879. Retired from University Computing Service
  3880. Cambridge, England.
  3881. REVISION
  3882. Last updated: 19 January 2024
  3883. Copyright (c) 1997-2024 University of Cambridge.
  3884. PCRE2 10.43 19 January 2024 PCRE2CALLOUT(3)
  3885. ------------------------------------------------------------------------------
  3886. PCRE2COMPAT(3) Library Functions Manual PCRE2COMPAT(3)
  3887. NAME
  3888. PCRE2 - Perl-compatible regular expressions (revised API)
  3889. DIFFERENCES BETWEEN PCRE2 AND PERL
  3890. This document describes some of the known differences in the ways that
  3891. PCRE2 and Perl handle regular expressions. The differences described
  3892. here are with respect to Perl version 5.38.0, but as both Perl and
  3893. PCRE2 are continually changing, the information may at times be out of
  3894. date.
  3895. 1. When PCRE2_DOTALL (equivalent to Perl's /s qualifier) is not set,
  3896. the behaviour of the '.' metacharacter differs from Perl. In PCRE2, '.'
  3897. matches the next character unless it is the start of a newline se-
  3898. quence. This means that, if the newline setting is CR, CRLF, or NUL,
  3899. '.' will match the code point LF (0x0A) in ASCII/Unicode environments,
  3900. and NL (either 0x15 or 0x25) when using EBCDIC. In Perl, '.' appears
  3901. never to match LF, even when 0x0A is not a newline indicator.
  3902. 2. PCRE2 has only a subset of Perl's Unicode support. Details of what
  3903. it does have are given in the pcre2unicode page.
  3904. 3. Like Perl, PCRE2 allows repeat quantifiers on parenthesized asser-
  3905. tions, but they do not mean what you might think. For example, (?!a){3}
  3906. does not assert that the next three characters are not "a". It just as-
  3907. serts that the next character is not "a" three times (in principle;
  3908. PCRE2 optimizes this to run the assertion just once). Perl allows some
  3909. repeat quantifiers on other assertions, for example, \b* , but these do
  3910. not seem to have any use. PCRE2 does not allow any kind of quantifier
  3911. on non-lookaround assertions.
  3912. 4. If a braced quantifier such as {1,2} appears where there is nothing
  3913. to repeat (for example, at the start of a branch), PCRE2 raises an er-
  3914. ror whereas Perl treats the quantifier characters as literal.
  3915. 5. Capture groups that occur inside negative lookaround assertions are
  3916. counted, but their entries in the offsets vector are set only when a
  3917. negative assertion is a condition that has a matching branch (that is,
  3918. the condition is false). Perl may set such capture groups in other
  3919. circumstances.
  3920. 6. The following Perl escape sequences are not supported: \F, \l, \L,
  3921. \u, \U, and \N when followed by a character name. \N on its own, match-
  3922. ing a non-newline character, and \N{U+dd..}, matching a Unicode code
  3923. point, are supported. The escapes that modify the case of following
  3924. letters are implemented by Perl's general string-handling and are not
  3925. part of its pattern matching engine. If any of these are encountered by
  3926. PCRE2, an error is generated by default. However, if either of the
  3927. PCRE2_ALT_BSUX or PCRE2_EXTRA_ALT_BSUX options is set, \U and \u are
  3928. interpreted as ECMAScript interprets them.
  3929. 7. The Perl escape sequences \p, \P, and \X are supported only if PCRE2
  3930. is built with Unicode support (the default). The properties that can be
  3931. tested with \p and \P are limited to the general category properties
  3932. such as Lu and Nd, the derived properties Any and LC (synonym L&),
  3933. script names such as Greek or Han, Bidi_Class, Bidi_Control, and a few
  3934. binary properties. Both PCRE2 and Perl support the Cs (surrogate) prop-
  3935. erty, but in PCRE2 its use is limited. See the pcre2pattern documenta-
  3936. tion for details. The long synonyms for property names that Perl sup-
  3937. ports (such as \p{Letter}) are not supported by PCRE2, nor is it per-
  3938. mitted to prefix any of these properties with "Is".
  3939. 8. PCRE2 supports the \Q...\E escape for quoting substrings. Characters
  3940. in between are treated as literals. However, this is slightly different
  3941. from Perl in that $ and @ are also handled as literals inside the
  3942. quotes. In Perl, they cause variable interpolation (PCRE2 does not have
  3943. variables). Also, Perl does "double-quotish backslash interpolation" on
  3944. any backslashes between \Q and \E which, its documentation says, "may
  3945. lead to confusing results". PCRE2 treats a backslash between \Q and \E
  3946. just like any other character. Note the following examples:
  3947. Pattern PCRE2 matches Perl matches
  3948. \Qabc$xyz\E abc$xyz abc followed by the
  3949. contents of $xyz
  3950. \Qabc\$xyz\E abc\$xyz abc\$xyz
  3951. \Qabc\E\$\Qxyz\E abc$xyz abc$xyz
  3952. \QA\B\E A\B A\B
  3953. \Q\\E \ \\E
  3954. The \Q...\E sequence is recognized both inside and outside character
  3955. classes by both PCRE2 and Perl.
  3956. 9. Fairly obviously, PCRE2 does not support the (?{code}) and
  3957. (??{code}) constructions. However, PCRE2 does have a "callout" feature,
  3958. which allows an external function to be called during pattern matching.
  3959. See the pcre2callout documentation for details.
  3960. 10. Subroutine calls (whether recursive or not) were treated as atomic
  3961. groups up to PCRE2 release 10.23, but from release 10.30 this changed,
  3962. and backtracking into subroutine calls is now supported, as in Perl.
  3963. 11. In PCRE2, if any of the backtracking control verbs are used in a
  3964. group that is called as a subroutine (whether or not recursively),
  3965. their effect is confined to that group; it does not extend to the sur-
  3966. rounding pattern. This is not always the case in Perl. In particular,
  3967. if (*THEN) is present in a group that is called as a subroutine, its
  3968. action is limited to that group, even if the group does not contain any
  3969. | characters. Note that such groups are processed as anchored at the
  3970. point where they are tested.
  3971. 12. If a pattern contains more than one backtracking control verb, the
  3972. first one that is backtracked onto acts. For example, in the pattern
  3973. A(*COMMIT)B(*PRUNE)C a failure in B triggers (*COMMIT), but a failure
  3974. in C triggers (*PRUNE). Perl's behaviour is more complex; in many cases
  3975. it is the same as PCRE2, but there are cases where it differs.
  3976. 13. There are some differences that are concerned with the settings of
  3977. captured strings when part of a pattern is repeated. For example,
  3978. matching "aba" against the pattern /^(a(b)?)+$/ in Perl leaves $2 un-
  3979. set, but in PCRE2 it is set to "b".
  3980. 14. PCRE2's handling of duplicate capture group numbers and names is
  3981. not as general as Perl's. This is a consequence of the fact the PCRE2
  3982. works internally just with numbers, using an external table to trans-
  3983. late between numbers and names. In particular, a pattern such as
  3984. (?|(?<a>A)|(?<b>B)), where the two capture groups have the same number
  3985. but different names, is not supported, and causes an error at compile
  3986. time. If it were allowed, it would not be possible to distinguish which
  3987. group matched, because both names map to capture group number 1. To
  3988. avoid this confusing situation, an error is given at compile time.
  3989. 15. Perl used to recognize comments in some places that PCRE2 does not,
  3990. for example, between the ( and ? at the start of a group. If the /x
  3991. modifier is set, Perl allowed white space between ( and ? though the
  3992. latest Perls give an error (for a while it was just deprecated). There
  3993. may still be some cases where Perl behaves differently.
  3994. 16. Perl, when in warning mode, gives warnings for character classes
  3995. such as [A-\d] or [a-[:digit:]]. It then treats the hyphens as liter-
  3996. als. PCRE2 has no warning features, so it gives an error in these cases
  3997. because they are almost certainly user mistakes.
  3998. 17. In PCRE2, the upper/lower case character properties Lu and Ll are
  3999. not affected when case-independent matching is specified. For example,
  4000. \p{Lu} always matches an upper case letter. I think Perl has changed in
  4001. this respect; in the release at the time of writing (5.38), \p{Lu} and
  4002. \p{Ll} match all letters, regardless of case, when case independence is
  4003. specified.
  4004. 18. From release 5.32.0, Perl locks out the use of \K in lookaround as-
  4005. sertions. From release 10.38 PCRE2 does the same by default. However,
  4006. there is an option for re-enabling the previous behaviour. When this
  4007. option is set, \K is acted on when it occurs in positive assertions,
  4008. but is ignored in negative assertions.
  4009. 19. PCRE2 provides some extensions to the Perl regular expression fa-
  4010. cilities. Perl 5.10 included new features that were not in earlier
  4011. versions of Perl, some of which (such as named parentheses) were in
  4012. PCRE2 for some time before. This list is with respect to Perl 5.38:
  4013. (a) If PCRE2_DOLLAR_ENDONLY is set and PCRE2_MULTILINE is not set, the
  4014. $ meta-character matches only at the very end of the string.
  4015. (b) A backslash followed by a letter with no special meaning is
  4016. faulted. (Perl can be made to issue a warning.)
  4017. (c) If PCRE2_UNGREEDY is set, the greediness of the repetition quanti-
  4018. fiers is inverted, that is, by default they are not greedy, but if fol-
  4019. lowed by a question mark they are.
  4020. (d) PCRE2_ANCHORED can be used at matching time to force a pattern to
  4021. be tried only at the first matching position in the subject string.
  4022. (e) The PCRE2_NOTBOL, PCRE2_NOTEOL, PCRE2_NOTEMPTY and
  4023. PCRE2_NOTEMPTY_ATSTART options have no Perl equivalents.
  4024. (f) The \R escape sequence can be restricted to match only CR, LF, or
  4025. CRLF by the PCRE2_BSR_ANYCRLF option.
  4026. (g) The callout facility is PCRE2-specific. Perl supports codeblocks
  4027. and variable interpolation, but not general hooks on every match.
  4028. (h) The partial matching facility is PCRE2-specific.
  4029. (i) The alternative matching function (pcre2_dfa_match() matches in a
  4030. different way and is not Perl-compatible.
  4031. (j) PCRE2 recognizes some special sequences such as (*CR) or (*NO_JIT)
  4032. at the start of a pattern. These set overall options that cannot be
  4033. changed within the pattern.
  4034. (k) PCRE2 supports non-atomic positive lookaround assertions. This is
  4035. an extension to the lookaround facilities. The default, Perl-compatible
  4036. lookarounds are atomic.
  4037. (l) There are three syntactical items in patterns that can refer to a
  4038. capturing group by number: back references such as \g{2}, subroutine
  4039. calls such as (?3), and condition references such as (?(4)...). PCRE2
  4040. supports relative group numbers such as +2 and -4 in all three cases.
  4041. Perl supports both plus and minus for subroutine calls, but only minus
  4042. for back references, and no relative numbering at all for conditions.
  4043. 20. Perl has different limits than PCRE2. See the pcre2limit documenta-
  4044. tion for details. Perl went with 5.10 from recursion to iteration keep-
  4045. ing the intermediate matches on the heap, which is ~10% slower but does
  4046. not fall into any stack-overflow limit. PCRE2 made a similar change at
  4047. release 10.30, and also has many build-time and run-time customizable
  4048. limits.
  4049. 21. Unlike Perl, PCRE2 doesn't have character set modifiers and spe-
  4050. cially no way to set characters by context just like Perl's "/d". A
  4051. regular expression using PCRE2_UTF and PCRE2_UCP will use similar rules
  4052. to Perl's "/u"; something closer to "/a" could be selected by adding
  4053. other PCRE2_EXTRA_ASCII* options on top.
  4054. 22. Some recursive patterns that Perl diagnoses as infinite recursions
  4055. can be handled by PCRE2, either by the interpreter or the JIT. An exam-
  4056. ple is /(?:|(?0)abcd)(?(R)|\z)/, which matches a sequence of any number
  4057. of repeated "abcd" substrings at the end of the subject.
  4058. AUTHOR
  4059. Philip Hazel
  4060. Retired from University Computing Service
  4061. Cambridge, England.
  4062. REVISION
  4063. Last updated: 30 November 2023
  4064. Copyright (c) 1997-2023 University of Cambridge.
  4065. PCRE2 10.43 30 November 2023 PCRE2COMPAT(3)
  4066. ------------------------------------------------------------------------------
  4067. PCRE2JIT(3) Library Functions Manual PCRE2JIT(3)
  4068. NAME
  4069. PCRE2 - Perl-compatible regular expressions (revised API)
  4070. PCRE2 JUST-IN-TIME COMPILER SUPPORT
  4071. Just-in-time compiling is a heavyweight optimization that can greatly
  4072. speed up pattern matching. However, it comes at the cost of extra pro-
  4073. cessing before the match is performed, so it is of most benefit when
  4074. the same pattern is going to be matched many times. This does not nec-
  4075. essarily mean many calls of a matching function; if the pattern is not
  4076. anchored, matching attempts may take place many times at various posi-
  4077. tions in the subject, even for a single call. Therefore, if the subject
  4078. string is very long, it may still pay to use JIT even for one-off
  4079. matches. JIT support is available for all of the 8-bit, 16-bit and
  4080. 32-bit PCRE2 libraries.
  4081. JIT support applies only to the traditional Perl-compatible matching
  4082. function. It does not apply when the DFA matching function is being
  4083. used. The code for JIT support was written by Zoltan Herczeg.
  4084. AVAILABILITY OF JIT SUPPORT
  4085. JIT support is an optional feature of PCRE2. The "configure" option
  4086. --enable-jit (or equivalent CMake option) must be set when PCRE2 is
  4087. built if you want to use JIT. The support is limited to the following
  4088. hardware platforms:
  4089. ARM 32-bit (v7, and Thumb2)
  4090. ARM 64-bit
  4091. IBM s390x 64 bit
  4092. Intel x86 32-bit and 64-bit
  4093. LoongArch 64 bit
  4094. MIPS 32-bit and 64-bit
  4095. Power PC 32-bit and 64-bit
  4096. RISC-V 32-bit and 64-bit
  4097. If --enable-jit is set on an unsupported platform, compilation fails.
  4098. A client program can tell if JIT support is available by calling
  4099. pcre2_config() with the PCRE2_CONFIG_JIT option. The result is one if
  4100. PCRE2 was built with JIT support, and zero otherwise. However, having
  4101. the JIT code available does not guarantee that it will be used for any
  4102. particular match. One reason for this is that there are a number of op-
  4103. tions and pattern items that are not supported by JIT (see below). An-
  4104. other reason is that in some environments JIT is unable to get memory
  4105. in which to build its compiled code. The only guarantee from pcre2_con-
  4106. fig() is that if it returns zero, JIT will definitely not be used.
  4107. A simple program does not need to check availability in order to use
  4108. JIT when possible. The API is implemented in a way that falls back to
  4109. the interpretive code if JIT is not available or cannot be used for a
  4110. given match. For programs that need the best possible performance,
  4111. there is a "fast path" API that is JIT-specific.
  4112. SIMPLE USE OF JIT
  4113. To make use of the JIT support in the simplest way, all you have to do
  4114. is to call pcre2_jit_compile() after successfully compiling a pattern
  4115. with pcre2_compile(). This function has two arguments: the first is the
  4116. compiled pattern pointer that was returned by pcre2_compile(), and the
  4117. second is zero or more of the following option bits: PCRE2_JIT_COM-
  4118. PLETE, PCRE2_JIT_PARTIAL_HARD, or PCRE2_JIT_PARTIAL_SOFT.
  4119. If JIT support is not available, a call to pcre2_jit_compile() does
  4120. nothing and returns PCRE2_ERROR_JIT_BADOPTION. Otherwise, the compiled
  4121. pattern is passed to the JIT compiler, which turns it into machine code
  4122. that executes much faster than the normal interpretive code, but yields
  4123. exactly the same results. The returned value from pcre2_jit_compile()
  4124. is zero on success, or a negative error code.
  4125. There is a limit to the size of pattern that JIT supports, imposed by
  4126. the size of machine stack that it uses. The exact rules are not docu-
  4127. mented because they may change at any time, in particular, when new op-
  4128. timizations are introduced. If a pattern is too big, a call to
  4129. pcre2_jit_compile() returns PCRE2_ERROR_NOMEMORY.
  4130. PCRE2_JIT_COMPLETE requests the JIT compiler to generate code for com-
  4131. plete matches. If you want to run partial matches using the PCRE2_PAR-
  4132. TIAL_HARD or PCRE2_PARTIAL_SOFT options of pcre2_match(), you should
  4133. set one or both of the other options as well as, or instead of
  4134. PCRE2_JIT_COMPLETE. The JIT compiler generates different optimized code
  4135. for each of the three modes (normal, soft partial, hard partial). When
  4136. pcre2_match() is called, the appropriate code is run if it is avail-
  4137. able. Otherwise, the pattern is matched using interpretive code.
  4138. You can call pcre2_jit_compile() multiple times for the same compiled
  4139. pattern. It does nothing if it has previously compiled code for any of
  4140. the option bits. For example, you can call it once with PCRE2_JIT_COM-
  4141. PLETE and (perhaps later, when you find you need partial matching)
  4142. again with PCRE2_JIT_COMPLETE and PCRE2_JIT_PARTIAL_HARD. This time it
  4143. will ignore PCRE2_JIT_COMPLETE and just compile code for partial match-
  4144. ing. If pcre2_jit_compile() is called with no option bits set, it imme-
  4145. diately returns zero. This is an alternative way of testing whether JIT
  4146. is available.
  4147. At present, it is not possible to free JIT compiled code except when
  4148. the entire compiled pattern is freed by calling pcre2_code_free().
  4149. In some circumstances you may need to call additional functions. These
  4150. are described in the section entitled "Controlling the JIT stack" be-
  4151. low.
  4152. There are some pcre2_match() options that are not supported by JIT, and
  4153. there are also some pattern items that JIT cannot handle. Details are
  4154. given below. In both cases, matching automatically falls back to the
  4155. interpretive code. If you want to know whether JIT was actually used
  4156. for a particular match, you should arrange for a JIT callback function
  4157. to be set up as described in the section entitled "Controlling the JIT
  4158. stack" below, even if you do not need to supply a non-default JIT
  4159. stack. Such a callback function is called whenever JIT code is about to
  4160. be obeyed. If the match-time options are not right for JIT execution,
  4161. the callback function is not obeyed.
  4162. If the JIT compiler finds an unsupported item, no JIT data is gener-
  4163. ated. You can find out if JIT compilation was successful for a compiled
  4164. pattern by calling pcre2_pattern_info() with the PCRE2_INFO_JITSIZE op-
  4165. tion. A non-zero result means that JIT compilation was successful. A
  4166. result of 0 means that JIT support is not available, or the pattern was
  4167. not processed by pcre2_jit_compile(), or the JIT compiler was not able
  4168. to handle the pattern. Successful JIT compilation does not, however,
  4169. guarantee the use of JIT at match time because there are some match
  4170. time options that are not supported by JIT.
  4171. MATCHING SUBJECTS CONTAINING INVALID UTF
  4172. When a pattern is compiled with the PCRE2_UTF option, subject strings
  4173. are normally expected to be a valid sequence of UTF code units. By de-
  4174. fault, this is checked at the start of matching and an error is gener-
  4175. ated if invalid UTF is detected. The PCRE2_NO_UTF_CHECK option can be
  4176. passed to pcre2_match() to skip the check (for improved performance) if
  4177. you are sure that a subject string is valid. If this option is used
  4178. with an invalid string, the result is undefined. The calling program
  4179. may crash or loop or otherwise misbehave.
  4180. However, a way of running matches on strings that may contain invalid
  4181. UTF sequences is available. Calling pcre2_compile() with the
  4182. PCRE2_MATCH_INVALID_UTF option has two effects: it tells the inter-
  4183. preter in pcre2_match() to support invalid UTF, and, if pcre2_jit_com-
  4184. pile() is subsequently called, the compiled JIT code also supports in-
  4185. valid UTF. Details of how this support works, in both the JIT and the
  4186. interpretive cases, is given in the pcre2unicode documentation.
  4187. There is also an obsolete option for pcre2_jit_compile() called
  4188. PCRE2_JIT_INVALID_UTF, which currently exists only for backward compat-
  4189. ibility. It is superseded by the pcre2_compile() option
  4190. PCRE2_MATCH_INVALID_UTF and should no longer be used. It may be removed
  4191. in future.
  4192. UNSUPPORTED OPTIONS AND PATTERN ITEMS
  4193. The pcre2_match() options that are supported for JIT matching are
  4194. PCRE2_COPY_MATCHED_SUBJECT, PCRE2_NOTBOL, PCRE2_NOTEOL, PCRE2_NOTEMPTY,
  4195. PCRE2_NOTEMPTY_ATSTART, PCRE2_NO_UTF_CHECK, PCRE2_PARTIAL_HARD, and
  4196. PCRE2_PARTIAL_SOFT. The PCRE2_ANCHORED and PCRE2_ENDANCHORED options
  4197. are not supported at match time.
  4198. If the PCRE2_NO_JIT option is passed to pcre2_match() it disables the
  4199. use of JIT, forcing matching by the interpreter code.
  4200. The only unsupported pattern items are \C (match a single data unit)
  4201. when running in a UTF mode, and a callout immediately before an asser-
  4202. tion condition in a conditional group.
  4203. RETURN VALUES FROM JIT MATCHING
  4204. When a pattern is matched using JIT, the return values are the same as
  4205. those given by the interpretive pcre2_match() code, with the addition
  4206. of one new error code: PCRE2_ERROR_JIT_STACKLIMIT. This means that the
  4207. memory used for the JIT stack was insufficient. See "Controlling the
  4208. JIT stack" below for a discussion of JIT stack usage.
  4209. The error code PCRE2_ERROR_MATCHLIMIT is returned by the JIT code if
  4210. searching a very large pattern tree goes on for too long, as it is in
  4211. the same circumstance when JIT is not used, but the details of exactly
  4212. what is counted are not the same. The PCRE2_ERROR_DEPTHLIMIT error code
  4213. is never returned when JIT matching is used.
  4214. CONTROLLING THE JIT STACK
  4215. When the compiled JIT code runs, it needs a block of memory to use as a
  4216. stack. By default, it uses 32KiB on the machine stack. However, some
  4217. large or complicated patterns need more than this. The error PCRE2_ER-
  4218. ROR_JIT_STACKLIMIT is given when there is not enough stack. Three func-
  4219. tions are provided for managing blocks of memory for use as JIT stacks.
  4220. There is further discussion about the use of JIT stacks in the section
  4221. entitled "JIT stack FAQ" below.
  4222. The pcre2_jit_stack_create() function creates a JIT stack. Its argu-
  4223. ments are a starting size, a maximum size, and a general context (for
  4224. memory allocation functions, or NULL for standard memory allocation).
  4225. It returns a pointer to an opaque structure of type pcre2_jit_stack, or
  4226. NULL if there is an error. The pcre2_jit_stack_free() function is used
  4227. to free a stack that is no longer needed. If its argument is NULL, this
  4228. function returns immediately, without doing anything. (For the techni-
  4229. cally minded: the address space is allocated by mmap or VirtualAlloc.)
  4230. A maximum stack size of 512KiB to 1MiB should be more than enough for
  4231. any pattern.
  4232. The pcre2_jit_stack_assign() function specifies which stack JIT code
  4233. should use. Its arguments are as follows:
  4234. pcre2_match_context *mcontext
  4235. pcre2_jit_callback callback
  4236. void *data
  4237. The first argument is a pointer to a match context. When this is subse-
  4238. quently passed to a matching function, its information determines which
  4239. JIT stack is used. If this argument is NULL, the function returns imme-
  4240. diately, without doing anything. There are three cases for the values
  4241. of the other two options:
  4242. (1) If callback is NULL and data is NULL, an internal 32KiB block
  4243. on the machine stack is used. This is the default when a match
  4244. context is created.
  4245. (2) If callback is NULL and data is not NULL, data must be
  4246. a pointer to a valid JIT stack, the result of calling
  4247. pcre2_jit_stack_create().
  4248. (3) If callback is not NULL, it must point to a function that is
  4249. called with data as an argument at the start of matching, in
  4250. order to set up a JIT stack. If the return from the callback
  4251. function is NULL, the internal 32KiB stack is used; otherwise the
  4252. return value must be a valid JIT stack, the result of calling
  4253. pcre2_jit_stack_create().
  4254. A callback function is obeyed whenever JIT code is about to be run; it
  4255. is not obeyed when pcre2_match() is called with options that are incom-
  4256. patible for JIT matching. A callback function can therefore be used to
  4257. determine whether a match operation was executed by JIT or by the in-
  4258. terpreter.
  4259. You may safely use the same JIT stack for more than one pattern (either
  4260. by assigning directly or by callback), as long as the patterns are
  4261. matched sequentially in the same thread. Currently, the only way to set
  4262. up non-sequential matches in one thread is to use callouts: if a call-
  4263. out function starts another match, that match must use a different JIT
  4264. stack to the one used for currently suspended match(es).
  4265. In a multithread application, if you do not specify a JIT stack, or if
  4266. you assign or pass back NULL from a callback, that is thread-safe, be-
  4267. cause each thread has its own machine stack. However, if you assign or
  4268. pass back a non-NULL JIT stack, this must be a different stack for each
  4269. thread so that the application is thread-safe.
  4270. Strictly speaking, even more is allowed. You can assign the same non-
  4271. NULL stack to a match context that is used by any number of patterns,
  4272. as long as they are not used for matching by multiple threads at the
  4273. same time. For example, you could use the same stack in all compiled
  4274. patterns, with a global mutex in the callback to wait until the stack
  4275. is available for use. However, this is an inefficient solution, and not
  4276. recommended.
  4277. This is a suggestion for how a multithreaded program that needs to set
  4278. up non-default JIT stacks might operate:
  4279. During thread initialization
  4280. thread_local_var = pcre2_jit_stack_create(...)
  4281. During thread exit
  4282. pcre2_jit_stack_free(thread_local_var)
  4283. Use a one-line callback function
  4284. return thread_local_var
  4285. All the functions described in this section do nothing if JIT is not
  4286. available.
  4287. JIT STACK FAQ
  4288. (1) Why do we need JIT stacks?
  4289. PCRE2 (and JIT) is a recursive, depth-first engine, so it needs a stack
  4290. where the local data of the current node is pushed before checking its
  4291. child nodes. Allocating real machine stack on some platforms is diffi-
  4292. cult. For example, the stack chain needs to be updated every time if we
  4293. extend the stack on PowerPC. Although it is possible, its updating
  4294. time overhead decreases performance. So we do the recursion in memory.
  4295. (2) Why don't we simply allocate blocks of memory with malloc()?
  4296. Modern operating systems have a nice feature: they can reserve an ad-
  4297. dress space instead of allocating memory. We can safely allocate memory
  4298. pages inside this address space, so the stack could grow without moving
  4299. memory data (this is important because of pointers). Thus we can allo-
  4300. cate 1MiB address space, and use only a single memory page (usually
  4301. 4KiB) if that is enough. However, we can still grow up to 1MiB anytime
  4302. if needed.
  4303. (3) Who "owns" a JIT stack?
  4304. The owner of the stack is the user program, not the JIT studied pattern
  4305. or anything else. The user program must ensure that if a stack is being
  4306. used by pcre2_match(), (that is, it is assigned to a match context that
  4307. is passed to the pattern currently running), that stack must not be
  4308. used by any other threads (to avoid overwriting the same memory area).
  4309. The best practice for multithreaded programs is to allocate a stack for
  4310. each thread, and return this stack through the JIT callback function.
  4311. (4) When should a JIT stack be freed?
  4312. You can free a JIT stack at any time, as long as it will not be used by
  4313. pcre2_match() again. When you assign the stack to a match context, only
  4314. a pointer is set. There is no reference counting or any other magic.
  4315. You can free compiled patterns, contexts, and stacks in any order, any-
  4316. time. Just do not call pcre2_match() with a match context pointing to
  4317. an already freed stack, as that will cause SEGFAULT. (Also, do not free
  4318. a stack currently used by pcre2_match() in another thread). You can
  4319. also replace the stack in a context at any time when it is not in use.
  4320. You should free the previous stack before assigning a replacement.
  4321. (5) Should I allocate/free a stack every time before/after calling
  4322. pcre2_match()?
  4323. No, because this is too costly in terms of resources. However, you
  4324. could implement some clever idea which release the stack if it is not
  4325. used in let's say two minutes. The JIT callback can help to achieve
  4326. this without keeping a list of patterns.
  4327. (6) OK, the stack is for long term memory allocation. But what happens
  4328. if a pattern causes stack overflow with a stack of 1MiB? Is that 1MiB
  4329. kept until the stack is freed?
  4330. Especially on embedded systems, it might be a good idea to release mem-
  4331. ory sometimes without freeing the stack. There is no API for this at
  4332. the moment. Probably a function call which returns with the currently
  4333. allocated memory for any stack and another which allows releasing mem-
  4334. ory (shrinking the stack) would be a good idea if someone needs this.
  4335. (7) This is too much of a headache. Isn't there any better solution for
  4336. JIT stack handling?
  4337. No, thanks to Windows. If POSIX threads were used everywhere, we could
  4338. throw out this complicated API.
  4339. FREEING JIT SPECULATIVE MEMORY
  4340. void pcre2_jit_free_unused_memory(pcre2_general_context *gcontext);
  4341. The JIT executable allocator does not free all memory when it is possi-
  4342. ble. It expects new allocations, and keeps some free memory around to
  4343. improve allocation speed. However, in low memory conditions, it might
  4344. be better to free all possible memory. You can cause this to happen by
  4345. calling pcre2_jit_free_unused_memory(). Its argument is a general con-
  4346. text, for custom memory management, or NULL for standard memory manage-
  4347. ment.
  4348. EXAMPLE CODE
  4349. This is a single-threaded example that specifies a JIT stack without
  4350. using a callback. A real program should include error checking after
  4351. all the function calls.
  4352. int rc;
  4353. pcre2_code *re;
  4354. pcre2_match_data *match_data;
  4355. pcre2_match_context *mcontext;
  4356. pcre2_jit_stack *jit_stack;
  4357. re = pcre2_compile(pattern, PCRE2_ZERO_TERMINATED, 0,
  4358. &errornumber, &erroffset, NULL);
  4359. rc = pcre2_jit_compile(re, PCRE2_JIT_COMPLETE);
  4360. mcontext = pcre2_match_context_create(NULL);
  4361. jit_stack = pcre2_jit_stack_create(32*1024, 512*1024, NULL);
  4362. pcre2_jit_stack_assign(mcontext, NULL, jit_stack);
  4363. match_data = pcre2_match_data_create(re, 10);
  4364. rc = pcre2_match(re, subject, length, 0, 0, match_data, mcontext);
  4365. /* Process result */
  4366. pcre2_code_free(re);
  4367. pcre2_match_data_free(match_data);
  4368. pcre2_match_context_free(mcontext);
  4369. pcre2_jit_stack_free(jit_stack);
  4370. JIT FAST PATH API
  4371. Because the API described above falls back to interpreted matching when
  4372. JIT is not available, it is convenient for programs that are written
  4373. for general use in many environments. However, calling JIT via
  4374. pcre2_match() does have a performance impact. Programs that are written
  4375. for use where JIT is known to be available, and which need the best
  4376. possible performance, can instead use a "fast path" API to call JIT
  4377. matching directly instead of calling pcre2_match() (obviously only for
  4378. patterns that have been successfully processed by pcre2_jit_compile()).
  4379. The fast path function is called pcre2_jit_match(), and it takes ex-
  4380. actly the same arguments as pcre2_match(). However, the subject string
  4381. must be specified with a length; PCRE2_ZERO_TERMINATED is not sup-
  4382. ported. Unsupported option bits (for example, PCRE2_ANCHORED and
  4383. PCRE2_ENDANCHORED) are ignored, as is the PCRE2_NO_JIT option. The re-
  4384. turn values are also the same as for pcre2_match(), plus PCRE2_ER-
  4385. ROR_JIT_BADOPTION if a matching mode (partial or complete) is requested
  4386. that was not compiled.
  4387. When you call pcre2_match(), as well as testing for invalid options, a
  4388. number of other sanity checks are performed on the arguments. For exam-
  4389. ple, if the subject pointer is NULL but the length is non-zero, an im-
  4390. mediate error is given. Also, unless PCRE2_NO_UTF_CHECK is set, a UTF
  4391. subject string is tested for validity. In the interests of speed, these
  4392. checks do not happen on the JIT fast path. If invalid UTF data is
  4393. passed when PCRE2_MATCH_INVALID_UTF was not set for pcre2_compile(),
  4394. the result is undefined. The program may crash or loop or give wrong
  4395. results. In the absence of PCRE2_MATCH_INVALID_UTF you should call
  4396. pcre2_jit_match() in UTF mode only if you are sure the subject is
  4397. valid.
  4398. Bypassing the sanity checks and the pcre2_match() wrapping can give
  4399. speedups of more than 10%.
  4400. SEE ALSO
  4401. pcre2api(3), pcre2unicode(3)
  4402. AUTHOR
  4403. Philip Hazel (FAQ by Zoltan Herczeg)
  4404. Retired from University Computing Service
  4405. Cambridge, England.
  4406. REVISION
  4407. Last updated: 21 February 2024
  4408. Copyright (c) 1997-2024 University of Cambridge.
  4409. PCRE2 10.43 21 February 2024 PCRE2JIT(3)
  4410. ------------------------------------------------------------------------------
  4411. PCRE2LIMITS(3) Library Functions Manual PCRE2LIMITS(3)
  4412. NAME
  4413. PCRE2 - Perl-compatible regular expressions (revised API)
  4414. SIZE AND OTHER LIMITATIONS
  4415. There are some size limitations in PCRE2 but it is hoped that they will
  4416. never in practice be relevant.
  4417. The maximum size of a compiled pattern is approximately 64 thousand
  4418. code units for the 8-bit and 16-bit libraries if PCRE2 is compiled with
  4419. the default internal linkage size, which is 2 bytes for these li-
  4420. braries. If you want to process regular expressions that are truly
  4421. enormous, you can compile PCRE2 with an internal linkage size of 3 or 4
  4422. (when building the 16-bit library, 3 is rounded up to 4). See the
  4423. README file in the source distribution and the pcre2build documentation
  4424. for details. In these cases the limit is substantially larger. How-
  4425. ever, the speed of execution is slower. In the 32-bit library, the in-
  4426. ternal linkage size is always 4.
  4427. The maximum length of a source pattern string is essentially unlimited;
  4428. it is the largest number a PCRE2_SIZE variable can hold. However, the
  4429. program that calls pcre2_compile() can specify a smaller limit.
  4430. The maximum length (in code units) of a subject string is one less than
  4431. the largest number a PCRE2_SIZE variable can hold. PCRE2_SIZE is an un-
  4432. signed integer type, usually defined as size_t. Its maximum value (that
  4433. is ~(PCRE2_SIZE)0) is reserved as a special indicator for zero-termi-
  4434. nated strings and unset offsets.
  4435. All values in repeating quantifiers must be less than 65536.
  4436. There are two different limits that apply to branches of lookbehind as-
  4437. sertions. If every branch in such an assertion matches a fixed number
  4438. of characters, the maximum length of any branch is 65535 characters. If
  4439. any branch matches a variable number of characters, then the maximum
  4440. matching length for every branch is limited. The default limit is set
  4441. at compile time, defaulting to 255, but can be changed by the calling
  4442. program.
  4443. There is no limit to the number of parenthesized groups, but there can
  4444. be no more than 65535 capture groups, and there is a limit to the depth
  4445. of nesting of parenthesized subpatterns of all kinds. This is imposed
  4446. in order to limit the amount of system stack used at compile time. The
  4447. default limit can be specified when PCRE2 is built; if not, the default
  4448. is set to 250. An application can change this limit by calling
  4449. pcre2_set_parens_nest_limit() to set the limit in a compile context.
  4450. The maximum length of name for a named capture group is 32 code units,
  4451. and the maximum number of such groups is 10000.
  4452. The maximum length of a name in a (*MARK), (*PRUNE), (*SKIP), or
  4453. (*THEN) verb is 255 code units for the 8-bit library and 65535 code
  4454. units for the 16-bit and 32-bit libraries.
  4455. The maximum length of a string argument to a callout is the largest
  4456. number a 32-bit unsigned integer can hold.
  4457. The maximum amount of heap memory used for matching is controlled by
  4458. the heap limit, which can be set in a pattern or in a match context.
  4459. The default is a very large number, effectively unlimited.
  4460. AUTHOR
  4461. Philip Hazel
  4462. Retired from University Computing Service
  4463. Cambridge, England.
  4464. REVISION
  4465. Last updated: August 2023
  4466. Copyright (c) 1997-2023 University of Cambridge.
  4467. PCRE2 10.43 1 August 2023 PCRE2LIMITS(3)
  4468. ------------------------------------------------------------------------------
  4469. PCRE2MATCHING(3) Library Functions Manual PCRE2MATCHING(3)
  4470. NAME
  4471. PCRE2 - Perl-compatible regular expressions (revised API)
  4472. PCRE2 MATCHING ALGORITHMS
  4473. This document describes the two different algorithms that are available
  4474. in PCRE2 for matching a compiled regular expression against a given
  4475. subject string. The "standard" algorithm is the one provided by the
  4476. pcre2_match() function. This works in the same as Perl's matching func-
  4477. tion, and provide a Perl-compatible matching operation. The just-in-
  4478. time (JIT) optimization that is described in the pcre2jit documentation
  4479. is compatible with this function.
  4480. An alternative algorithm is provided by the pcre2_dfa_match() function;
  4481. it operates in a different way, and is not Perl-compatible. This alter-
  4482. native has advantages and disadvantages compared with the standard al-
  4483. gorithm, and these are described below.
  4484. When there is only one possible way in which a given subject string can
  4485. match a pattern, the two algorithms give the same answer. A difference
  4486. arises, however, when there are multiple possibilities. For example, if
  4487. the pattern
  4488. ^<.*>
  4489. is matched against the string
  4490. <something> <something else> <something further>
  4491. there are three possible answers. The standard algorithm finds only one
  4492. of them, whereas the alternative algorithm finds all three.
  4493. REGULAR EXPRESSIONS AS TREES
  4494. The set of strings that are matched by a regular expression can be rep-
  4495. resented as a tree structure. An unlimited repetition in the pattern
  4496. makes the tree of infinite size, but it is still a tree. Matching the
  4497. pattern to a given subject string (from a given starting point) can be
  4498. thought of as a search of the tree. There are two ways to search a
  4499. tree: depth-first and breadth-first, and these correspond to the two
  4500. matching algorithms provided by PCRE2.
  4501. THE STANDARD MATCHING ALGORITHM
  4502. In the terminology of Jeffrey Friedl's book "Mastering Regular Expres-
  4503. sions", the standard algorithm is an "NFA algorithm". It conducts a
  4504. depth-first search of the pattern tree. That is, it proceeds along a
  4505. single path through the tree, checking that the subject matches what is
  4506. required. When there is a mismatch, the algorithm tries any alterna-
  4507. tives at the current point, and if they all fail, it backs up to the
  4508. previous branch point in the tree, and tries the next alternative
  4509. branch at that level. This often involves backing up (moving to the
  4510. left) in the subject string as well. The order in which repetition
  4511. branches are tried is controlled by the greedy or ungreedy nature of
  4512. the quantifier.
  4513. If a leaf node is reached, a matching string has been found, and at
  4514. that point the algorithm stops. Thus, if there is more than one possi-
  4515. ble match, this algorithm returns the first one that it finds. Whether
  4516. this is the shortest, the longest, or some intermediate length depends
  4517. on the way the alternations and the greedy or ungreedy repetition quan-
  4518. tifiers are specified in the pattern.
  4519. Because it ends up with a single path through the tree, it is rela-
  4520. tively straightforward for this algorithm to keep track of the sub-
  4521. strings that are matched by portions of the pattern in parentheses.
  4522. This provides support for capturing parentheses and backreferences.
  4523. THE ALTERNATIVE MATCHING ALGORITHM
  4524. This algorithm conducts a breadth-first search of the tree. Starting
  4525. from the first matching point in the subject, it scans the subject
  4526. string from left to right, once, character by character, and as it does
  4527. this, it remembers all the paths through the tree that represent valid
  4528. matches. In Friedl's terminology, this is a kind of "DFA algorithm",
  4529. though it is not implemented as a traditional finite state machine (it
  4530. keeps multiple states active simultaneously).
  4531. Although the general principle of this matching algorithm is that it
  4532. scans the subject string only once, without backtracking, there is one
  4533. exception: when a lookaround assertion is encountered, the characters
  4534. following or preceding the current point have to be independently in-
  4535. spected.
  4536. The scan continues until either the end of the subject is reached, or
  4537. there are no more unterminated paths. At this point, terminated paths
  4538. represent the different matching possibilities (if there are none, the
  4539. match has failed). Thus, if there is more than one possible match,
  4540. this algorithm finds all of them, and in particular, it finds the
  4541. longest. The matches are returned in the output vector in decreasing
  4542. order of length. There is an option to stop the algorithm after the
  4543. first match (which is necessarily the shortest) is found.
  4544. Note that the size of vector needed to contain all the results depends
  4545. on the number of simultaneous matches, not on the number of parentheses
  4546. in the pattern. Using pcre2_match_data_create_from_pattern() to create
  4547. the match data block is therefore not advisable when doing DFA match-
  4548. ing.
  4549. Note also that all the matches that are found start at the same point
  4550. in the subject. If the pattern
  4551. cat(er(pillar)?)?
  4552. is matched against the string "the caterpillar catchment", the result
  4553. is the three strings "caterpillar", "cater", and "cat" that start at
  4554. the fifth character of the subject. The algorithm does not automati-
  4555. cally move on to find matches that start at later positions.
  4556. PCRE2's "auto-possessification" optimization usually applies to charac-
  4557. ter repeats at the end of a pattern (as well as internally). For exam-
  4558. ple, the pattern "a\d+" is compiled as if it were "a\d++" because there
  4559. is no point even considering the possibility of backtracking into the
  4560. repeated digits. For DFA matching, this means that only one possible
  4561. match is found. If you really do want multiple matches in such cases,
  4562. either use an ungreedy repeat ("a\d+?") or set the PCRE2_NO_AUTO_POS-
  4563. SESS option when compiling.
  4564. There are a number of features of PCRE2 regular expressions that are
  4565. not supported or behave differently in the alternative matching func-
  4566. tion. Those that are not supported cause an error if encountered.
  4567. 1. Because the algorithm finds all possible matches, the greedy or un-
  4568. greedy nature of repetition quantifiers is not relevant (though it may
  4569. affect auto-possessification, as just described). During matching,
  4570. greedy and ungreedy quantifiers are treated in exactly the same way.
  4571. However, possessive quantifiers can make a difference when what follows
  4572. could also match what is quantified, for example in a pattern like
  4573. this:
  4574. ^a++\w!
  4575. This pattern matches "aaab!" but not "aaa!", which would be matched by
  4576. a non-possessive quantifier. Similarly, if an atomic group is present,
  4577. it is matched as if it were a standalone pattern at the current point,
  4578. and the longest match is then "locked in" for the rest of the overall
  4579. pattern.
  4580. 2. When dealing with multiple paths through the tree simultaneously, it
  4581. is not straightforward to keep track of captured substrings for the
  4582. different matching possibilities, and PCRE2's implementation of this
  4583. algorithm does not attempt to do this. This means that no captured sub-
  4584. strings are available.
  4585. 3. Because no substrings are captured, backreferences within the pat-
  4586. tern are not supported.
  4587. 4. For the same reason, conditional expressions that use a backrefer-
  4588. ence as the condition or test for a specific group recursion are not
  4589. supported.
  4590. 5. Again for the same reason, script runs are not supported.
  4591. 6. Because many paths through the tree may be active, the \K escape se-
  4592. quence, which resets the start of the match when encountered (but may
  4593. be on some paths and not on others), is not supported.
  4594. 7. Callouts are supported, but the value of the capture_top field is
  4595. always 1, and the value of the capture_last field is always 0.
  4596. 8. The \C escape sequence, which (in the standard algorithm) always
  4597. matches a single code unit, even in a UTF mode, is not supported in
  4598. these modes, because the alternative algorithm moves through the sub-
  4599. ject string one character (not code unit) at a time, for all active
  4600. paths through the tree.
  4601. 9. Except for (*FAIL), the backtracking control verbs such as (*PRUNE)
  4602. are not supported. (*FAIL) is supported, and behaves like a failing
  4603. negative assertion.
  4604. 10. The PCRE2_MATCH_INVALID_UTF option for pcre2_compile() is not sup-
  4605. ported by pcre2_dfa_match().
  4606. ADVANTAGES OF THE ALTERNATIVE ALGORITHM
  4607. The main advantage of the alternative algorithm is that all possible
  4608. matches (at a single point in the subject) are automatically found, and
  4609. in particular, the longest match is found. To find more than one match
  4610. at the same point using the standard algorithm, you have to do kludgy
  4611. things with callouts.
  4612. Partial matching is possible with this algorithm, though it has some
  4613. limitations. The pcre2partial documentation gives details of partial
  4614. matching and discusses multi-segment matching.
  4615. DISADVANTAGES OF THE ALTERNATIVE ALGORITHM
  4616. The alternative algorithm suffers from a number of disadvantages:
  4617. 1. It is substantially slower than the standard algorithm. This is
  4618. partly because it has to search for all possible matches, but is also
  4619. because it is less susceptible to optimization.
  4620. 2. Capturing parentheses, backreferences, script runs, and matching
  4621. within invalid UTF string are not supported.
  4622. 3. Although atomic groups are supported, their use does not provide the
  4623. performance advantage that it does for the standard algorithm.
  4624. 4. JIT optimization is not supported.
  4625. AUTHOR
  4626. Philip Hazel
  4627. Retired from University Computing Service
  4628. Cambridge, England.
  4629. REVISION
  4630. Last updated: 19 January 2024
  4631. Copyright (c) 1997-2024 University of Cambridge.
  4632. PCRE2 10.43 19 January 2024 PCRE2MATCHING(3)
  4633. ------------------------------------------------------------------------------
  4634. PCRE2PARTIAL(3) Library Functions Manual PCRE2PARTIAL(3)
  4635. NAME
  4636. PCRE2 - Perl-compatible regular expressions
  4637. PARTIAL MATCHING IN PCRE2
  4638. In normal use of PCRE2, if there is a match up to the end of a subject
  4639. string, but more characters are needed to match the entire pattern,
  4640. PCRE2_ERROR_NOMATCH is returned, just like any other failing match.
  4641. There are circumstances where it might be helpful to distinguish this
  4642. "partial match" case.
  4643. One example is an application where the subject string is very long,
  4644. and not all available at once. The requirement here is to be able to do
  4645. the matching segment by segment, but special action is needed when a
  4646. matched substring spans the boundary between two segments.
  4647. Another example is checking a user input string as it is typed, to en-
  4648. sure that it conforms to a required format. Invalid characters can be
  4649. immediately diagnosed and rejected, giving instant feedback.
  4650. Partial matching is a PCRE2-specific feature; it is not Perl-compati-
  4651. ble. It is requested by setting one of the PCRE2_PARTIAL_HARD or
  4652. PCRE2_PARTIAL_SOFT options when calling a matching function. The dif-
  4653. ference between the two options is whether or not a partial match is
  4654. preferred to an alternative complete match, though the details differ
  4655. between the two types of matching function. If both options are set,
  4656. PCRE2_PARTIAL_HARD takes precedence.
  4657. If you want to use partial matching with just-in-time optimized code,
  4658. as well as setting a partial match option for the matching function,
  4659. you must also call pcre2_jit_compile() with one or both of these op-
  4660. tions:
  4661. PCRE2_JIT_PARTIAL_HARD
  4662. PCRE2_JIT_PARTIAL_SOFT
  4663. PCRE2_JIT_COMPLETE should also be set if you are going to run non-par-
  4664. tial matches on the same pattern. Separate code is compiled for each
  4665. mode. If the appropriate JIT mode has not been compiled, interpretive
  4666. matching code is used.
  4667. Setting a partial matching option disables two of PCRE2's standard op-
  4668. timization hints. PCRE2 remembers the last literal code unit in a pat-
  4669. tern, and abandons matching immediately if it is not present in the
  4670. subject string. This optimization cannot be used for a subject string
  4671. that might match only partially. PCRE2 also remembers a minimum length
  4672. of a matching string, and does not bother to run the matching function
  4673. on shorter strings. This optimization is also disabled for partial
  4674. matching.
  4675. REQUIREMENTS FOR A PARTIAL MATCH
  4676. A possible partial match occurs during matching when the end of the
  4677. subject string is reached successfully, but either more characters are
  4678. needed to complete the match, or the addition of more characters might
  4679. change what is matched.
  4680. Example 1: if the pattern is /abc/ and the subject is "ab", more char-
  4681. acters are definitely needed to complete a match. In this case both
  4682. hard and soft matching options yield a partial match.
  4683. Example 2: if the pattern is /ab+/ and the subject is "ab", a complete
  4684. match can be found, but the addition of more characters might change
  4685. what is matched. In this case, only PCRE2_PARTIAL_HARD returns a par-
  4686. tial match; PCRE2_PARTIAL_SOFT returns the complete match.
  4687. On reaching the end of the subject, when PCRE2_PARTIAL_HARD is set, if
  4688. the next pattern item is \z, \Z, \b, \B, or $ there is always a partial
  4689. match. Otherwise, for both options, the next pattern item must be one
  4690. that inspects a character, and at least one of the following must be
  4691. true:
  4692. (1) At least one character has already been inspected. An inspected
  4693. character need not form part of the final matched string; lookbehind
  4694. assertions and the \K escape sequence provide ways of inspecting char-
  4695. acters before the start of a matched string.
  4696. (2) The pattern contains one or more lookbehind assertions. This condi-
  4697. tion exists in case there is a lookbehind that inspects characters be-
  4698. fore the start of the match.
  4699. (3) There is a special case when the whole pattern can match an empty
  4700. string. When the starting point is at the end of the subject, the
  4701. empty string match is a possibility, and if PCRE2_PARTIAL_SOFT is set
  4702. and neither of the above conditions is true, it is returned. However,
  4703. because adding more characters might result in a non-empty match,
  4704. PCRE2_PARTIAL_HARD returns a partial match, which in this case means
  4705. "there is going to be a match at this point, but until some more char-
  4706. acters are added, we do not know if it will be an empty string or some-
  4707. thing longer".
  4708. PARTIAL MATCHING USING pcre2_match()
  4709. When a partial matching option is set, the result of calling
  4710. pcre2_match() can be one of the following:
  4711. A successful match
  4712. A complete match has been found, starting and ending within this sub-
  4713. ject.
  4714. PCRE2_ERROR_NOMATCH
  4715. No match can start anywhere in this subject.
  4716. PCRE2_ERROR_PARTIAL
  4717. Adding more characters may result in a complete match that uses one
  4718. or more characters from the end of this subject.
  4719. When a partial match is returned, the first two elements in the ovector
  4720. point to the portion of the subject that was matched, but the values in
  4721. the rest of the ovector are undefined. The appearance of \K in the pat-
  4722. tern has no effect for a partial match. Consider this pattern:
  4723. /abc\K123/
  4724. If it is matched against "456abc123xyz" the result is a complete match,
  4725. and the ovector defines the matched string as "123", because \K resets
  4726. the "start of match" point. However, if a partial match is requested
  4727. and the subject string is "456abc12", a partial match is found for the
  4728. string "abc12", because all these characters are needed for a subse-
  4729. quent re-match with additional characters.
  4730. If there is more than one partial match, the first one that was found
  4731. provides the data that is returned. Consider this pattern:
  4732. /123\w+X|dogY/
  4733. If this is matched against the subject string "abc123dog", both alter-
  4734. natives fail to match, but the end of the subject is reached during
  4735. matching, so PCRE2_ERROR_PARTIAL is returned. The offsets are set to 3
  4736. and 9, identifying "123dog" as the first partial match. (In this exam-
  4737. ple, there are two partial matches, because "dog" on its own partially
  4738. matches the second alternative.)
  4739. How a partial match is processed by pcre2_match()
  4740. What happens when a partial match is identified depends on which of the
  4741. two partial matching options is set.
  4742. If PCRE2_PARTIAL_HARD is set, PCRE2_ERROR_PARTIAL is returned as soon
  4743. as a partial match is found, without continuing to search for possible
  4744. complete matches. This option is "hard" because it prefers an earlier
  4745. partial match over a later complete match. For this reason, the assump-
  4746. tion is made that the end of the supplied subject string is not the
  4747. true end of the available data, which is why \z, \Z, \b, \B, and $ al-
  4748. ways give a partial match.
  4749. If PCRE2_PARTIAL_SOFT is set, the partial match is remembered, but
  4750. matching continues as normal, and other alternatives in the pattern are
  4751. tried. If no complete match can be found, PCRE2_ERROR_PARTIAL is re-
  4752. turned instead of PCRE2_ERROR_NOMATCH. This option is "soft" because it
  4753. prefers a complete match over a partial match. All the various matching
  4754. items in a pattern behave as if the subject string is potentially com-
  4755. plete; \z, \Z, and $ match at the end of the subject, as normal, and
  4756. for \b and \B the end of the subject is treated as a non-alphanumeric.
  4757. The difference between the two partial matching options can be illus-
  4758. trated by a pattern such as:
  4759. /dog(sbody)?/
  4760. This matches either "dog" or "dogsbody", greedily (that is, it prefers
  4761. the longer string if possible). If it is matched against the string
  4762. "dog" with PCRE2_PARTIAL_SOFT, it yields a complete match for "dog".
  4763. However, if PCRE2_PARTIAL_HARD is set, the result is PCRE2_ERROR_PAR-
  4764. TIAL. On the other hand, if the pattern is made ungreedy the result is
  4765. different:
  4766. /dog(sbody)??/
  4767. In this case the result is always a complete match because that is
  4768. found first, and matching never continues after finding a complete
  4769. match. It might be easier to follow this explanation by thinking of the
  4770. two patterns like this:
  4771. /dog(sbody)?/ is the same as /dogsbody|dog/
  4772. /dog(sbody)??/ is the same as /dog|dogsbody/
  4773. The second pattern will never match "dogsbody", because it will always
  4774. find the shorter match first.
  4775. Example of partial matching using pcre2test
  4776. The pcre2test data modifiers partial_hard (or ph) and partial_soft (or
  4777. ps) set PCRE2_PARTIAL_HARD and PCRE2_PARTIAL_SOFT, respectively, when
  4778. calling pcre2_match(). Here is a run of pcre2test using a pattern that
  4779. matches the whole subject in the form of a date:
  4780. re> /^\d?\d(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d\d$/
  4781. data> 25dec3\=ph
  4782. Partial match: 23dec3
  4783. data> 3ju\=ph
  4784. Partial match: 3ju
  4785. data> 3juj\=ph
  4786. No match
  4787. This example gives the same results for both hard and soft partial
  4788. matching options. Here is an example where there is a difference:
  4789. re> /^\d?\d(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d\d$/
  4790. data> 25jun04\=ps
  4791. 0: 25jun04
  4792. 1: jun
  4793. data> 25jun04\=ph
  4794. Partial match: 25jun04
  4795. With PCRE2_PARTIAL_SOFT, the subject is matched completely. For
  4796. PCRE2_PARTIAL_HARD, however, the subject is assumed not to be complete,
  4797. so there is only a partial match.
  4798. MULTI-SEGMENT MATCHING WITH pcre2_match()
  4799. PCRE was not originally designed with multi-segment matching in mind.
  4800. However, over time, features (including partial matching) that make
  4801. multi-segment matching possible have been added. A very long string can
  4802. be searched segment by segment by calling pcre2_match() repeatedly,
  4803. with the aim of achieving the same results that would happen if the en-
  4804. tire string was available for searching all the time. Normally, the
  4805. strings that are being sought are much shorter than each individual
  4806. segment, and are in the middle of very long strings, so the pattern is
  4807. normally not anchored.
  4808. Special logic must be implemented to handle a matched substring that
  4809. spans a segment boundary. PCRE2_PARTIAL_HARD should be used, because it
  4810. returns a partial match at the end of a segment whenever there is the
  4811. possibility of changing the match by adding more characters. The
  4812. PCRE2_NOTBOL option should also be set for all but the first segment.
  4813. When a partial match occurs, the next segment must be added to the cur-
  4814. rent subject and the match re-run, using the startoffset argument of
  4815. pcre2_match() to begin at the point where the partial match started.
  4816. For example:
  4817. re> /\d?\d(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d\d/
  4818. data> ...the date is 23ja\=ph
  4819. Partial match: 23ja
  4820. data> ...the date is 23jan19 and on that day...\=offset=15
  4821. 0: 23jan19
  4822. 1: jan
  4823. Note the use of the offset modifier to start the new match where the
  4824. partial match was found. In this example, the next segment was added to
  4825. the one in which the partial match was found. This is the most
  4826. straightforward approach, typically using a memory buffer that is twice
  4827. the size of each segment. After a partial match, the first half of the
  4828. buffer is discarded, the second half is moved to the start of the
  4829. buffer, and a new segment is added before repeating the match as in the
  4830. example above. After a no match, the entire buffer can be discarded.
  4831. If there are memory constraints, you may want to discard text that pre-
  4832. cedes a partial match before adding the next segment. Unfortunately,
  4833. this is not at present straightforward. In cases such as the above,
  4834. where the pattern does not contain any lookbehinds, it is sufficient to
  4835. retain only the partially matched substring. However, if the pattern
  4836. contains a lookbehind assertion, characters that precede the start of
  4837. the partial match may have been inspected during the matching process.
  4838. When pcre2test displays a partial match, it indicates these characters
  4839. with '<' if the allusedtext modifier is set:
  4840. re> "(?<=123)abc"
  4841. data> xx123ab\=ph,allusedtext
  4842. Partial match: 123ab
  4843. <<<
  4844. However, the allusedtext modifier is not available for JIT matching,
  4845. because JIT matching does not record the first (or last) consulted
  4846. characters. For this reason, this information is not available via the
  4847. API. It is therefore not possible in general to obtain the exact number
  4848. of characters that must be retained in order to get the right match re-
  4849. sult. If you cannot retain the entire segment, you must find some
  4850. heuristic way of choosing.
  4851. If you know the approximate length of the matching substrings, you can
  4852. use that to decide how much text to retain. The only lookbehind infor-
  4853. mation that is currently available via the API is the length of the
  4854. longest individual lookbehind in a pattern, but this can be misleading
  4855. if there are nested lookbehinds. The value returned by calling
  4856. pcre2_pattern_info() with the PCRE2_INFO_MAXLOOKBEHIND option is the
  4857. maximum number of characters (not code units) that any individual look-
  4858. behind moves back when it is processed. A pattern such as
  4859. "(?<=(?<!b)a)" has a maximum lookbehind value of one, but inspects two
  4860. characters before its starting point.
  4861. In a non-UTF or a 32-bit case, moving back is just a subtraction, but
  4862. in UTF-8 or UTF-16 you have to count characters while moving back
  4863. through the code units.
  4864. PARTIAL MATCHING USING pcre2_dfa_match()
  4865. The DFA function moves along the subject string character by character,
  4866. without backtracking, searching for all possible matches simultane-
  4867. ously. If the end of the subject is reached before the end of the pat-
  4868. tern, there is the possibility of a partial match.
  4869. When PCRE2_PARTIAL_SOFT is set, PCRE2_ERROR_PARTIAL is returned only if
  4870. there have been no complete matches. Otherwise, the complete matches
  4871. are returned. If PCRE2_PARTIAL_HARD is set, a partial match takes
  4872. precedence over any complete matches. The portion of the string that
  4873. was matched when the longest partial match was found is set as the
  4874. first matching string.
  4875. Because the DFA function always searches for all possible matches, and
  4876. there is no difference between greedy and ungreedy repetition, its be-
  4877. haviour is different from the pcre2_match(). Consider the string "dog"
  4878. matched against this ungreedy pattern:
  4879. /dog(sbody)??/
  4880. Whereas the standard function stops as soon as it finds the complete
  4881. match for "dog", the DFA function also finds the partial match for
  4882. "dogsbody", and so returns that when PCRE2_PARTIAL_HARD is set.
  4883. MULTI-SEGMENT MATCHING WITH pcre2_dfa_match()
  4884. When a partial match has been found using the DFA matching function, it
  4885. is possible to continue the match by providing additional subject data
  4886. and calling the function again with the same compiled regular expres-
  4887. sion, this time setting the PCRE2_DFA_RESTART option. You must pass the
  4888. same working space as before, because this is where details of the pre-
  4889. vious partial match are stored. You can set the PCRE2_PARTIAL_SOFT or
  4890. PCRE2_PARTIAL_HARD options with PCRE2_DFA_RESTART to continue partial
  4891. matching over multiple segments. Here is an example using pcre2test:
  4892. re> /^\d?\d(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d\d$/
  4893. data> 23ja\=dfa,ps
  4894. Partial match: 23ja
  4895. data> n05\=dfa,dfa_restart
  4896. 0: n05
  4897. The first call has "23ja" as the subject, and requests partial match-
  4898. ing; the second call has "n05" as the subject for the continued
  4899. (restarted) match. Notice that when the match is complete, only the
  4900. last part is shown; PCRE2 does not retain the previously partially-
  4901. matched string. It is up to the calling program to do that if it needs
  4902. to. This means that, for an unanchored pattern, if a continued match
  4903. fails, it is not possible to try again at a new starting point. All
  4904. this facility is capable of doing is continuing with the previous match
  4905. attempt. For example, consider this pattern:
  4906. 1234|3789
  4907. If the first part of the subject is "ABC123", a partial match of the
  4908. first alternative is found at offset 3. There is no partial match for
  4909. the second alternative, because such a match does not start at the same
  4910. point in the subject string. Attempting to continue with the string
  4911. "7890" does not yield a match because only those alternatives that
  4912. match at one point in the subject are remembered. Depending on the ap-
  4913. plication, this may or may not be what you want.
  4914. If you do want to allow for starting again at the next character, one
  4915. way of doing it is to retain some or all of the segment and try a new
  4916. complete match, as described for pcre2_match() above. Another possibil-
  4917. ity is to work with two buffers. If a partial match at offset n in the
  4918. first buffer is followed by "no match" when PCRE2_DFA_RESTART is used
  4919. on the second buffer, you can then try a new match starting at offset
  4920. n+1 in the first buffer.
  4921. AUTHOR
  4922. Philip Hazel
  4923. Retired from University Computing Service
  4924. Cambridge, England.
  4925. REVISION
  4926. Last updated: 04 September 2019
  4927. Copyright (c) 1997-2019 University of Cambridge.
  4928. PCRE2 10.34 04 September 2019 PCRE2PARTIAL(3)
  4929. ------------------------------------------------------------------------------
  4930. PCRE2PATTERN(3) Library Functions Manual PCRE2PATTERN(3)
  4931. NAME
  4932. PCRE2 - Perl-compatible regular expressions (revised API)
  4933. PCRE2 REGULAR EXPRESSION DETAILS
  4934. The syntax and semantics of the regular expressions that are supported
  4935. by PCRE2 are described in detail below. There is a quick-reference syn-
  4936. tax summary in the pcre2syntax page. PCRE2 tries to match Perl syntax
  4937. and semantics as closely as it can. PCRE2 also supports some alterna-
  4938. tive regular expression syntax (which does not conflict with the Perl
  4939. syntax) in order to provide some compatibility with regular expressions
  4940. in Python, .NET, and Oniguruma.
  4941. Perl's regular expressions are described in its own documentation, and
  4942. regular expressions in general are covered in a number of books, some
  4943. of which have copious examples. Jeffrey Friedl's "Mastering Regular Ex-
  4944. pressions", published by O'Reilly, covers regular expressions in great
  4945. detail. This description of PCRE2's regular expressions is intended as
  4946. reference material.
  4947. This document discusses the regular expression patterns that are sup-
  4948. ported by PCRE2 when its main matching function, pcre2_match(), is
  4949. used. PCRE2 also has an alternative matching function,
  4950. pcre2_dfa_match(), which matches using a different algorithm that is
  4951. not Perl-compatible. Some of the features discussed below are not
  4952. available when DFA matching is used. The advantages and disadvantages
  4953. of the alternative function, and how it differs from the normal func-
  4954. tion, are discussed in the pcre2matching page.
  4955. SPECIAL START-OF-PATTERN ITEMS
  4956. A number of options that can be passed to pcre2_compile() can also be
  4957. set by special items at the start of a pattern. These are not Perl-com-
  4958. patible, but are provided to make these options accessible to pattern
  4959. writers who are not able to change the program that processes the pat-
  4960. tern. Any number of these items may appear, but they must all be to-
  4961. gether right at the start of the pattern string, and the letters must
  4962. be in upper case.
  4963. UTF support
  4964. In the 8-bit and 16-bit PCRE2 libraries, characters may be coded either
  4965. as single code units, or as multiple UTF-8 or UTF-16 code units. UTF-32
  4966. can be specified for the 32-bit library, in which case it constrains
  4967. the character values to valid Unicode code points. To process UTF
  4968. strings, PCRE2 must be built to include Unicode support (which is the
  4969. default). When using UTF strings you must either call the compiling
  4970. function with one or both of the PCRE2_UTF or PCRE2_MATCH_INVALID_UTF
  4971. options, or the pattern must start with the special sequence (*UTF),
  4972. which is equivalent to setting the relevant PCRE2_UTF. How setting a
  4973. UTF mode affects pattern matching is mentioned in several places below.
  4974. There is also a summary of features in the pcre2unicode page.
  4975. Some applications that allow their users to supply patterns may wish to
  4976. restrict them to non-UTF data for security reasons. If the
  4977. PCRE2_NEVER_UTF option is passed to pcre2_compile(), (*UTF) is not al-
  4978. lowed, and its appearance in a pattern causes an error.
  4979. Unicode property support
  4980. Another special sequence that may appear at the start of a pattern is
  4981. (*UCP). This has the same effect as setting the PCRE2_UCP option: it
  4982. causes sequences such as \d and \w to use Unicode properties to deter-
  4983. mine character types, instead of recognizing only characters with codes
  4984. less than 256 via a lookup table. If also causes upper/lower casing op-
  4985. erations to use Unicode properties for characters with code points
  4986. greater than 127, even when UTF is not set. These behaviours can be
  4987. changed within the pattern; see the section entitled "Internal Option
  4988. Setting" below.
  4989. Some applications that allow their users to supply patterns may wish to
  4990. restrict them for security reasons. If the PCRE2_NEVER_UCP option is
  4991. passed to pcre2_compile(), (*UCP) is not allowed, and its appearance in
  4992. a pattern causes an error.
  4993. Locking out empty string matching
  4994. Starting a pattern with (*NOTEMPTY) or (*NOTEMPTY_ATSTART) has the same
  4995. effect as passing the PCRE2_NOTEMPTY or PCRE2_NOTEMPTY_ATSTART option
  4996. to whichever matching function is subsequently called to match the pat-
  4997. tern. These options lock out the matching of empty strings, either en-
  4998. tirely, or only at the start of the subject.
  4999. Disabling auto-possessification
  5000. If a pattern starts with (*NO_AUTO_POSSESS), it has the same effect as
  5001. setting the PCRE2_NO_AUTO_POSSESS option. This stops PCRE2 from making
  5002. quantifiers possessive when what follows cannot match the repeated
  5003. item. For example, by default a+b is treated as a++b. For more details,
  5004. see the pcre2api documentation.
  5005. Disabling start-up optimizations
  5006. If a pattern starts with (*NO_START_OPT), it has the same effect as
  5007. setting the PCRE2_NO_START_OPTIMIZE option. This disables several opti-
  5008. mizations for quickly reaching "no match" results. For more details,
  5009. see the pcre2api documentation.
  5010. Disabling automatic anchoring
  5011. If a pattern starts with (*NO_DOTSTAR_ANCHOR), it has the same effect
  5012. as setting the PCRE2_NO_DOTSTAR_ANCHOR option. This disables optimiza-
  5013. tions that apply to patterns whose top-level branches all start with .*
  5014. (match any number of arbitrary characters). For more details, see the
  5015. pcre2api documentation.
  5016. Disabling JIT compilation
  5017. If a pattern that starts with (*NO_JIT) is successfully compiled, an
  5018. attempt by the application to apply the JIT optimization by calling
  5019. pcre2_jit_compile() is ignored.
  5020. Setting match resource limits
  5021. The pcre2_match() function contains a counter that is incremented every
  5022. time it goes round its main loop. The caller of pcre2_match() can set a
  5023. limit on this counter, which therefore limits the amount of computing
  5024. resource used for a match. The maximum depth of nested backtracking can
  5025. also be limited; this indirectly restricts the amount of heap memory
  5026. that is used, but there is also an explicit memory limit that can be
  5027. set.
  5028. These facilities are provided to catch runaway matches that are pro-
  5029. voked by patterns with huge matching trees. A common example is a pat-
  5030. tern with nested unlimited repeats applied to a long string that does
  5031. not match. When one of these limits is reached, pcre2_match() gives an
  5032. error return. The limits can also be set by items at the start of the
  5033. pattern of the form
  5034. (*LIMIT_HEAP=d)
  5035. (*LIMIT_MATCH=d)
  5036. (*LIMIT_DEPTH=d)
  5037. where d is any number of decimal digits. However, the value of the set-
  5038. ting must be less than the value set (or defaulted) by the caller of
  5039. pcre2_match() for it to have any effect. In other words, the pattern
  5040. writer can lower the limits set by the programmer, but not raise them.
  5041. If there is more than one setting of one of these limits, the lower
  5042. value is used. The heap limit is specified in kibibytes (units of 1024
  5043. bytes).
  5044. Prior to release 10.30, LIMIT_DEPTH was called LIMIT_RECURSION. This
  5045. name is still recognized for backwards compatibility.
  5046. The heap limit applies only when the pcre2_match() or pcre2_dfa_match()
  5047. interpreters are used for matching. It does not apply to JIT. The match
  5048. limit is used (but in a different way) when JIT is being used, or when
  5049. pcre2_dfa_match() is called, to limit computing resource usage by those
  5050. matching functions. The depth limit is ignored by JIT but is relevant
  5051. for DFA matching, which uses function recursion for recursions within
  5052. the pattern and for lookaround assertions and atomic groups. In this
  5053. case, the depth limit controls the depth of such recursion.
  5054. Newline conventions
  5055. PCRE2 supports six different conventions for indicating line breaks in
  5056. strings: a single CR (carriage return) character, a single LF (line-
  5057. feed) character, the two-character sequence CRLF, any of the three pre-
  5058. ceding, any Unicode newline sequence, or the NUL character (binary
  5059. zero). The pcre2api page has further discussion about newlines, and
  5060. shows how to set the newline convention when calling pcre2_compile().
  5061. It is also possible to specify a newline convention by starting a pat-
  5062. tern string with one of the following sequences:
  5063. (*CR) carriage return
  5064. (*LF) linefeed
  5065. (*CRLF) carriage return, followed by linefeed
  5066. (*ANYCRLF) any of the three above
  5067. (*ANY) all Unicode newline sequences
  5068. (*NUL) the NUL character (binary zero)
  5069. These override the default and the options given to the compiling func-
  5070. tion. For example, on a Unix system where LF is the default newline se-
  5071. quence, the pattern
  5072. (*CR)a.b
  5073. changes the convention to CR. That pattern matches "a\nb" because LF is
  5074. no longer a newline. If more than one of these settings is present, the
  5075. last one is used.
  5076. The newline convention affects where the circumflex and dollar asser-
  5077. tions are true. It also affects the interpretation of the dot metachar-
  5078. acter when PCRE2_DOTALL is not set, and the behaviour of \N when not
  5079. followed by an opening brace. However, it does not affect what the \R
  5080. escape sequence matches. By default, this is any Unicode newline se-
  5081. quence, for Perl compatibility. However, this can be changed; see the
  5082. next section and the description of \R in the section entitled "Newline
  5083. sequences" below. A change of \R setting can be combined with a change
  5084. of newline convention.
  5085. Specifying what \R matches
  5086. It is possible to restrict \R to match only CR, LF, or CRLF (instead of
  5087. the complete set of Unicode line endings) by setting the option
  5088. PCRE2_BSR_ANYCRLF at compile time. This effect can also be achieved by
  5089. starting a pattern with (*BSR_ANYCRLF). For completeness, (*BSR_UNI-
  5090. CODE) is also recognized, corresponding to PCRE2_BSR_UNICODE.
  5091. EBCDIC CHARACTER CODES
  5092. PCRE2 can be compiled to run in an environment that uses EBCDIC as its
  5093. character code instead of ASCII or Unicode (typically a mainframe sys-
  5094. tem). In the sections below, character code values are ASCII or Uni-
  5095. code; in an EBCDIC environment these characters may have different code
  5096. values, and there are no code points greater than 255.
  5097. CHARACTERS AND METACHARACTERS
  5098. A regular expression is a pattern that is matched against a subject
  5099. string from left to right. Most characters stand for themselves in a
  5100. pattern, and match the corresponding characters in the subject. As a
  5101. trivial example, the pattern
  5102. The quick brown fox
  5103. matches a portion of a subject string that is identical to itself. When
  5104. caseless matching is specified (the PCRE2_CASELESS option or (?i)
  5105. within the pattern), letters are matched independently of case. Note
  5106. that there are two ASCII characters, K and S, that, in addition to
  5107. their lower case ASCII equivalents, are case-equivalent with Unicode
  5108. U+212A (Kelvin sign) and U+017F (long S) respectively when either
  5109. PCRE2_UTF or PCRE2_UCP is set, unless the PCRE2_EXTRA_CASELESS_RESTRICT
  5110. option is in force (either passed to pcre2_compile() or set by (?r)
  5111. within the pattern).
  5112. The power of regular expressions comes from the ability to include wild
  5113. cards, character classes, alternatives, and repetitions in the pattern.
  5114. These are encoded in the pattern by the use of metacharacters, which do
  5115. not stand for themselves but instead are interpreted in some special
  5116. way.
  5117. There are two different sets of metacharacters: those that are recog-
  5118. nized anywhere in the pattern except within square brackets, and those
  5119. that are recognized within square brackets. Outside square brackets,
  5120. the metacharacters are as follows:
  5121. \ general escape character with several uses
  5122. ^ assert start of string (or line, in multiline mode)
  5123. $ assert end of string (or line, in multiline mode)
  5124. . match any character except newline (by default)
  5125. [ start character class definition
  5126. | start of alternative branch
  5127. ( start group or control verb
  5128. ) end group or control verb
  5129. * 0 or more quantifier
  5130. + 1 or more quantifier; also "possessive quantifier"
  5131. ? 0 or 1 quantifier; also quantifier minimizer
  5132. { potential start of min/max quantifier
  5133. Brace characters { and } are also used to enclose data for construc-
  5134. tions such as \g{2} or \k{name}. In almost all uses of braces, space
  5135. and/or horizontal tab characters that follow { or precede } are allowed
  5136. and are ignored. In the case of quantifiers, they may also appear be-
  5137. fore or after the comma. The exception to this is \u{...} which is an
  5138. ECMAScript compatibility feature that is recognized only when the
  5139. PCRE2_EXTRA_ALT_BSUX option is set. ECMAScript does not ignore such
  5140. white space; it causes the item to be interpreted as literal.
  5141. Part of a pattern that is in square brackets is called a "character
  5142. class". In a character class the only metacharacters are:
  5143. \ general escape character
  5144. ^ negate the class, but only if the first character
  5145. - indicates character range
  5146. [ POSIX character class (if followed by POSIX syntax)
  5147. ] terminates the character class
  5148. If a pattern is compiled with the PCRE2_EXTENDED option, most white
  5149. space in the pattern, other than in a character class, within a \Q...\E
  5150. sequence, or between a # outside a character class and the next new-
  5151. line, inclusive, are ignored. An escaping backslash can be used to in-
  5152. clude a white space or a # character as part of the pattern. If the
  5153. PCRE2_EXTENDED_MORE option is set, the same applies, but in addition
  5154. unescaped space and horizontal tab characters are ignored inside a
  5155. character class. Note: only these two characters are ignored, not the
  5156. full set of pattern white space characters that are ignored outside a
  5157. character class. Option settings can be changed within a pattern; see
  5158. the section entitled "Internal Option Setting" below.
  5159. The following sections describe the use of each of the metacharacters.
  5160. BACKSLASH
  5161. The backslash character has several uses. Firstly, if it is followed by
  5162. a character that is not a digit or a letter, it takes away any special
  5163. meaning that character may have. This use of backslash as an escape
  5164. character applies both inside and outside character classes.
  5165. For example, if you want to match a * character, you must write \* in
  5166. the pattern. This escaping action applies whether or not the following
  5167. character would otherwise be interpreted as a metacharacter, so it is
  5168. always safe to precede a non-alphanumeric with backslash to specify
  5169. that it stands for itself. In particular, if you want to match a back-
  5170. slash, you write \\.
  5171. Only ASCII digits and letters have any special meaning after a back-
  5172. slash. All other characters (in particular, those whose code points are
  5173. greater than 127) are treated as literals.
  5174. If you want to treat all characters in a sequence as literals, you can
  5175. do so by putting them between \Q and \E. Note that this includes white
  5176. space even when the PCRE2_EXTENDED option is set so that most other
  5177. white space is ignored. The behaviour is different from Perl in that $
  5178. and @ are handled as literals in \Q...\E sequences in PCRE2, whereas in
  5179. Perl, $ and @ cause variable interpolation. Also, Perl does "double-
  5180. quotish backslash interpolation" on any backslashes between \Q and \E
  5181. which, its documentation says, "may lead to confusing results". PCRE2
  5182. treats a backslash between \Q and \E just like any other character.
  5183. Note the following examples:
  5184. Pattern PCRE2 matches Perl matches
  5185. \Qabc$xyz\E abc$xyz abc followed by the
  5186. contents of $xyz
  5187. \Qabc\$xyz\E abc\$xyz abc\$xyz
  5188. \Qabc\E\$\Qxyz\E abc$xyz abc$xyz
  5189. \QA\B\E A\B A\B
  5190. \Q\\E \ \\E
  5191. The \Q...\E sequence is recognized both inside and outside character
  5192. classes. An isolated \E that is not preceded by \Q is ignored. If \Q
  5193. is not followed by \E later in the pattern, the literal interpretation
  5194. continues to the end of the pattern (that is, \E is assumed at the
  5195. end). If the isolated \Q is inside a character class, this causes an
  5196. error, because the character class is then not terminated by a closing
  5197. square bracket.
  5198. Non-printing characters
  5199. A second use of backslash provides a way of encoding non-printing char-
  5200. acters in patterns in a visible manner. There is no restriction on the
  5201. appearance of non-printing characters in a pattern, but when a pattern
  5202. is being prepared by text editing, it is often easier to use one of the
  5203. following escape sequences instead of the binary character it repre-
  5204. sents. In an ASCII or Unicode environment, these escapes are as fol-
  5205. lows:
  5206. \a alarm, that is, the BEL character (hex 07)
  5207. \cx "control-x", where x is a non-control ASCII character
  5208. \e escape (hex 1B)
  5209. \f form feed (hex 0C)
  5210. \n linefeed (hex 0A)
  5211. \r carriage return (hex 0D) (but see below)
  5212. \t tab (hex 09)
  5213. \0dd character with octal code 0dd
  5214. \ddd character with octal code ddd, or backreference
  5215. \o{ddd..} character with octal code ddd..
  5216. \xhh character with hex code hh
  5217. \x{hhh..} character with hex code hhh..
  5218. \N{U+hhh..} character with Unicode hex code point hhh..
  5219. By default, after \x that is not followed by {, from zero to two hexa-
  5220. decimal digits are read (letters can be in upper or lower case). Any
  5221. number of hexadecimal digits may appear between \x{ and }. If a charac-
  5222. ter other than a hexadecimal digit appears between \x{ and }, or if
  5223. there is no terminating }, an error occurs.
  5224. Characters whose code points are less than 256 can be defined by either
  5225. of the two syntaxes for \x or by an octal sequence. There is no differ-
  5226. ence in the way they are handled. For example, \xdc is exactly the same
  5227. as \x{dc} or \334. However, using the braced versions does make such
  5228. sequences easier to read.
  5229. Support is available for some ECMAScript (aka JavaScript) escape se-
  5230. quences via two compile-time options. If PCRE2_ALT_BSUX is set, the se-
  5231. quence \x followed by { is not recognized. Only if \x is followed by
  5232. two hexadecimal digits is it recognized as a character escape. Other-
  5233. wise it is interpreted as a literal "x" character. In this mode, sup-
  5234. port for code points greater than 256 is provided by \u, which must be
  5235. followed by four hexadecimal digits; otherwise it is interpreted as a
  5236. literal "u" character.
  5237. PCRE2_EXTRA_ALT_BSUX has the same effect as PCRE2_ALT_BSUX and, in ad-
  5238. dition, \u{hhh..} is recognized as the character specified by hexadeci-
  5239. mal code point. There may be any number of hexadecimal digits, but un-
  5240. like other places that also use curly brackets, spaces are not allowed
  5241. and would result in the string being interpreted as a literal. This
  5242. syntax is from ECMAScript 6.
  5243. The \N{U+hhh..} escape sequence is recognized only when PCRE2 is oper-
  5244. ating in UTF mode. Perl also uses \N{name} to specify characters by
  5245. Unicode name; PCRE2 does not support this. Note that when \N is not
  5246. followed by an opening brace (curly bracket) it has an entirely differ-
  5247. ent meaning, matching any character that is not a newline.
  5248. There are some legacy applications where the escape sequence \r is ex-
  5249. pected to match a newline. If the PCRE2_EXTRA_ESCAPED_CR_IS_LF option
  5250. is set, \r in a pattern is converted to \n so that it matches a LF
  5251. (linefeed) instead of a CR (carriage return) character.
  5252. An error occurs if \c is not followed by a character whose ASCII code
  5253. point is in the range 32 to 126. The precise effect of \cx is as fol-
  5254. lows: if x is a lower case letter, it is converted to upper case. Then
  5255. bit 6 of the character (hex 40) is inverted. Thus \cA to \cZ become hex
  5256. 01 to hex 1A (A is 41, Z is 5A), but \c{ becomes hex 3B ({ is 7B), and
  5257. \c; becomes hex 7B (; is 3B). If the code unit following \c has a code
  5258. point less than 32 or greater than 126, a compile-time error occurs.
  5259. When PCRE2 is compiled in EBCDIC mode, \N{U+hhh..} is not supported.
  5260. \a, \e, \f, \n, \r, and \t generate the appropriate EBCDIC code values.
  5261. The \c escape is processed as specified for Perl in the perlebcdic doc-
  5262. ument. The only characters that are allowed after \c are A-Z, a-z, or
  5263. one of @, [, \, ], ^, _, or ?. Any other character provokes a compile-
  5264. time error. The sequence \c@ encodes character code 0; after \c the
  5265. letters (in either case) encode characters 1-26 (hex 01 to hex 1A); [,
  5266. \, ], ^, and _ encode characters 27-31 (hex 1B to hex 1F), and \c? be-
  5267. comes either 255 (hex FF) or 95 (hex 5F).
  5268. Thus, apart from \c?, these escapes generate the same character code
  5269. values as they do in an ASCII environment, though the meanings of the
  5270. values mostly differ. For example, \cG always generates code value 7,
  5271. which is BEL in ASCII but DEL in EBCDIC.
  5272. The sequence \c? generates DEL (127, hex 7F) in an ASCII environment,
  5273. but because 127 is not a control character in EBCDIC, Perl makes it
  5274. generate the APC character. Unfortunately, there are several variants
  5275. of EBCDIC. In most of them the APC character has the value 255 (hex
  5276. FF), but in the one Perl calls POSIX-BC its value is 95 (hex 5F). If
  5277. certain other characters have POSIX-BC values, PCRE2 makes \c? generate
  5278. 95; otherwise it generates 255.
  5279. After \0 up to two further octal digits are read. If there are fewer
  5280. than two digits, just those that are present are used. Thus the se-
  5281. quence \0\x\015 specifies two binary zeros followed by a CR character
  5282. (code value 13). Make sure you supply two digits after the initial zero
  5283. if the pattern character that follows is itself an octal digit.
  5284. The escape \o must be followed by a sequence of octal digits, enclosed
  5285. in braces. An error occurs if this is not the case. This escape is a
  5286. recent addition to Perl; it provides way of specifying character code
  5287. points as octal numbers greater than 0777, and it also allows octal
  5288. numbers and backreferences to be unambiguously specified.
  5289. For greater clarity and unambiguity, it is best to avoid following \ by
  5290. a digit greater than zero. Instead, use \o{...} or \x{...} to specify
  5291. numerical character code points, and \g{...} to specify backreferences.
  5292. The following paragraphs describe the old, ambiguous syntax.
  5293. The handling of a backslash followed by a digit other than 0 is compli-
  5294. cated, and Perl has changed over time, causing PCRE2 also to change.
  5295. Outside a character class, PCRE2 reads the digit and any following dig-
  5296. its as a decimal number. If the number is less than 10, begins with the
  5297. digit 8 or 9, or if there are at least that many previous capture
  5298. groups in the expression, the entire sequence is taken as a backrefer-
  5299. ence. A description of how this works is given later, following the
  5300. discussion of parenthesized groups. Otherwise, up to three octal dig-
  5301. its are read to form a character code.
  5302. Inside a character class, PCRE2 handles \8 and \9 as the literal char-
  5303. acters "8" and "9", and otherwise reads up to three octal digits fol-
  5304. lowing the backslash, using them to generate a data character. Any sub-
  5305. sequent digits stand for themselves. For example, outside a character
  5306. class:
  5307. \040 is another way of writing an ASCII space
  5308. \40 is the same, provided there are fewer than 40
  5309. previous capture groups
  5310. \7 is always a backreference
  5311. \11 might be a backreference, or another way of
  5312. writing a tab
  5313. \011 is always a tab
  5314. \0113 is a tab followed by the character "3"
  5315. \113 might be a backreference, otherwise the
  5316. character with octal code 113
  5317. \377 might be a backreference, otherwise
  5318. the value 255 (decimal)
  5319. \81 is always a backreference
  5320. Note that octal values of 100 or greater that are specified using this
  5321. syntax must not be introduced by a leading zero, because no more than
  5322. three octal digits are ever read.
  5323. Constraints on character values
  5324. Characters that are specified using octal or hexadecimal numbers are
  5325. limited to certain values, as follows:
  5326. 8-bit non-UTF mode no greater than 0xff
  5327. 16-bit non-UTF mode no greater than 0xffff
  5328. 32-bit non-UTF mode no greater than 0xffffffff
  5329. All UTF modes no greater than 0x10ffff and a valid code point
  5330. Invalid Unicode code points are all those in the range 0xd800 to 0xdfff
  5331. (the so-called "surrogate" code points). The check for these can be
  5332. disabled by the caller of pcre2_compile() by setting the option
  5333. PCRE2_EXTRA_ALLOW_SURROGATE_ESCAPES. However, this is possible only in
  5334. UTF-8 and UTF-32 modes, because these values are not representable in
  5335. UTF-16.
  5336. Escape sequences in character classes
  5337. All the sequences that define a single character value can be used both
  5338. inside and outside character classes. In addition, inside a character
  5339. class, \b is interpreted as the backspace character (hex 08).
  5340. When not followed by an opening brace, \N is not allowed in a character
  5341. class. \B, \R, and \X are not special inside a character class. Like
  5342. other unrecognized alphabetic escape sequences, they cause an error.
  5343. Outside a character class, these sequences have different meanings.
  5344. Unsupported escape sequences
  5345. In Perl, the sequences \F, \l, \L, \u, and \U are recognized by its
  5346. string handler and used to modify the case of following characters. By
  5347. default, PCRE2 does not support these escape sequences in patterns.
  5348. However, if either of the PCRE2_ALT_BSUX or PCRE2_EXTRA_ALT_BSUX op-
  5349. tions is set, \U matches a "U" character, and \u can be used to define
  5350. a character by code point, as described above.
  5351. Absolute and relative backreferences
  5352. The sequence \g followed by a signed or unsigned number, optionally en-
  5353. closed in braces, is an absolute or relative backreference. A named
  5354. backreference can be coded as \g{name}. Backreferences are discussed
  5355. later, following the discussion of parenthesized groups.
  5356. Absolute and relative subroutine calls
  5357. For compatibility with Oniguruma, the non-Perl syntax \g followed by a
  5358. name or a number enclosed either in angle brackets or single quotes, is
  5359. an alternative syntax for referencing a capture group as a subroutine.
  5360. Details are discussed later. Note that \g{...} (Perl syntax) and
  5361. \g<...> (Oniguruma syntax) are not synonymous. The former is a backref-
  5362. erence; the latter is a subroutine call.
  5363. Generic character types
  5364. Another use of backslash is for specifying generic character types:
  5365. \d any decimal digit
  5366. \D any character that is not a decimal digit
  5367. \h any horizontal white space character
  5368. \H any character that is not a horizontal white space character
  5369. \N any character that is not a newline
  5370. \s any white space character
  5371. \S any character that is not a white space character
  5372. \v any vertical white space character
  5373. \V any character that is not a vertical white space character
  5374. \w any "word" character
  5375. \W any "non-word" character
  5376. The \N escape sequence has the same meaning as the "." metacharacter
  5377. when PCRE2_DOTALL is not set, but setting PCRE2_DOTALL does not change
  5378. the meaning of \N. Note that when \N is followed by an opening brace it
  5379. has a different meaning. See the section entitled "Non-printing charac-
  5380. ters" above for details. Perl also uses \N{name} to specify characters
  5381. by Unicode name; PCRE2 does not support this.
  5382. Each pair of lower and upper case escape sequences partitions the com-
  5383. plete set of characters into two disjoint sets. Any given character
  5384. matches one, and only one, of each pair. The sequences can appear both
  5385. inside and outside character classes. They each match one character of
  5386. the appropriate type. If the current matching point is at the end of
  5387. the subject string, all of them fail, because there is no character to
  5388. match.
  5389. The default \s characters are HT (9), LF (10), VT (11), FF (12), CR
  5390. (13), and space (32), which are defined as white space in the "C" lo-
  5391. cale. This list may vary if locale-specific matching is taking place.
  5392. For example, in some locales the "non-breaking space" character (\xA0)
  5393. is recognized as white space, and in others the VT character is not.
  5394. A "word" character is an underscore or any character that is a letter
  5395. or digit. By default, the definition of letters and digits is con-
  5396. trolled by PCRE2's low-valued character tables, and may vary if locale-
  5397. specific matching is taking place (see "Locale support" in the pcre2api
  5398. page). For example, in a French locale such as "fr_FR" in Unix-like
  5399. systems, or "french" in Windows, some character codes greater than 127
  5400. are used for accented letters, and these are then matched by \w. The
  5401. use of locales with Unicode is discouraged.
  5402. By default, characters whose code points are greater than 127 never
  5403. match \d, \s, or \w, and always match \D, \S, and \W, although this may
  5404. be different for characters in the range 128-255 when locale-specific
  5405. matching is happening. These escape sequences retain their original
  5406. meanings from before Unicode support was available, mainly for effi-
  5407. ciency reasons. If the PCRE2_UCP option is set, the behaviour is
  5408. changed so that Unicode properties are used to determine character
  5409. types, as follows:
  5410. \d any character that matches \p{Nd} (decimal digit)
  5411. \s any character that matches \p{Z} or \h or \v
  5412. \w any character that matches \p{L}, \p{N}, \p{Mn}, or \p{Pc}
  5413. The addition of \p{Mn} (non-spacing mark) and the replacement of an ex-
  5414. plicit test for underscore with a test for \p{Pc} (connector punctua-
  5415. tion) happened in PCRE2 release 10.43. This brings PCRE2 into line with
  5416. Perl.
  5417. The upper case escapes match the inverse sets of characters. Note that
  5418. \d matches only decimal digits, whereas \w matches any Unicode digit,
  5419. as well as other character categories. Note also that PCRE2_UCP affects
  5420. \b, and \B because they are defined in terms of \w and \W. Matching
  5421. these sequences is noticeably slower when PCRE2_UCP is set.
  5422. The effect of PCRE2_UCP on any one of these escape sequences can be
  5423. negated by the options PCRE2_EXTRA_ASCII_BSD, PCRE2_EXTRA_ASCII_BSS,
  5424. and PCRE2_EXTRA_ASCII_BSW, respectively. These options can be set and
  5425. reset within a pattern by means of an internal option setting (see be-
  5426. low).
  5427. The sequences \h, \H, \v, and \V, in contrast to the other sequences,
  5428. which match only ASCII characters by default, always match a specific
  5429. list of code points, whether or not PCRE2_UCP is set. The horizontal
  5430. space characters are:
  5431. U+0009 Horizontal tab (HT)
  5432. U+0020 Space
  5433. U+00A0 Non-break space
  5434. U+1680 Ogham space mark
  5435. U+180E Mongolian vowel separator
  5436. U+2000 En quad
  5437. U+2001 Em quad
  5438. U+2002 En space
  5439. U+2003 Em space
  5440. U+2004 Three-per-em space
  5441. U+2005 Four-per-em space
  5442. U+2006 Six-per-em space
  5443. U+2007 Figure space
  5444. U+2008 Punctuation space
  5445. U+2009 Thin space
  5446. U+200A Hair space
  5447. U+202F Narrow no-break space
  5448. U+205F Medium mathematical space
  5449. U+3000 Ideographic space
  5450. The vertical space characters are:
  5451. U+000A Linefeed (LF)
  5452. U+000B Vertical tab (VT)
  5453. U+000C Form feed (FF)
  5454. U+000D Carriage return (CR)
  5455. U+0085 Next line (NEL)
  5456. U+2028 Line separator
  5457. U+2029 Paragraph separator
  5458. In 8-bit, non-UTF-8 mode, only the characters with code points less
  5459. than 256 are relevant.
  5460. Newline sequences
  5461. Outside a character class, by default, the escape sequence \R matches
  5462. any Unicode newline sequence. In 8-bit non-UTF-8 mode \R is equivalent
  5463. to the following:
  5464. (?>\r\n|\n|\x0b|\f|\r|\x85)
  5465. This is an example of an "atomic group", details of which are given be-
  5466. low. This particular group matches either the two-character sequence
  5467. CR followed by LF, or one of the single characters LF (linefeed,
  5468. U+000A), VT (vertical tab, U+000B), FF (form feed, U+000C), CR (car-
  5469. riage return, U+000D), or NEL (next line, U+0085). Because this is an
  5470. atomic group, the two-character sequence is treated as a single unit
  5471. that cannot be split.
  5472. In other modes, two additional characters whose code points are greater
  5473. than 255 are added: LS (line separator, U+2028) and PS (paragraph sepa-
  5474. rator, U+2029). Unicode support is not needed for these characters to
  5475. be recognized.
  5476. It is possible to restrict \R to match only CR, LF, or CRLF (instead of
  5477. the complete set of Unicode line endings) by setting the option
  5478. PCRE2_BSR_ANYCRLF at compile time. (BSR is an abbreviation for "back-
  5479. slash R".) This can be made the default when PCRE2 is built; if this is
  5480. the case, the other behaviour can be requested via the PCRE2_BSR_UNI-
  5481. CODE option. It is also possible to specify these settings by starting
  5482. a pattern string with one of the following sequences:
  5483. (*BSR_ANYCRLF) CR, LF, or CRLF only
  5484. (*BSR_UNICODE) any Unicode newline sequence
  5485. These override the default and the options given to the compiling func-
  5486. tion. Note that these special settings, which are not Perl-compatible,
  5487. are recognized only at the very start of a pattern, and that they must
  5488. be in upper case. If more than one of them is present, the last one is
  5489. used. They can be combined with a change of newline convention; for ex-
  5490. ample, a pattern can start with:
  5491. (*ANY)(*BSR_ANYCRLF)
  5492. They can also be combined with the (*UTF) or (*UCP) special sequences.
  5493. Inside a character class, \R is treated as an unrecognized escape se-
  5494. quence, and causes an error.
  5495. Unicode character properties
  5496. When PCRE2 is built with Unicode support (the default), three addi-
  5497. tional escape sequences that match characters with specific properties
  5498. are available. They can be used in any mode, though in 8-bit and 16-bit
  5499. non-UTF modes these sequences are of course limited to testing charac-
  5500. ters whose code points are less than U+0100 and U+10000, respectively.
  5501. In 32-bit non-UTF mode, code points greater than 0x10ffff (the Unicode
  5502. limit) may be encountered. These are all treated as being in the Un-
  5503. known script and with an unassigned type.
  5504. Matching characters by Unicode property is not fast, because PCRE2 has
  5505. to do a multistage table lookup in order to find a character's prop-
  5506. erty. That is why the traditional escape sequences such as \d and \w do
  5507. not use Unicode properties in PCRE2 by default, though you can make
  5508. them do so by setting the PCRE2_UCP option or by starting the pattern
  5509. with (*UCP).
  5510. The extra escape sequences that provide property support are:
  5511. \p{xx} a character with the xx property
  5512. \P{xx} a character without the xx property
  5513. \X a Unicode extended grapheme cluster
  5514. The property names represented by xx above are not case-sensitive, and
  5515. in accordance with Unicode's "loose matching" rules, spaces, hyphens,
  5516. and underscores are ignored. There is support for Unicode script names,
  5517. Unicode general category properties, "Any", which matches any character
  5518. (including newline), Bidi_Class, a number of binary (yes/no) proper-
  5519. ties, and some special PCRE2 properties (described below). Certain
  5520. other Perl properties such as "InMusicalSymbols" are not supported by
  5521. PCRE2. Note that \P{Any} does not match any characters, so always
  5522. causes a match failure.
  5523. Script properties for \p and \P
  5524. There are three different syntax forms for matching a script. Each Uni-
  5525. code character has a basic script and, optionally, a list of other
  5526. scripts ("Script Extensions") with which it is commonly used. Using the
  5527. Adlam script as an example, \p{sc:Adlam} matches characters whose basic
  5528. script is Adlam, whereas \p{scx:Adlam} matches, in addition, characters
  5529. that have Adlam in their extensions list. The full names "script" and
  5530. "script extensions" for the property types are recognized, and a equals
  5531. sign is an alternative to the colon. If a script name is given without
  5532. a property type, for example, \p{Adlam}, it is treated as \p{scx:Ad-
  5533. lam}. Perl changed to this interpretation at release 5.26 and PCRE2
  5534. changed at release 10.40.
  5535. Unassigned characters (and in non-UTF 32-bit mode, characters with code
  5536. points greater than 0x10FFFF) are assigned the "Unknown" script. Others
  5537. that are not part of an identified script are lumped together as "Com-
  5538. mon". The current list of recognized script names and their 4-character
  5539. abbreviations can be obtained by running this command:
  5540. pcre2test -LS
  5541. The general category property for \p and \P
  5542. Each character has exactly one Unicode general category property, spec-
  5543. ified by a two-letter abbreviation. For compatibility with Perl, nega-
  5544. tion can be specified by including a circumflex between the opening
  5545. brace and the property name. For example, \p{^Lu} is the same as
  5546. \P{Lu}.
  5547. If only one letter is specified with \p or \P, it includes all the gen-
  5548. eral category properties that start with that letter. In this case, in
  5549. the absence of negation, the curly brackets in the escape sequence are
  5550. optional; these two examples have the same effect:
  5551. \p{L}
  5552. \pL
  5553. The following general category property codes are supported:
  5554. C Other
  5555. Cc Control
  5556. Cf Format
  5557. Cn Unassigned
  5558. Co Private use
  5559. Cs Surrogate
  5560. L Letter
  5561. Ll Lower case letter
  5562. Lm Modifier letter
  5563. Lo Other letter
  5564. Lt Title case letter
  5565. Lu Upper case letter
  5566. M Mark
  5567. Mc Spacing mark
  5568. Me Enclosing mark
  5569. Mn Non-spacing mark
  5570. N Number
  5571. Nd Decimal number
  5572. Nl Letter number
  5573. No Other number
  5574. P Punctuation
  5575. Pc Connector punctuation
  5576. Pd Dash punctuation
  5577. Pe Close punctuation
  5578. Pf Final punctuation
  5579. Pi Initial punctuation
  5580. Po Other punctuation
  5581. Ps Open punctuation
  5582. S Symbol
  5583. Sc Currency symbol
  5584. Sk Modifier symbol
  5585. Sm Mathematical symbol
  5586. So Other symbol
  5587. Z Separator
  5588. Zl Line separator
  5589. Zp Paragraph separator
  5590. Zs Space separator
  5591. The special property LC, which has the synonym L&, is also supported:
  5592. it matches a character that has the Lu, Ll, or Lt property, in other
  5593. words, a letter that is not classified as a modifier or "other".
  5594. The Cs (Surrogate) property applies only to characters whose code
  5595. points are in the range U+D800 to U+DFFF. These characters are no dif-
  5596. ferent to any other character when PCRE2 is not in UTF mode (using the
  5597. 16-bit or 32-bit library). However, they are not valid in Unicode
  5598. strings and so cannot be tested by PCRE2 in UTF mode, unless UTF valid-
  5599. ity checking has been turned off (see the discussion of
  5600. PCRE2_NO_UTF_CHECK in the pcre2api page).
  5601. The long synonyms for property names that Perl supports (such as
  5602. \p{Letter}) are not supported by PCRE2, nor is it permitted to prefix
  5603. any of these properties with "Is".
  5604. No character that is in the Unicode table has the Cn (unassigned) prop-
  5605. erty. Instead, this property is assumed for any code point that is not
  5606. in the Unicode table.
  5607. Specifying caseless matching does not affect these escape sequences.
  5608. For example, \p{Lu} always matches only upper case letters. This is
  5609. different from the behaviour of current versions of Perl.
  5610. Binary (yes/no) properties for \p and \P
  5611. Unicode defines a number of binary properties, that is, properties
  5612. whose only values are true or false. You can obtain a list of those
  5613. that are recognized by \p and \P, along with their abbreviations, by
  5614. running this command:
  5615. pcre2test -LP
  5616. The Bidi_Class property for \p and \P
  5617. \p{Bidi_Class:<class>} matches a character with the given class
  5618. \p{BC:<class>} matches a character with the given class
  5619. The recognized classes are:
  5620. AL Arabic letter
  5621. AN Arabic number
  5622. B paragraph separator
  5623. BN boundary neutral
  5624. CS common separator
  5625. EN European number
  5626. ES European separator
  5627. ET European terminator
  5628. FSI first strong isolate
  5629. L left-to-right
  5630. LRE left-to-right embedding
  5631. LRI left-to-right isolate
  5632. LRO left-to-right override
  5633. NSM non-spacing mark
  5634. ON other neutral
  5635. PDF pop directional format
  5636. PDI pop directional isolate
  5637. R right-to-left
  5638. RLE right-to-left embedding
  5639. RLI right-to-left isolate
  5640. RLO right-to-left override
  5641. S segment separator
  5642. WS which space
  5643. An equals sign may be used instead of a colon. The class names are
  5644. case-insensitive; only the short names listed above are recognized.
  5645. Extended grapheme clusters
  5646. The \X escape matches any number of Unicode characters that form an
  5647. "extended grapheme cluster", and treats the sequence as an atomic group
  5648. (see below). Unicode supports various kinds of composite character by
  5649. giving each character a grapheme breaking property, and having rules
  5650. that use these properties to define the boundaries of extended grapheme
  5651. clusters. The rules are defined in Unicode Standard Annex 29, "Unicode
  5652. Text Segmentation". Unicode 11.0.0 abandoned the use of some previous
  5653. properties that had been used for emojis. Instead it introduced vari-
  5654. ous emoji-specific properties. PCRE2 uses only the Extended Picto-
  5655. graphic property.
  5656. \X always matches at least one character. Then it decides whether to
  5657. add additional characters according to the following rules for ending a
  5658. cluster:
  5659. 1. End at the end of the subject string.
  5660. 2. Do not end between CR and LF; otherwise end after any control char-
  5661. acter.
  5662. 3. Do not break Hangul (a Korean script) syllable sequences. Hangul
  5663. characters are of five types: L, V, T, LV, and LVT. An L character may
  5664. be followed by an L, V, LV, or LVT character; an LV or V character may
  5665. be followed by a V or T character; an LVT or T character may be fol-
  5666. lowed only by a T character.
  5667. 4. Do not end before extending characters or spacing marks or the zero-
  5668. width joiner (ZWJ) character. Characters with the "mark" property al-
  5669. ways have the "extend" grapheme breaking property.
  5670. 5. Do not end after prepend characters.
  5671. 6. Do not end within emoji modifier sequences or emoji ZWJ (zero-width
  5672. joiner) sequences. An emoji ZWJ sequence consists of a character with
  5673. the Extended_Pictographic property, optionally followed by one or more
  5674. characters with the Extend property, followed by the ZWJ character,
  5675. followed by another Extended_Pictographic character.
  5676. 7. Do not break within emoji flag sequences. That is, do not break be-
  5677. tween regional indicator (RI) characters if there are an odd number of
  5678. RI characters before the break point.
  5679. 8. Otherwise, end the cluster.
  5680. PCRE2's additional properties
  5681. As well as the standard Unicode properties described above, PCRE2 sup-
  5682. ports four more that make it possible to convert traditional escape se-
  5683. quences such as \w and \s to use Unicode properties. PCRE2 uses these
  5684. non-standard, non-Perl properties internally when PCRE2_UCP is set.
  5685. However, they may also be used explicitly. These properties are:
  5686. Xan Any alphanumeric character
  5687. Xps Any POSIX space character
  5688. Xsp Any Perl space character
  5689. Xwd Any Perl "word" character
  5690. Xan matches characters that have either the L (letter) or the N (num-
  5691. ber) property. Xps matches the characters tab, linefeed, vertical tab,
  5692. form feed, or carriage return, and any other character that has the Z
  5693. (separator) property. Xsp is the same as Xps; in PCRE1 it used to ex-
  5694. clude vertical tab, for Perl compatibility, but Perl changed. Xwd
  5695. matches the same characters as Xan, plus those that match Mn (non-spac-
  5696. ing mark) or Pc (connector punctuation, which includes underscore).
  5697. There is another non-standard property, Xuc, which matches any charac-
  5698. ter that can be represented by a Universal Character Name in C++ and
  5699. other programming languages. These are the characters $, @, ` (grave
  5700. accent), and all characters with Unicode code points greater than or
  5701. equal to U+00A0, except for the surrogates U+D800 to U+DFFF. Note that
  5702. most base (ASCII) characters are excluded. (Universal Character Names
  5703. are of the form \uHHHH or \UHHHHHHHH where H is a hexadecimal digit.
  5704. Note that the Xuc property does not match these sequences but the char-
  5705. acters that they represent.)
  5706. Resetting the match start
  5707. In normal use, the escape sequence \K causes any previously matched
  5708. characters not to be included in the final matched sequence that is re-
  5709. turned. For example, the pattern:
  5710. foo\Kbar
  5711. matches "foobar", but reports that it has matched "bar". \K does not
  5712. interact with anchoring in any way. The pattern:
  5713. ^foo\Kbar
  5714. matches only when the subject begins with "foobar" (in single line
  5715. mode), though it again reports the matched string as "bar". This fea-
  5716. ture is similar to a lookbehind assertion (described below), but the
  5717. part of the pattern that precedes \K is not constrained to match a lim-
  5718. ited number of characters, as is required for a lookbehind assertion.
  5719. The use of \K does not interfere with the setting of captured sub-
  5720. strings. For example, when the pattern
  5721. (foo)\Kbar
  5722. matches "foobar", the first substring is still set to "foo".
  5723. From version 5.32.0 Perl forbids the use of \K in lookaround asser-
  5724. tions. From release 10.38 PCRE2 also forbids this by default. However,
  5725. the PCRE2_EXTRA_ALLOW_LOOKAROUND_BSK option can be used when calling
  5726. pcre2_compile() to re-enable the previous behaviour. When this option
  5727. is set, \K is acted upon when it occurs inside positive assertions, but
  5728. is ignored in negative assertions. Note that when a pattern such as
  5729. (?=ab\K) matches, the reported start of the match can be greater than
  5730. the end of the match. Using \K in a lookbehind assertion at the start
  5731. of a pattern can also lead to odd effects. For example, consider this
  5732. pattern:
  5733. (?<=\Kfoo)bar
  5734. If the subject is "foobar", a call to pcre2_match() with a starting
  5735. offset of 3 succeeds and reports the matching string as "foobar", that
  5736. is, the start of the reported match is earlier than where the match
  5737. started.
  5738. Simple assertions
  5739. The final use of backslash is for certain simple assertions. An asser-
  5740. tion specifies a condition that has to be met at a particular point in
  5741. a match, without consuming any characters from the subject string. The
  5742. use of groups for more complicated assertions is described below. The
  5743. backslashed assertions are:
  5744. \b matches at a word boundary
  5745. \B matches when not at a word boundary
  5746. \A matches at the start of the subject
  5747. \Z matches at the end of the subject
  5748. also matches before a newline at the end of the subject
  5749. \z matches only at the end of the subject
  5750. \G matches at the first matching position in the subject
  5751. Inside a character class, \b has a different meaning; it matches the
  5752. backspace character. If any other of these assertions appears in a
  5753. character class, an "invalid escape sequence" error is generated.
  5754. A word boundary is a position in the subject string where the current
  5755. character and the previous character do not both match \w or \W (i.e.
  5756. one matches \w and the other matches \W), or the start or end of the
  5757. string if the first or last character matches \w, respectively. When
  5758. PCRE2 is built with Unicode support, the meanings of \w and \W can be
  5759. changed by setting the PCRE2_UCP option. When this is done, it also af-
  5760. fects \b and \B. Neither PCRE2 nor Perl has a separate "start of word"
  5761. or "end of word" metasequence. However, whatever follows \b normally
  5762. determines which it is. For example, the fragment \ba matches "a" at
  5763. the start of a word.
  5764. The \A, \Z, and \z assertions differ from the traditional circumflex
  5765. and dollar (described in the next section) in that they only ever match
  5766. at the very start and end of the subject string, whatever options are
  5767. set. Thus, they are independent of multiline mode. These three asser-
  5768. tions are not affected by the PCRE2_NOTBOL or PCRE2_NOTEOL options,
  5769. which affect only the behaviour of the circumflex and dollar metachar-
  5770. acters. However, if the startoffset argument of pcre2_match() is non-
  5771. zero, indicating that matching is to start at a point other than the
  5772. beginning of the subject, \A can never match. The difference between
  5773. \Z and \z is that \Z matches before a newline at the end of the string
  5774. as well as at the very end, whereas \z matches only at the end.
  5775. The \G assertion is true only when the current matching position is at
  5776. the start point of the matching process, as specified by the startoff-
  5777. set argument of pcre2_match(). It differs from \A when the value of
  5778. startoffset is non-zero. By calling pcre2_match() multiple times with
  5779. appropriate arguments, you can mimic Perl's /g option, and it is in
  5780. this kind of implementation where \G can be useful.
  5781. Note, however, that PCRE2's implementation of \G, being true at the
  5782. starting character of the matching process, is subtly different from
  5783. Perl's, which defines it as true at the end of the previous match. In
  5784. Perl, these can be different when the previously matched string was
  5785. empty. Because PCRE2 does just one match at a time, it cannot reproduce
  5786. this behaviour.
  5787. If all the alternatives of a pattern begin with \G, the expression is
  5788. anchored to the starting match position, and the "anchored" flag is set
  5789. in the compiled regular expression.
  5790. CIRCUMFLEX AND DOLLAR
  5791. The circumflex and dollar metacharacters are zero-width assertions.
  5792. That is, they test for a particular condition being true without con-
  5793. suming any characters from the subject string. These two metacharacters
  5794. are concerned with matching the starts and ends of lines. If the new-
  5795. line convention is set so that only the two-character sequence CRLF is
  5796. recognized as a newline, isolated CR and LF characters are treated as
  5797. ordinary data characters, and are not recognized as newlines.
  5798. Outside a character class, in the default matching mode, the circumflex
  5799. character is an assertion that is true only if the current matching
  5800. point is at the start of the subject string. If the startoffset argu-
  5801. ment of pcre2_match() is non-zero, or if PCRE2_NOTBOL is set, circum-
  5802. flex can never match if the PCRE2_MULTILINE option is unset. Inside a
  5803. character class, circumflex has an entirely different meaning (see be-
  5804. low).
  5805. Circumflex need not be the first character of the pattern if a number
  5806. of alternatives are involved, but it should be the first thing in each
  5807. alternative in which it appears if the pattern is ever to match that
  5808. branch. If all possible alternatives start with a circumflex, that is,
  5809. if the pattern is constrained to match only at the start of the sub-
  5810. ject, it is said to be an "anchored" pattern. (There are also other
  5811. constructs that can cause a pattern to be anchored.)
  5812. The dollar character is an assertion that is true only if the current
  5813. matching point is at the end of the subject string, or immediately be-
  5814. fore a newline at the end of the string (by default), unless PCRE2_NO-
  5815. TEOL is set. Note, however, that it does not actually match the new-
  5816. line. Dollar need not be the last character of the pattern if a number
  5817. of alternatives are involved, but it should be the last item in any
  5818. branch in which it appears. Dollar has no special meaning in a charac-
  5819. ter class.
  5820. The meaning of dollar can be changed so that it matches only at the
  5821. very end of the string, by setting the PCRE2_DOLLAR_ENDONLY option at
  5822. compile time. This does not affect the \Z assertion.
  5823. The meanings of the circumflex and dollar metacharacters are changed if
  5824. the PCRE2_MULTILINE option is set. When this is the case, a dollar
  5825. character matches before any newlines in the string, as well as at the
  5826. very end, and a circumflex matches immediately after internal newlines
  5827. as well as at the start of the subject string. It does not match after
  5828. a newline that ends the string, for compatibility with Perl. However,
  5829. this can be changed by setting the PCRE2_ALT_CIRCUMFLEX option.
  5830. For example, the pattern /^abc$/ matches the subject string "def\nabc"
  5831. (where \n represents a newline) in multiline mode, but not otherwise.
  5832. Consequently, patterns that are anchored in single line mode because
  5833. all branches start with ^ are not anchored in multiline mode, and a
  5834. match for circumflex is possible when the startoffset argument of
  5835. pcre2_match() is non-zero. The PCRE2_DOLLAR_ENDONLY option is ignored
  5836. if PCRE2_MULTILINE is set.
  5837. When the newline convention (see "Newline conventions" below) recog-
  5838. nizes the two-character sequence CRLF as a newline, this is preferred,
  5839. even if the single characters CR and LF are also recognized as new-
  5840. lines. For example, if the newline convention is "any", a multiline
  5841. mode circumflex matches before "xyz" in the string "abc\r\nxyz" rather
  5842. than after CR, even though CR on its own is a valid newline. (It also
  5843. matches at the very start of the string, of course.)
  5844. Note that the sequences \A, \Z, and \z can be used to match the start
  5845. and end of the subject in both modes, and if all branches of a pattern
  5846. start with \A it is always anchored, whether or not PCRE2_MULTILINE is
  5847. set.
  5848. FULL STOP (PERIOD, DOT) AND \N
  5849. Outside a character class, a dot in the pattern matches any one charac-
  5850. ter in the subject string except (by default) a character that signi-
  5851. fies the end of a line. One or more characters may be specified as line
  5852. terminators (see "Newline conventions" above).
  5853. Dot never matches a single line-ending character. When the two-charac-
  5854. ter sequence CRLF is the only line ending, dot does not match CR if it
  5855. is immediately followed by LF, but otherwise it matches all characters
  5856. (including isolated CRs and LFs). When ANYCRLF is selected for line
  5857. endings, no occurrences of CR of LF match dot. When all Unicode line
  5858. endings are being recognized, dot does not match CR or LF or any of the
  5859. other line ending characters.
  5860. The behaviour of dot with regard to newlines can be changed. If the
  5861. PCRE2_DOTALL option is set, a dot matches any one character, without
  5862. exception. If the two-character sequence CRLF is present in the sub-
  5863. ject string, it takes two dots to match it.
  5864. The handling of dot is entirely independent of the handling of circum-
  5865. flex and dollar, the only relationship being that they both involve
  5866. newlines. Dot has no special meaning in a character class.
  5867. The escape sequence \N when not followed by an opening brace behaves
  5868. like a dot, except that it is not affected by the PCRE2_DOTALL option.
  5869. In other words, it matches any character except one that signifies the
  5870. end of a line.
  5871. When \N is followed by an opening brace it has a different meaning. See
  5872. the section entitled "Non-printing characters" above for details. Perl
  5873. also uses \N{name} to specify characters by Unicode name; PCRE2 does
  5874. not support this.
  5875. MATCHING A SINGLE CODE UNIT
  5876. Outside a character class, the escape sequence \C matches any one code
  5877. unit, whether or not a UTF mode is set. In the 8-bit library, one code
  5878. unit is one byte; in the 16-bit library it is a 16-bit unit; in the
  5879. 32-bit library it is a 32-bit unit. Unlike a dot, \C always matches
  5880. line-ending characters. The feature is provided in Perl in order to
  5881. match individual bytes in UTF-8 mode, but it is unclear how it can use-
  5882. fully be used.
  5883. Because \C breaks up characters into individual code units, matching
  5884. one unit with \C in UTF-8 or UTF-16 mode means that the rest of the
  5885. string may start with a malformed UTF character. This has undefined re-
  5886. sults, because PCRE2 assumes that it is matching character by character
  5887. in a valid UTF string (by default it checks the subject string's valid-
  5888. ity at the start of processing unless the PCRE2_NO_UTF_CHECK or
  5889. PCRE2_MATCH_INVALID_UTF option is used).
  5890. An application can lock out the use of \C by setting the
  5891. PCRE2_NEVER_BACKSLASH_C option when compiling a pattern. It is also
  5892. possible to build PCRE2 with the use of \C permanently disabled.
  5893. PCRE2 does not allow \C to appear in lookbehind assertions (described
  5894. below) in UTF-8 or UTF-16 modes, because this would make it impossible
  5895. to calculate the length of the lookbehind. Neither the alternative
  5896. matching function pcre2_dfa_match() nor the JIT optimizer support \C in
  5897. these UTF modes. The former gives a match-time error; the latter fails
  5898. to optimize and so the match is always run using the interpreter.
  5899. In the 32-bit library, however, \C is always supported (when not ex-
  5900. plicitly locked out) because it always matches a single code unit,
  5901. whether or not UTF-32 is specified.
  5902. In general, the \C escape sequence is best avoided. However, one way of
  5903. using it that avoids the problem of malformed UTF-8 or UTF-16 charac-
  5904. ters is to use a lookahead to check the length of the next character,
  5905. as in this pattern, which could be used with a UTF-8 string (ignore
  5906. white space and line breaks):
  5907. (?| (?=[\x00-\x7f])(\C) |
  5908. (?=[\x80-\x{7ff}])(\C)(\C) |
  5909. (?=[\x{800}-\x{ffff}])(\C)(\C)(\C) |
  5910. (?=[\x{10000}-\x{1fffff}])(\C)(\C)(\C)(\C))
  5911. In this example, a group that starts with (?| resets the capturing
  5912. parentheses numbers in each alternative (see "Duplicate Group Numbers"
  5913. below). The assertions at the start of each branch check the next UTF-8
  5914. character for values whose encoding uses 1, 2, 3, or 4 bytes, respec-
  5915. tively. The character's individual bytes are then captured by the ap-
  5916. propriate number of \C groups.
  5917. SQUARE BRACKETS AND CHARACTER CLASSES
  5918. An opening square bracket introduces a character class, terminated by a
  5919. closing square bracket. A closing square bracket on its own is not spe-
  5920. cial by default. If a closing square bracket is required as a member
  5921. of the class, it should be the first data character in the class (after
  5922. an initial circumflex, if present) or escaped with a backslash. This
  5923. means that, by default, an empty class cannot be defined. However, if
  5924. the PCRE2_ALLOW_EMPTY_CLASS option is set, a closing square bracket at
  5925. the start does end the (empty) class.
  5926. A character class matches a single character in the subject. A matched
  5927. character must be in the set of characters defined by the class, unless
  5928. the first character in the class definition is a circumflex, in which
  5929. case the subject character must not be in the set defined by the class.
  5930. If a circumflex is actually required as a member of the class, ensure
  5931. it is not the first character, or escape it with a backslash.
  5932. For example, the character class [aeiou] matches any lower case vowel,
  5933. while [^aeiou] matches any character that is not a lower case vowel.
  5934. Note that a circumflex is just a convenient notation for specifying the
  5935. characters that are in the class by enumerating those that are not. A
  5936. class that starts with a circumflex is not an assertion; it still con-
  5937. sumes a character from the subject string, and therefore it fails if
  5938. the current pointer is at the end of the string.
  5939. Characters in a class may be specified by their code points using \o,
  5940. \x, or \N{U+hh..} in the usual way. When caseless matching is set, any
  5941. letters in a class represent both their upper case and lower case ver-
  5942. sions, so for example, a caseless [aeiou] matches "A" as well as "a",
  5943. and a caseless [^aeiou] does not match "A", whereas a caseful version
  5944. would. Note that there are two ASCII characters, K and S, that, in ad-
  5945. dition to their lower case ASCII equivalents, are case-equivalent with
  5946. Unicode U+212A (Kelvin sign) and U+017F (long S) respectively when ei-
  5947. ther PCRE2_UTF or PCRE2_UCP is set.
  5948. Characters that might indicate line breaks are never treated in any
  5949. special way when matching character classes, whatever line-ending se-
  5950. quence is in use, and whatever setting of the PCRE2_DOTALL and
  5951. PCRE2_MULTILINE options is used. A class such as [^a] always matches
  5952. one of these characters.
  5953. The generic character type escape sequences \d, \D, \h, \H, \p, \P, \s,
  5954. \S, \v, \V, \w, and \W may appear in a character class, and add the
  5955. characters that they match to the class. For example, [\dABCDEF]
  5956. matches any hexadecimal digit. In UTF modes, the PCRE2_UCP option af-
  5957. fects the meanings of \d, \s, \w and their upper case partners, just as
  5958. it does when they appear outside a character class, as described in the
  5959. section entitled "Generic character types" above. The escape sequence
  5960. \b has a different meaning inside a character class; it matches the
  5961. backspace character. The sequences \B, \R, and \X are not special in-
  5962. side a character class. Like any other unrecognized escape sequences,
  5963. they cause an error. The same is true for \N when not followed by an
  5964. opening brace.
  5965. The minus (hyphen) character can be used to specify a range of charac-
  5966. ters in a character class. For example, [d-m] matches any letter be-
  5967. tween d and m, inclusive. If a minus character is required in a class,
  5968. it must be escaped with a backslash or appear in a position where it
  5969. cannot be interpreted as indicating a range, typically as the first or
  5970. last character in the class, or immediately after a range. For example,
  5971. [b-d-z] matches letters in the range b to d, a hyphen character, or z.
  5972. Perl treats a hyphen as a literal if it appears before or after a POSIX
  5973. class (see below) or before or after a character type escape such as \d
  5974. or \H. However, unless the hyphen is the last character in the class,
  5975. Perl outputs a warning in its warning mode, as this is most likely a
  5976. user error. As PCRE2 has no facility for warning, an error is given in
  5977. these cases.
  5978. It is not possible to have the literal character "]" as the end charac-
  5979. ter of a range. A pattern such as [W-]46] is interpreted as a class of
  5980. two characters ("W" and "-") followed by a literal string "46]", so it
  5981. would match "W46]" or "-46]". However, if the "]" is escaped with a
  5982. backslash it is interpreted as the end of range, so [W-\]46] is inter-
  5983. preted as a class containing a range followed by two other characters.
  5984. The octal or hexadecimal representation of "]" can also be used to end
  5985. a range.
  5986. Ranges normally include all code points between the start and end char-
  5987. acters, inclusive. They can also be used for code points specified nu-
  5988. merically, for example [\000-\037]. Ranges can include any characters
  5989. that are valid for the current mode. In any UTF mode, the so-called
  5990. "surrogate" characters (those whose code points lie between 0xd800 and
  5991. 0xdfff inclusive) may not be specified explicitly by default (the
  5992. PCRE2_EXTRA_ALLOW_SURROGATE_ESCAPES option disables this check). How-
  5993. ever, ranges such as [\x{d7ff}-\x{e000}], which include the surrogates,
  5994. are always permitted.
  5995. There is a special case in EBCDIC environments for ranges whose end
  5996. points are both specified as literal letters in the same case. For com-
  5997. patibility with Perl, EBCDIC code points within the range that are not
  5998. letters are omitted. For example, [h-k] matches only four characters,
  5999. even though the codes for h and k are 0x88 and 0x92, a range of 11 code
  6000. points. However, if the range is specified numerically, for example,
  6001. [\x88-\x92] or [h-\x92], all code points are included.
  6002. If a range that includes letters is used when caseless matching is set,
  6003. it matches the letters in either case. For example, [W-c] is equivalent
  6004. to [][\\^_`wxyzabc], matched caselessly, and in a non-UTF mode, if
  6005. character tables for a French locale are in use, [\xc8-\xcb] matches
  6006. accented E characters in both cases.
  6007. A circumflex can conveniently be used with the upper case character
  6008. types to specify a more restricted set of characters than the matching
  6009. lower case type. For example, the class [^\W_] matches any letter or
  6010. digit, but not underscore, whereas [\w] includes underscore. A positive
  6011. character class should be read as "something OR something OR ..." and a
  6012. negative class as "NOT something AND NOT something AND NOT ...".
  6013. The only metacharacters that are recognized in character classes are
  6014. backslash, hyphen (only where it can be interpreted as specifying a
  6015. range), circumflex (only at the start), opening square bracket (only
  6016. when it can be interpreted as introducing a POSIX class name, or for a
  6017. special compatibility feature - see the next two sections), and the
  6018. terminating closing square bracket. However, escaping other non-al-
  6019. phanumeric characters does no harm.
  6020. POSIX CHARACTER CLASSES
  6021. Perl supports the POSIX notation for character classes. This uses names
  6022. enclosed by [: and :] within the enclosing square brackets. PCRE2 also
  6023. supports this notation. For example,
  6024. [01[:alpha:]%]
  6025. matches "0", "1", any alphabetic character, or "%". The supported class
  6026. names are:
  6027. alnum letters and digits
  6028. alpha letters
  6029. ascii character codes 0 - 127
  6030. blank space or tab only
  6031. cntrl control characters
  6032. digit decimal digits (same as \d)
  6033. graph printing characters, excluding space
  6034. lower lower case letters
  6035. print printing characters, including space
  6036. punct printing characters, excluding letters and digits and space
  6037. space white space (the same as \s from PCRE2 8.34)
  6038. upper upper case letters
  6039. word "word" characters (same as \w)
  6040. xdigit hexadecimal digits
  6041. The default "space" characters are HT (9), LF (10), VT (11), FF (12),
  6042. CR (13), and space (32). If locale-specific matching is taking place,
  6043. the list of space characters may be different; there may be fewer or
  6044. more of them. "Space" and \s match the same set of characters, as do
  6045. "word" and \w.
  6046. The name "word" is a Perl extension, and "blank" is a GNU extension
  6047. from Perl 5.8. Another Perl extension is negation, which is indicated
  6048. by a ^ character after the colon. For example,
  6049. [12[:^digit:]]
  6050. matches "1", "2", or any non-digit. PCRE2 (and Perl) also recognize the
  6051. POSIX syntax [.ch.] and [=ch=] where "ch" is a "collating element", but
  6052. these are not supported, and an error is given if they are encountered.
  6053. By default, characters with values greater than 127 do not match any of
  6054. the POSIX character classes, although this may be different for charac-
  6055. ters in the range 128-255 when locale-specific matching is happening.
  6056. However, in UCP mode, unless certain options are set (see below), some
  6057. of the classes are changed so that Unicode character properties are
  6058. used. This is achieved by replacing POSIX classes with other sequences,
  6059. as follows:
  6060. [:alnum:] becomes \p{Xan}
  6061. [:alpha:] becomes \p{L}
  6062. [:blank:] becomes \h
  6063. [:cntrl:] becomes \p{Cc}
  6064. [:digit:] becomes \p{Nd}
  6065. [:lower:] becomes \p{Ll}
  6066. [:space:] becomes \p{Xps}
  6067. [:upper:] becomes \p{Lu}
  6068. [:word:] becomes \p{Xwd}
  6069. Negated versions, such as [:^alpha:] use \P instead of \p. Four other
  6070. POSIX classes are handled specially in UCP mode:
  6071. [:graph:] This matches characters that have glyphs that mark the page
  6072. when printed. In Unicode property terms, it matches all char-
  6073. acters with the L, M, N, P, S, or Cf properties, except for:
  6074. U+061C Arabic Letter Mark
  6075. U+180E Mongolian Vowel Separator
  6076. U+2066 - U+2069 Various "isolate"s
  6077. [:print:] This matches the same characters as [:graph:] plus space
  6078. characters that are not controls, that is, characters with
  6079. the Zs property.
  6080. [:punct:] This matches all characters that have the Unicode P (punctua-
  6081. tion) property, plus those characters with code points less
  6082. than 256 that have the S (Symbol) property.
  6083. [:xdigit:]
  6084. In addition to the ASCII hexadecimal digits, this also
  6085. matches the "fullwidth" versions of those characters, whose
  6086. Unicode code points start at U+FF10. This is a change that
  6087. was made in PCRE release 10.43 for Perl compatibility.
  6088. The other POSIX classes are unchanged by PCRE2_UCP, and match only
  6089. characters with code points less than 256.
  6090. There are two options that can be used to restrict the POSIX classes to
  6091. ASCII characters when PCRE2_UCP is set. The option PCRE2_EX-
  6092. TRA_ASCII_DIGIT affects just [:digit:] and [:xdigit:]. Within a pat-
  6093. tern, this can be set and unset by (?aT) and (?-aT). The PCRE2_EX-
  6094. TRA_ASCII_POSIX option disables UCP processing for all POSIX classes,
  6095. including [:digit:] and [:xdigit:]. Within a pattern, (?aP) and (?-aP)
  6096. set and unset both these options for consistency.
  6097. COMPATIBILITY FEATURE FOR WORD BOUNDARIES
  6098. In the POSIX.2 compliant library that was included in 4.4BSD Unix, the
  6099. ugly syntax [[:<:]] and [[:>:]] is used for matching "start of word"
  6100. and "end of word". PCRE2 treats these items as follows:
  6101. [[:<:]] is converted to \b(?=\w)
  6102. [[:>:]] is converted to \b(?<=\w)
  6103. Only these exact character sequences are recognized. A sequence such as
  6104. [a[:<:]b] provokes error for an unrecognized POSIX class name. This
  6105. support is not compatible with Perl. It is provided to help migrations
  6106. from other environments, and is best not used in any new patterns. Note
  6107. that \b matches at the start and the end of a word (see "Simple asser-
  6108. tions" above), and in a Perl-style pattern the preceding or following
  6109. character normally shows which is wanted, without the need for the as-
  6110. sertions that are used above in order to give exactly the POSIX behav-
  6111. iour. Note also that the PCRE2_UCP option changes the meaning of \w
  6112. (and therefore \b) by default, so it also affects these POSIX se-
  6113. quences.
  6114. VERTICAL BAR
  6115. Vertical bar characters are used to separate alternative patterns. For
  6116. example, the pattern
  6117. gilbert|sullivan
  6118. matches either "gilbert" or "sullivan". Any number of alternatives may
  6119. appear, and an empty alternative is permitted (matching the empty
  6120. string). The matching process tries each alternative in turn, from left
  6121. to right, and the first one that succeeds is used. If the alternatives
  6122. are within a group (defined below), "succeeds" means matching the rest
  6123. of the main pattern as well as the alternative in the group.
  6124. INTERNAL OPTION SETTING
  6125. The settings of several options can be changed within a pattern by a
  6126. sequence of letters enclosed between "(?" and ")". The following are
  6127. Perl-compatible, and are described in detail in the pcre2api documenta-
  6128. tion. The option letters are:
  6129. i for PCRE2_CASELESS
  6130. m for PCRE2_MULTILINE
  6131. n for PCRE2_NO_AUTO_CAPTURE
  6132. s for PCRE2_DOTALL
  6133. x for PCRE2_EXTENDED
  6134. xx for PCRE2_EXTENDED_MORE
  6135. For example, (?im) sets caseless, multiline matching. It is also possi-
  6136. ble to unset these options by preceding the relevant letters with a hy-
  6137. phen, for example (?-im). The two "extended" options are not indepen-
  6138. dent; unsetting either one cancels the effects of both of them.
  6139. A combined setting and unsetting such as (?im-sx), which sets
  6140. PCRE2_CASELESS and PCRE2_MULTILINE while unsetting PCRE2_DOTALL and
  6141. PCRE2_EXTENDED, is also permitted. Only one hyphen may appear in the
  6142. options string. If a letter appears both before and after the hyphen,
  6143. the option is unset. An empty options setting "(?)" is allowed. Need-
  6144. less to say, it has no effect.
  6145. If the first character following (? is a circumflex, it causes all of
  6146. the above options to be unset. Letters may follow the circumflex to
  6147. cause some options to be re-instated, but a hyphen may not appear.
  6148. Some PCRE2-specific options can be changed by the same mechanism using
  6149. these pairs or individual letters:
  6150. aD for PCRE2_EXTRA_ASCII_BSD
  6151. aS for PCRE2_EXTRA_ASCII_BSS
  6152. aW for PCRE2_EXTRA_ASCII_BSW
  6153. aP for PCRE2_EXTRA_ASCII_POSIX and PCRE2_EXTRA_ASCII_DIGIT
  6154. aT for PCRE2_EXTRA_ASCII_DIGIT
  6155. r for PCRE2_EXTRA_CASELESS_RESTRICT
  6156. J for PCRE2_DUPNAMES
  6157. U for PCRE2_UNGREEDY
  6158. However, except for 'r', these are not unset by (?^), which is equiva-
  6159. lent to (?-imnrsx). If 'a' is not followed by any of the upper case
  6160. letters shown above, it sets (or unsets) all the ASCII options.
  6161. PCRE2_EXTRA_ASCII_DIGIT has no additional effect when PCRE2_EX-
  6162. TRA_ASCII_POSIX is set, but including it in (?aP) means that (?-aP)
  6163. suppresses all ASCII restrictions for POSIX classes.
  6164. When one of these option changes occurs at top level (that is, not in-
  6165. side group parentheses), the change applies until a subsequent change,
  6166. or the end of the pattern. An option change within a group (see below
  6167. for a description of groups) affects only that part of the group that
  6168. follows it. At the end of the group these options are reset to the
  6169. state they were before the group. For example,
  6170. (a(?i)b)c
  6171. matches abc and aBc and no other strings (assuming PCRE2_CASELESS is
  6172. not set externally). Any changes made in one alternative do carry on
  6173. into subsequent branches within the same group. For example,
  6174. (a(?i)b|c)
  6175. matches "ab", "aB", "c", and "C", even though when matching "C" the
  6176. first branch is abandoned before the option setting. This is because
  6177. the effects of option settings happen at compile time. There would be
  6178. some very weird behaviour otherwise.
  6179. As a convenient shorthand, if any option settings are required at the
  6180. start of a non-capturing group (see the next section), the option let-
  6181. ters may appear between the "?" and the ":". Thus the two patterns
  6182. (?i:saturday|sunday)
  6183. (?:(?i)saturday|sunday)
  6184. match exactly the same set of strings.
  6185. Note: There are other PCRE2-specific options, applying to the whole
  6186. pattern, which can be set by the application when the compiling func-
  6187. tion is called. In addition, the pattern can contain special leading
  6188. sequences such as (*CRLF) to override what the application has set or
  6189. what has been defaulted. Details are given in the section entitled
  6190. "Newline sequences" above. There are also the (*UTF) and (*UCP) leading
  6191. sequences that can be used to set UTF and Unicode property modes; they
  6192. are equivalent to setting the PCRE2_UTF and PCRE2_UCP options, respec-
  6193. tively. However, the application can set the PCRE2_NEVER_UTF or
  6194. PCRE2_NEVER_UCP options, which lock out the use of the (*UTF) and
  6195. (*UCP) sequences.
  6196. GROUPS
  6197. Groups are delimited by parentheses (round brackets), which can be
  6198. nested. Turning part of a pattern into a group does two things:
  6199. 1. It localizes a set of alternatives. For example, the pattern
  6200. cat(aract|erpillar|)
  6201. matches "cataract", "caterpillar", or "cat". Without the parentheses,
  6202. it would match "cataract", "erpillar" or an empty string.
  6203. 2. It creates a "capture group". This means that, when the whole pat-
  6204. tern matches, the portion of the subject string that matched the group
  6205. is passed back to the caller, separately from the portion that matched
  6206. the whole pattern. (This applies only to the traditional matching
  6207. function; the DFA matching function does not support capturing.)
  6208. Opening parentheses are counted from left to right (starting from 1) to
  6209. obtain numbers for capture groups. For example, if the string "the red
  6210. king" is matched against the pattern
  6211. the ((red|white) (king|queen))
  6212. the captured substrings are "red king", "red", and "king", and are num-
  6213. bered 1, 2, and 3, respectively.
  6214. The fact that plain parentheses fulfil two functions is not always
  6215. helpful. There are often times when grouping is required without cap-
  6216. turing. If an opening parenthesis is followed by a question mark and a
  6217. colon, the group does not do any capturing, and is not counted when
  6218. computing the number of any subsequent capture groups. For example, if
  6219. the string "the white queen" is matched against the pattern
  6220. the ((?:red|white) (king|queen))
  6221. the captured substrings are "white queen" and "queen", and are numbered
  6222. 1 and 2. The maximum number of capture groups is 65535.
  6223. As a convenient shorthand, if any option settings are required at the
  6224. start of a non-capturing group, the option letters may appear between
  6225. the "?" and the ":". Thus the two patterns
  6226. (?i:saturday|sunday)
  6227. (?:(?i)saturday|sunday)
  6228. match exactly the same set of strings. Because alternative branches are
  6229. tried from left to right, and options are not reset until the end of
  6230. the group is reached, an option setting in one branch does affect sub-
  6231. sequent branches, so the above patterns match "SUNDAY" as well as "Sat-
  6232. urday".
  6233. DUPLICATE GROUP NUMBERS
  6234. Perl 5.10 introduced a feature whereby each alternative in a group uses
  6235. the same numbers for its capturing parentheses. Such a group starts
  6236. with (?| and is itself a non-capturing group. For example, consider
  6237. this pattern:
  6238. (?|(Sat)ur|(Sun))day
  6239. Because the two alternatives are inside a (?| group, both sets of cap-
  6240. turing parentheses are numbered one. Thus, when the pattern matches,
  6241. you can look at captured substring number one, whichever alternative
  6242. matched. This construct is useful when you want to capture part, but
  6243. not all, of one of a number of alternatives. Inside a (?| group, paren-
  6244. theses are numbered as usual, but the number is reset at the start of
  6245. each branch. The numbers of any capturing parentheses that follow the
  6246. whole group start after the highest number used in any branch. The fol-
  6247. lowing example is taken from the Perl documentation. The numbers under-
  6248. neath show in which buffer the captured content will be stored.
  6249. # before ---------------branch-reset----------- after
  6250. / ( a ) (?| x ( y ) z | (p (q) r) | (t) u (v) ) ( z ) /x
  6251. # 1 2 2 3 2 3 4
  6252. A backreference to a capture group uses the most recent value that is
  6253. set for the group. The following pattern matches "abcabc" or "defdef":
  6254. /(?|(abc)|(def))\1/
  6255. In contrast, a subroutine call to a capture group always refers to the
  6256. first one in the pattern with the given number. The following pattern
  6257. matches "abcabc" or "defabc":
  6258. /(?|(abc)|(def))(?1)/
  6259. A relative reference such as (?-1) is no different: it is just a conve-
  6260. nient way of computing an absolute group number.
  6261. If a condition test for a group's having matched refers to a non-unique
  6262. number, the test is true if any group with that number has matched.
  6263. An alternative approach to using this "branch reset" feature is to use
  6264. duplicate named groups, as described in the next section.
  6265. NAMED CAPTURE GROUPS
  6266. Identifying capture groups by number is simple, but it can be very hard
  6267. to keep track of the numbers in complicated patterns. Furthermore, if
  6268. an expression is modified, the numbers may change. To help with this
  6269. difficulty, PCRE2 supports the naming of capture groups. This feature
  6270. was not added to Perl until release 5.10. Python had the feature ear-
  6271. lier, and PCRE1 introduced it at release 4.0, using the Python syntax.
  6272. PCRE2 supports both the Perl and the Python syntax.
  6273. In PCRE2, a capture group can be named in one of three ways:
  6274. (?<name>...) or (?'name'...) as in Perl, or (?P<name>...) as in Python.
  6275. Names may be up to 128 code units long. When PCRE2_UTF is not set, they
  6276. may contain only ASCII alphanumeric characters and underscores, but
  6277. must start with a non-digit. When PCRE2_UTF is set, the syntax of group
  6278. names is extended to allow any Unicode letter or Unicode decimal digit.
  6279. In other words, group names must match one of these patterns:
  6280. ^[_A-Za-z][_A-Za-z0-9]*\z when PCRE2_UTF is not set
  6281. ^[_\p{L}][_\p{L}\p{Nd}]*\z when PCRE2_UTF is set
  6282. References to capture groups from other parts of the pattern, such as
  6283. backreferences, recursion, and conditions, can all be made by name as
  6284. well as by number.
  6285. Named capture groups are allocated numbers as well as names, exactly as
  6286. if the names were not present. In both PCRE2 and Perl, capture groups
  6287. are primarily identified by numbers; any names are just aliases for
  6288. these numbers. The PCRE2 API provides function calls for extracting the
  6289. complete name-to-number translation table from a compiled pattern, as
  6290. well as convenience functions for extracting captured substrings by
  6291. name.
  6292. Warning: When more than one capture group has the same number, as de-
  6293. scribed in the previous section, a name given to one of them applies to
  6294. all of them. Perl allows identically numbered groups to have different
  6295. names. Consider this pattern, where there are two capture groups, both
  6296. numbered 1:
  6297. (?|(?<AA>aa)|(?<BB>bb))
  6298. Perl allows this, with both names AA and BB as aliases of group 1.
  6299. Thus, after a successful match, both names yield the same value (either
  6300. "aa" or "bb").
  6301. In an attempt to reduce confusion, PCRE2 does not allow the same group
  6302. number to be associated with more than one name. The example above pro-
  6303. vokes a compile-time error. However, there is still scope for confu-
  6304. sion. Consider this pattern:
  6305. (?|(?<AA>aa)|(bb))
  6306. Although the second group number 1 is not explicitly named, the name AA
  6307. is still an alias for any group 1. Whether the pattern matches "aa" or
  6308. "bb", a reference by name to group AA yields the matched string.
  6309. By default, a name must be unique within a pattern, except that dupli-
  6310. cate names are permitted for groups with the same number, for example:
  6311. (?|(?<AA>aa)|(?<AA>bb))
  6312. The duplicate name constraint can be disabled by setting the PCRE2_DUP-
  6313. NAMES option at compile time, or by the use of (?J) within the pattern,
  6314. as described in the section entitled "Internal Option Setting" above.
  6315. Duplicate names can be useful for patterns where only one instance of
  6316. the named capture group can match. Suppose you want to match the name
  6317. of a weekday, either as a 3-letter abbreviation or as the full name,
  6318. and in both cases you want to extract the abbreviation. This pattern
  6319. (ignoring the line breaks) does the job:
  6320. (?J)
  6321. (?<DN>Mon|Fri|Sun)(?:day)?|
  6322. (?<DN>Tue)(?:sday)?|
  6323. (?<DN>Wed)(?:nesday)?|
  6324. (?<DN>Thu)(?:rsday)?|
  6325. (?<DN>Sat)(?:urday)?
  6326. There are five capture groups, but only one is ever set after a match.
  6327. The convenience functions for extracting the data by name returns the
  6328. substring for the first (and in this example, the only) group of that
  6329. name that matched. This saves searching to find which numbered group it
  6330. was. (An alternative way of solving this problem is to use a "branch
  6331. reset" group, as described in the previous section.)
  6332. If you make a backreference to a non-unique named group from elsewhere
  6333. in the pattern, the groups to which the name refers are checked in the
  6334. order in which they appear in the overall pattern. The first one that
  6335. is set is used for the reference. For example, this pattern matches
  6336. both "foofoo" and "barbar" but not "foobar" or "barfoo":
  6337. (?J)(?:(?<n>foo)|(?<n>bar))\k<n>
  6338. If you make a subroutine call to a non-unique named group, the one that
  6339. corresponds to the first occurrence of the name is used. In the absence
  6340. of duplicate numbers this is the one with the lowest number.
  6341. If you use a named reference in a condition test (see the section about
  6342. conditions below), either to check whether a capture group has matched,
  6343. or to check for recursion, all groups with the same name are tested. If
  6344. the condition is true for any one of them, the overall condition is
  6345. true. This is the same behaviour as testing by number. For further de-
  6346. tails of the interfaces for handling named capture groups, see the
  6347. pcre2api documentation.
  6348. REPETITION
  6349. Repetition is specified by quantifiers, which may follow any one of
  6350. these items:
  6351. a literal data character
  6352. the dot metacharacter
  6353. the \C escape sequence
  6354. the \R escape sequence
  6355. the \X escape sequence
  6356. any escape sequence that matches a single character
  6357. a character class
  6358. a backreference
  6359. a parenthesized group (including lookaround assertions)
  6360. a subroutine call (recursive or otherwise)
  6361. If a quantifier does not follow a repeatable item, an error occurs. The
  6362. general repetition quantifier specifies a minimum and maximum number of
  6363. permitted matches by giving two numbers in curly brackets (braces),
  6364. separated by a comma. The numbers must be less than 65536, and the
  6365. first must be less than or equal to the second. For example,
  6366. z{2,4}
  6367. matches "zz", "zzz", or "zzzz". A closing brace on its own is not a
  6368. special character. If the second number is omitted, but the comma is
  6369. present, there is no upper limit; if the second number and the comma
  6370. are both omitted, the quantifier specifies an exact number of required
  6371. matches. Thus
  6372. [aeiou]{3,}
  6373. matches at least 3 successive vowels, but may match many more, whereas
  6374. \d{8}
  6375. matches exactly 8 digits. If the first number is omitted, the lower
  6376. limit is taken as zero; in this case the upper limit must be present.
  6377. X{,4} is interpreted as X{0,4}
  6378. This is a change in behaviour that happened in Perl 5.34.0 and PCRE2
  6379. 10.43. In earlier versions such a sequence was not interpreted as a
  6380. quantifier. Other regular expression engines may behave either way.
  6381. If the characters that follow an opening brace do not match the syntax
  6382. of a quantifier, the brace is taken as a literal character. In particu-
  6383. lar, this means that {,} is a literal string of three characters.
  6384. Note that not every opening brace is potentially the start of a quanti-
  6385. fier because braces are used in other items such as \N{U+345} or
  6386. \k{name}.
  6387. In UTF modes, quantifiers apply to characters rather than to individual
  6388. code units. Thus, for example, \x{100}{2} matches two characters, each
  6389. of which is represented by a two-byte sequence in a UTF-8 string. Simi-
  6390. larly, \X{3} matches three Unicode extended grapheme clusters, each of
  6391. which may be several code units long (and they may be of different
  6392. lengths).
  6393. The quantifier {0} is permitted, causing the expression to behave as if
  6394. the previous item and the quantifier were not present. This may be use-
  6395. ful for capture groups that are referenced as subroutines from else-
  6396. where in the pattern (but see also the section entitled "Defining cap-
  6397. ture groups for use by reference only" below). Except for parenthesized
  6398. groups, items that have a {0} quantifier are omitted from the compiled
  6399. pattern.
  6400. For convenience, the three most common quantifiers have single-charac-
  6401. ter abbreviations:
  6402. * is equivalent to {0,}
  6403. + is equivalent to {1,}
  6404. ? is equivalent to {0,1}
  6405. It is possible to construct infinite loops by following a group that
  6406. can match no characters with a quantifier that has no upper limit, for
  6407. example:
  6408. (a?)*
  6409. Earlier versions of Perl and PCRE1 used to give an error at compile
  6410. time for such patterns. However, because there are cases where this can
  6411. be useful, such patterns are now accepted, but whenever an iteration of
  6412. such a group matches no characters, matching moves on to the next item
  6413. in the pattern instead of repeatedly matching an empty string. This
  6414. does not prevent backtracking into any of the iterations if a subse-
  6415. quent item fails to match.
  6416. By default, quantifiers are "greedy", that is, they match as much as
  6417. possible (up to the maximum number of permitted repetitions), without
  6418. causing the rest of the pattern to fail. The classic example of where
  6419. this gives problems is in trying to match comments in C programs. These
  6420. appear between /* and */ and within the comment, individual * and /
  6421. characters may appear. An attempt to match C comments by applying the
  6422. pattern
  6423. /\*.*\*/
  6424. to the string
  6425. /* first comment */ not comment /* second comment */
  6426. fails, because it matches the entire string owing to the greediness of
  6427. the .* item. However, if a quantifier is followed by a question mark,
  6428. it ceases to be greedy, and instead matches the minimum number of times
  6429. possible, so the pattern
  6430. /\*.*?\*/
  6431. does the right thing with C comments. The meaning of the various quan-
  6432. tifiers is not otherwise changed, just the preferred number of matches.
  6433. Do not confuse this use of question mark with its use as a quantifier
  6434. in its own right. Because it has two uses, it can sometimes appear
  6435. doubled, as in
  6436. \d??\d
  6437. which matches one digit by preference, but can match two if that is the
  6438. only way the rest of the pattern matches.
  6439. If the PCRE2_UNGREEDY option is set (an option that is not available in
  6440. Perl), the quantifiers are not greedy by default, but individual ones
  6441. can be made greedy by following them with a question mark. In other
  6442. words, it inverts the default behaviour.
  6443. When a parenthesized group is quantified with a minimum repeat count
  6444. that is greater than 1 or with a limited maximum, more memory is re-
  6445. quired for the compiled pattern, in proportion to the size of the mini-
  6446. mum or maximum.
  6447. If a pattern starts with .* or .{0,} and the PCRE2_DOTALL option
  6448. (equivalent to Perl's /s) is set, thus allowing the dot to match new-
  6449. lines, the pattern is implicitly anchored, because whatever follows
  6450. will be tried against every character position in the subject string,
  6451. so there is no point in retrying the overall match at any position af-
  6452. ter the first. PCRE2 normally treats such a pattern as though it were
  6453. preceded by \A.
  6454. In cases where it is known that the subject string contains no new-
  6455. lines, it is worth setting PCRE2_DOTALL in order to obtain this opti-
  6456. mization, or alternatively, using ^ to indicate anchoring explicitly.
  6457. However, there are some cases where the optimization cannot be used.
  6458. When .* is inside capturing parentheses that are the subject of a
  6459. backreference elsewhere in the pattern, a match at the start may fail
  6460. where a later one succeeds. Consider, for example:
  6461. (.*)abc\1
  6462. If the subject is "xyz123abc123" the match point is the fourth charac-
  6463. ter. For this reason, such a pattern is not implicitly anchored.
  6464. Another case where implicit anchoring is not applied is when the lead-
  6465. ing .* is inside an atomic group. Once again, a match at the start may
  6466. fail where a later one succeeds. Consider this pattern:
  6467. (?>.*?a)b
  6468. It matches "ab" in the subject "aab". The use of the backtracking con-
  6469. trol verbs (*PRUNE) and (*SKIP) also disable this optimization, and
  6470. there is an option, PCRE2_NO_DOTSTAR_ANCHOR, to do so explicitly.
  6471. When a capture group is repeated, the value captured is the substring
  6472. that matched the final iteration. For example, after
  6473. (tweedle[dume]{3}\s*)+
  6474. has matched "tweedledum tweedledee" the value of the captured substring
  6475. is "tweedledee". However, if there are nested capture groups, the cor-
  6476. responding captured values may have been set in previous iterations.
  6477. For example, after
  6478. (a|(b))+
  6479. matches "aba" the value of the second captured substring is "b".
  6480. ATOMIC GROUPING AND POSSESSIVE QUANTIFIERS
  6481. With both maximizing ("greedy") and minimizing ("ungreedy" or "lazy")
  6482. repetition, failure of what follows normally causes the repeated item
  6483. to be re-evaluated to see if a different number of repeats allows the
  6484. rest of the pattern to match. Sometimes it is useful to prevent this,
  6485. either to change the nature of the match, or to cause it fail earlier
  6486. than it otherwise might, when the author of the pattern knows there is
  6487. no point in carrying on.
  6488. Consider, for example, the pattern \d+foo when applied to the subject
  6489. line
  6490. 123456bar
  6491. After matching all 6 digits and then failing to match "foo", the normal
  6492. action of the matcher is to try again with only 5 digits matching the
  6493. \d+ item, and then with 4, and so on, before ultimately failing.
  6494. "Atomic grouping" (a term taken from Jeffrey Friedl's book) provides
  6495. the means for specifying that once a group has matched, it is not to be
  6496. re-evaluated in this way.
  6497. If we use atomic grouping for the previous example, the matcher gives
  6498. up immediately on failing to match "foo" the first time. The notation
  6499. is a kind of special parenthesis, starting with (?> as in this example:
  6500. (?>\d+)foo
  6501. Perl 5.28 introduced an experimental alphabetic form starting with (*
  6502. which may be easier to remember:
  6503. (*atomic:\d+)foo
  6504. This kind of parenthesized group "locks up" the part of the pattern it
  6505. contains once it has matched, and a failure further into the pattern is
  6506. prevented from backtracking into it. Backtracking past it to previous
  6507. items, however, works as normal.
  6508. An alternative description is that a group of this type matches exactly
  6509. the string of characters that an identical standalone pattern would
  6510. match, if anchored at the current point in the subject string.
  6511. Atomic groups are not capture groups. Simple cases such as the above
  6512. example can be thought of as a maximizing repeat that must swallow
  6513. everything it can. So, while both \d+ and \d+? are prepared to adjust
  6514. the number of digits they match in order to make the rest of the pat-
  6515. tern match, (?>\d+) can only match an entire sequence of digits.
  6516. Atomic groups in general can of course contain arbitrarily complicated
  6517. expressions, and can be nested. However, when the contents of an atomic
  6518. group is just a single repeated item, as in the example above, a sim-
  6519. pler notation, called a "possessive quantifier" can be used. This con-
  6520. sists of an additional + character following a quantifier. Using this
  6521. notation, the previous example can be rewritten as
  6522. \d++foo
  6523. Note that a possessive quantifier can be used with an entire group, for
  6524. example:
  6525. (abc|xyz){2,3}+
  6526. Possessive quantifiers are always greedy; the setting of the PCRE2_UN-
  6527. GREEDY option is ignored. They are a convenient notation for the sim-
  6528. pler forms of atomic group. However, there is no difference in the
  6529. meaning of a possessive quantifier and the equivalent atomic group,
  6530. though there may be a performance difference; possessive quantifiers
  6531. should be slightly faster.
  6532. The possessive quantifier syntax is an extension to the Perl 5.8 syn-
  6533. tax. Jeffrey Friedl originated the idea (and the name) in the first
  6534. edition of his book. Mike McCloskey liked it, so implemented it when he
  6535. built Sun's Java package, and PCRE1 copied it from there. It found its
  6536. way into Perl at release 5.10.
  6537. PCRE2 has an optimization that automatically "possessifies" certain
  6538. simple pattern constructs. For example, the sequence A+B is treated as
  6539. A++B because there is no point in backtracking into a sequence of A's
  6540. when B must follow. This feature can be disabled by the PCRE2_NO_AUTO-
  6541. POSSESS option, or starting the pattern with (*NO_AUTO_POSSESS).
  6542. When a pattern contains an unlimited repeat inside a group that can it-
  6543. self be repeated an unlimited number of times, the use of an atomic
  6544. group is the only way to avoid some failing matches taking a very long
  6545. time indeed. The pattern
  6546. (\D+|<\d+>)*[!?]
  6547. matches an unlimited number of substrings that either consist of non-
  6548. digits, or digits enclosed in <>, followed by either ! or ?. When it
  6549. matches, it runs quickly. However, if it is applied to
  6550. aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
  6551. it takes a long time before reporting failure. This is because the
  6552. string can be divided between the internal \D+ repeat and the external
  6553. * repeat in a large number of ways, and all have to be tried. (The ex-
  6554. ample uses [!?] rather than a single character at the end, because both
  6555. PCRE2 and Perl have an optimization that allows for fast failure when a
  6556. single character is used. They remember the last single character that
  6557. is required for a match, and fail early if it is not present in the
  6558. string.) If the pattern is changed so that it uses an atomic group,
  6559. like this:
  6560. ((?>\D+)|<\d+>)*[!?]
  6561. sequences of non-digits cannot be broken, and failure happens quickly.
  6562. BACKREFERENCES
  6563. Outside a character class, a backslash followed by a digit greater than
  6564. 0 (and possibly further digits) is a backreference to a capture group
  6565. earlier (that is, to its left) in the pattern, provided there have been
  6566. that many previous capture groups.
  6567. However, if the decimal number following the backslash is less than 8,
  6568. it is always taken as a backreference, and causes an error only if
  6569. there are not that many capture groups in the entire pattern. In other
  6570. words, the group that is referenced need not be to the left of the ref-
  6571. erence for numbers less than 8. A "forward backreference" of this type
  6572. can make sense when a repetition is involved and the group to the right
  6573. has participated in an earlier iteration.
  6574. It is not possible to have a numerical "forward backreference" to a
  6575. group whose number is 8 or more using this syntax because a sequence
  6576. such as \50 is interpreted as a character defined in octal. See the
  6577. subsection entitled "Non-printing characters" above for further details
  6578. of the handling of digits following a backslash. Other forms of back-
  6579. referencing do not suffer from this restriction. In particular, there
  6580. is no problem when named capture groups are used (see below).
  6581. Another way of avoiding the ambiguity inherent in the use of digits
  6582. following a backslash is to use the \g escape sequence. This escape
  6583. must be followed by a signed or unsigned number, optionally enclosed in
  6584. braces. These examples are all identical:
  6585. (ring), \1
  6586. (ring), \g1
  6587. (ring), \g{1}
  6588. An unsigned number specifies an absolute reference without the ambigu-
  6589. ity that is present in the older syntax. It is also useful when literal
  6590. digits follow the reference. A signed number is a relative reference.
  6591. Consider this example:
  6592. (abc(def)ghi)\g{-1}
  6593. The sequence \g{-1} is a reference to the capture group whose number is
  6594. one less than the number of the next group to be started, so in this
  6595. example (where the next group would be numbered 3) is it equivalent to
  6596. \2, and \g{-2} would be equivalent to \1. Note that if this construct
  6597. is inside a capture group, that group is included in the count, so in
  6598. this example \g{-2} also refers to group 1:
  6599. (A)(\g{-2}B)
  6600. The use of relative references can be helpful in long patterns, and
  6601. also in patterns that are created by joining together fragments that
  6602. contain references within themselves.
  6603. The sequence \g{+1} is a reference to the next capture group that is
  6604. started after this item, and \g{+2} refers to the one after that, and
  6605. so on. This kind of forward reference can be useful in patterns that
  6606. repeat. Perl does not support the use of + in this way.
  6607. A backreference matches whatever actually most recently matched the
  6608. capture group in the current subject string, rather than anything at
  6609. all that matches the group (see "Groups as subroutines" below for a way
  6610. of doing that). So the pattern
  6611. (sens|respons)e and \1ibility
  6612. matches "sense and sensibility" and "response and responsibility", but
  6613. not "sense and responsibility". If caseful matching is in force at the
  6614. time of the backreference, the case of letters is relevant. For exam-
  6615. ple,
  6616. ((?i)rah)\s+\1
  6617. matches "rah rah" and "RAH RAH", but not "RAH rah", even though the
  6618. original capture group is matched caselessly.
  6619. There are several different ways of writing backreferences to named
  6620. capture groups. The .NET syntax is \k{name}, the Python syntax is
  6621. (?=name), and the original Perl syntax is \k<name> or \k'name'. All of
  6622. these are now supported by both Perl and PCRE2. Perl 5.10's unified
  6623. backreference syntax, in which \g can be used for both numeric and
  6624. named references, is also supported by PCRE2. We could rewrite the
  6625. above example in any of the following ways:
  6626. (?<p1>(?i)rah)\s+\k<p1>
  6627. (?'p1'(?i)rah)\s+\k{p1}
  6628. (?P<p1>(?i)rah)\s+(?P=p1)
  6629. (?<p1>(?i)rah)\s+\g{p1}
  6630. A capture group that is referenced by name may appear in the pattern
  6631. before or after the reference.
  6632. There may be more than one backreference to the same group. If a group
  6633. has not actually been used in a particular match, backreferences to it
  6634. always fail by default. For example, the pattern
  6635. (a|(bc))\2
  6636. always fails if it starts to match "a" rather than "bc". However, if
  6637. the PCRE2_MATCH_UNSET_BACKREF option is set at compile time, a backref-
  6638. erence to an unset value matches an empty string.
  6639. Because there may be many capture groups in a pattern, all digits fol-
  6640. lowing a backslash are taken as part of a potential backreference num-
  6641. ber. If the pattern continues with a digit character, some delimiter
  6642. must be used to terminate the backreference. If the PCRE2_EXTENDED or
  6643. PCRE2_EXTENDED_MORE option is set, this can be white space. Otherwise,
  6644. the \g{} syntax or an empty comment (see "Comments" below) can be used.
  6645. Recursive backreferences
  6646. A backreference that occurs inside the group to which it refers fails
  6647. when the group is first used, so, for example, (a\1) never matches.
  6648. However, such references can be useful inside repeated groups. For ex-
  6649. ample, the pattern
  6650. (a|b\1)+
  6651. matches any number of "a"s and also "aba", "ababbaa" etc. At each iter-
  6652. ation of the group, the backreference matches the character string cor-
  6653. responding to the previous iteration. In order for this to work, the
  6654. pattern must be such that the first iteration does not need to match
  6655. the backreference. This can be done using alternation, as in the exam-
  6656. ple above, or by a quantifier with a minimum of zero.
  6657. For versions of PCRE2 less than 10.25, backreferences of this type used
  6658. to cause the group that they reference to be treated as an atomic
  6659. group. This restriction no longer applies, and backtracking into such
  6660. groups can occur as normal.
  6661. ASSERTIONS
  6662. An assertion is a test on the characters following or preceding the
  6663. current matching point that does not consume any characters. The simple
  6664. assertions coded as \b, \B, \A, \G, \Z, \z, ^ and $ are described
  6665. above.
  6666. More complicated assertions are coded as parenthesized groups. There
  6667. are two kinds: those that look ahead of the current position in the
  6668. subject string, and those that look behind it, and in each case an as-
  6669. sertion may be positive (must match for the assertion to be true) or
  6670. negative (must not match for the assertion to be true). An assertion
  6671. group is matched in the normal way, and if it is true, matching contin-
  6672. ues after it, but with the matching position in the subject string re-
  6673. set to what it was before the assertion was processed.
  6674. The Perl-compatible lookaround assertions are atomic. If an assertion
  6675. is true, but there is a subsequent matching failure, there is no back-
  6676. tracking into the assertion. However, there are some cases where non-
  6677. atomic assertions can be useful. PCRE2 has some support for these, de-
  6678. scribed in the section entitled "Non-atomic assertions" below, but they
  6679. are not Perl-compatible.
  6680. A lookaround assertion may appear as the condition in a conditional
  6681. group (see below). In this case, the result of matching the assertion
  6682. determines which branch of the condition is followed.
  6683. Assertion groups are not capture groups. If an assertion contains cap-
  6684. ture groups within it, these are counted for the purposes of numbering
  6685. the capture groups in the whole pattern. Within each branch of an as-
  6686. sertion, locally captured substrings may be referenced in the usual
  6687. way. For example, a sequence such as (.)\g{-1} can be used to check
  6688. that two adjacent characters are the same.
  6689. When a branch within an assertion fails to match, any substrings that
  6690. were captured are discarded (as happens with any pattern branch that
  6691. fails to match). A negative assertion is true only when all its
  6692. branches fail to match; this means that no captured substrings are ever
  6693. retained after a successful negative assertion. When an assertion con-
  6694. tains a matching branch, what happens depends on the type of assertion.
  6695. For a positive assertion, internally captured substrings in the suc-
  6696. cessful branch are retained, and matching continues with the next pat-
  6697. tern item after the assertion. For a negative assertion, a matching
  6698. branch means that the assertion is not true. If such an assertion is
  6699. being used as a condition in a conditional group (see below), captured
  6700. substrings are retained, because matching continues with the "no"
  6701. branch of the condition. For other failing negative assertions, control
  6702. passes to the previous backtracking point, thus discarding any captured
  6703. strings within the assertion.
  6704. Most assertion groups may be repeated; though it makes no sense to as-
  6705. sert the same thing several times, the side effect of capturing in pos-
  6706. itive assertions may occasionally be useful. However, an assertion that
  6707. forms the condition for a conditional group may not be quantified.
  6708. PCRE2 used to restrict the repetition of assertions, but from release
  6709. 10.35 the only restriction is that an unlimited maximum repetition is
  6710. changed to be one more than the minimum. For example, {3,} is treated
  6711. as {3,4}.
  6712. Alphabetic assertion names
  6713. Traditionally, symbolic sequences such as (?= and (?<= have been used
  6714. to specify lookaround assertions. Perl 5.28 introduced some experimen-
  6715. tal alphabetic alternatives which might be easier to remember. They all
  6716. start with (* instead of (? and must be written using lower case let-
  6717. ters. PCRE2 supports the following synonyms:
  6718. (*positive_lookahead: or (*pla: is the same as (?=
  6719. (*negative_lookahead: or (*nla: is the same as (?!
  6720. (*positive_lookbehind: or (*plb: is the same as (?<=
  6721. (*negative_lookbehind: or (*nlb: is the same as (?<!
  6722. For example, (*pla:foo) is the same assertion as (?=foo). In the fol-
  6723. lowing sections, the various assertions are described using the origi-
  6724. nal symbolic forms.
  6725. Lookahead assertions
  6726. Lookahead assertions start with (?= for positive assertions and (?! for
  6727. negative assertions. For example,
  6728. \w+(?=;)
  6729. matches a word followed by a semicolon, but does not include the semi-
  6730. colon in the match, and
  6731. foo(?!bar)
  6732. matches any occurrence of "foo" that is not followed by "bar". Note
  6733. that the apparently similar pattern
  6734. (?!foo)bar
  6735. does not find an occurrence of "bar" that is preceded by something
  6736. other than "foo"; it finds any occurrence of "bar" whatsoever, because
  6737. the assertion (?!foo) is always true when the next three characters are
  6738. "bar". A lookbehind assertion is needed to achieve the other effect.
  6739. If you want to force a matching failure at some point in a pattern, the
  6740. most convenient way to do it is with (?!) because an empty string al-
  6741. ways matches, so an assertion that requires there not to be an empty
  6742. string must always fail. The backtracking control verb (*FAIL) or (*F)
  6743. is a synonym for (?!).
  6744. Lookbehind assertions
  6745. Lookbehind assertions start with (?<= for positive assertions and (?<!
  6746. for negative assertions. For example,
  6747. (?<!foo)bar
  6748. does find an occurrence of "bar" that is not preceded by "foo". The
  6749. contents of a lookbehind assertion are restricted such that there must
  6750. be a known maximum to the lengths of all the strings it matches. There
  6751. are two cases:
  6752. If every top-level alternative matches a fixed length, for example
  6753. (?<=colour|color)
  6754. there is a limit of 65535 characters to the lengths, which do not have
  6755. to be the same, as this example demonstrates. This is the only kind of
  6756. lookbehind supported by PCRE2 versions earlier than 10.43 and by the
  6757. alternative matching function pcre2_dfa_match().
  6758. In PCRE2 10.43 and later, pcre2_match() supports lookbehind assertions
  6759. in which one or more top-level alternatives can match more than one
  6760. string length, for example
  6761. (?<=colou?r)
  6762. The maximum matching length for any branch of the lookbehind is limited
  6763. to a value set by the calling program (default 255 characters). Unlim-
  6764. ited repetition (for example \d*) is not supported. In some cases, the
  6765. escape sequence \K (see above) can be used instead of a lookbehind as-
  6766. sertion at the start of a pattern to get round the length limit re-
  6767. striction.
  6768. In UTF-8 and UTF-16 modes, PCRE2 does not allow the \C escape (which
  6769. matches a single code unit even in a UTF mode) to appear in lookbehind
  6770. assertions, because it makes it impossible to calculate the length of
  6771. the lookbehind. The \X and \R escapes, which can match different num-
  6772. bers of code units, are never permitted in lookbehinds.
  6773. "Subroutine" calls (see below) such as (?2) or (?&X) are permitted in
  6774. lookbehinds, as long as the called capture group matches a limited-
  6775. length string. However, recursion, that is, a "subroutine" call into a
  6776. group that is already active, is not supported.
  6777. PCRE2 supports backreferences in lookbehinds, but only if certain con-
  6778. ditions are met. The PCRE2_MATCH_UNSET_BACKREF option must not be set,
  6779. there must be no use of (?| in the pattern (it creates duplicate group
  6780. numbers), and if the backreference is by name, the name must be unique.
  6781. Of course, the referenced group must itself match a limited length sub-
  6782. string. The following pattern matches words containing at least two
  6783. characters that begin and end with the same character:
  6784. \b(\w)\w++(?<=\1)
  6785. Possessive quantifiers can be used in conjunction with lookbehind as-
  6786. sertions to specify efficient matching at the end of subject strings.
  6787. Consider a simple pattern such as
  6788. abcd$
  6789. when applied to a long string that does not match. Because matching
  6790. proceeds from left to right, PCRE2 will look for each "a" in the sub-
  6791. ject and then see if what follows matches the rest of the pattern. If
  6792. the pattern is specified as
  6793. ^.*abcd$
  6794. the initial .* matches the entire string at first, but when this fails
  6795. (because there is no following "a"), it backtracks to match all but the
  6796. last character, then all but the last two characters, and so on. Once
  6797. again the search for "a" covers the entire string, from right to left,
  6798. so we are no better off. However, if the pattern is written as
  6799. ^.*+(?<=abcd)
  6800. there can be no backtracking for the .*+ item because of the possessive
  6801. quantifier; it can match only the entire string. The subsequent lookbe-
  6802. hind assertion does a single test on the last four characters. If it
  6803. fails, the match fails immediately. For long strings, this approach
  6804. makes a significant difference to the processing time.
  6805. Using multiple assertions
  6806. Several assertions (of any sort) may occur in succession. For example,
  6807. (?<=\d{3})(?<!999)foo
  6808. matches "foo" preceded by three digits that are not "999". Notice that
  6809. each of the assertions is applied independently at the same point in
  6810. the subject string. First there is a check that the previous three
  6811. characters are all digits, and then there is a check that the same
  6812. three characters are not "999". This pattern does not match "foo" pre-
  6813. ceded by six characters, the first of which are digits and the last
  6814. three of which are not "999". For example, it doesn't match "123abc-
  6815. foo". A pattern to do that is
  6816. (?<=\d{3}...)(?<!999)foo
  6817. This time the first assertion looks at the preceding six characters,
  6818. checking that the first three are digits, and then the second assertion
  6819. checks that the preceding three characters are not "999".
  6820. Assertions can be nested in any combination. For example,
  6821. (?<=(?<!foo)bar)baz
  6822. matches an occurrence of "baz" that is preceded by "bar" which in turn
  6823. is not preceded by "foo", while
  6824. (?<=\d{3}(?!999)...)foo
  6825. is another pattern that matches "foo" preceded by three digits and any
  6826. three characters that are not "999".
  6827. NON-ATOMIC ASSERTIONS
  6828. Traditional lookaround assertions are atomic. That is, if an assertion
  6829. is true, but there is a subsequent matching failure, there is no back-
  6830. tracking into the assertion. However, there are some cases where non-
  6831. atomic positive assertions can be useful. PCRE2 provides these using
  6832. the following syntax:
  6833. (*non_atomic_positive_lookahead: or (*napla: or (?*
  6834. (*non_atomic_positive_lookbehind: or (*naplb: or (?<*
  6835. Consider the problem of finding the right-most word in a string that
  6836. also appears earlier in the string, that is, it must appear at least
  6837. twice in total. This pattern returns the required result as captured
  6838. substring 1:
  6839. ^(?x)(*napla: .* \b(\w++)) (?> .*? \b\1\b ){2}
  6840. For a subject such as "word1 word2 word3 word2 word3 word4" the result
  6841. is "word3". How does it work? At the start, ^(?x) anchors the pattern
  6842. and sets the "x" option, which causes white space (introduced for read-
  6843. ability) to be ignored. Inside the assertion, the greedy .* at first
  6844. consumes the entire string, but then has to backtrack until the rest of
  6845. the assertion can match a word, which is captured by group 1. In other
  6846. words, when the assertion first succeeds, it captures the right-most
  6847. word in the string.
  6848. The current matching point is then reset to the start of the subject,
  6849. and the rest of the pattern match checks for two occurrences of the
  6850. captured word, using an ungreedy .*? to scan from the left. If this
  6851. succeeds, we are done, but if the last word in the string does not oc-
  6852. cur twice, this part of the pattern fails. If a traditional atomic
  6853. lookahead (?= or (*pla: had been used, the assertion could not be re-
  6854. entered, and the whole match would fail. The pattern would succeed only
  6855. if the very last word in the subject was found twice.
  6856. Using a non-atomic lookahead, however, means that when the last word
  6857. does not occur twice in the string, the lookahead can backtrack and
  6858. find the second-last word, and so on, until either the match succeeds,
  6859. or all words have been tested.
  6860. Two conditions must be met for a non-atomic assertion to be useful: the
  6861. contents of one or more capturing groups must change after a backtrack
  6862. into the assertion, and there must be a backreference to a changed
  6863. group later in the pattern. If this is not the case, the rest of the
  6864. pattern match fails exactly as before because nothing has changed, so
  6865. using a non-atomic assertion just wastes resources.
  6866. There is one exception to backtracking into a non-atomic assertion. If
  6867. an (*ACCEPT) control verb is triggered, the assertion succeeds atomi-
  6868. cally. That is, a subsequent match failure cannot backtrack into the
  6869. assertion.
  6870. Non-atomic assertions are not supported by the alternative matching
  6871. function pcre2_dfa_match(). They are supported by JIT, but only if they
  6872. do not contain any control verbs such as (*ACCEPT). (This may change in
  6873. future). Note that assertions that appear as conditions for conditional
  6874. groups (see below) must be atomic.
  6875. SCRIPT RUNS
  6876. In concept, a script run is a sequence of characters that are all from
  6877. the same Unicode script such as Latin or Greek. However, because some
  6878. scripts are commonly used together, and because some diacritical and
  6879. other marks are used with multiple scripts, it is not that simple.
  6880. There is a full description of the rules that PCRE2 uses in the section
  6881. entitled "Script Runs" in the pcre2unicode documentation.
  6882. If part of a pattern is enclosed between (*script_run: or (*sr: and a
  6883. closing parenthesis, it fails if the sequence of characters that it
  6884. matches are not a script run. After a failure, normal backtracking oc-
  6885. curs. Script runs can be used to detect spoofing attacks using charac-
  6886. ters that look the same, but are from different scripts. The string
  6887. "paypal.com" is an infamous example, where the letters could be a mix-
  6888. ture of Latin and Cyrillic. This pattern ensures that the matched char-
  6889. acters in a sequence of non-spaces that follow white space are a script
  6890. run:
  6891. \s+(*sr:\S+)
  6892. To be sure that they are all from the Latin script (for example), a
  6893. lookahead can be used:
  6894. \s+(?=\p{Latin})(*sr:\S+)
  6895. This works as long as the first character is expected to be a character
  6896. in that script, and not (for example) punctuation, which is allowed
  6897. with any script. If this is not the case, a more creative lookahead is
  6898. needed. For example, if digits, underscore, and dots are permitted at
  6899. the start:
  6900. \s+(?=[0-9_.]*\p{Latin})(*sr:\S+)
  6901. In many cases, backtracking into a script run pattern fragment is not
  6902. desirable. The script run can employ an atomic group to prevent this.
  6903. Because this is a common requirement, a shorthand notation is provided
  6904. by (*atomic_script_run: or (*asr:
  6905. (*asr:...) is the same as (*sr:(?>...))
  6906. Note that the atomic group is inside the script run. Putting it outside
  6907. would not prevent backtracking into the script run pattern.
  6908. Support for script runs is not available if PCRE2 is compiled without
  6909. Unicode support. A compile-time error is given if any of the above con-
  6910. structs is encountered. Script runs are not supported by the alternate
  6911. matching function, pcre2_dfa_match() because they use the same mecha-
  6912. nism as capturing parentheses.
  6913. Warning: The (*ACCEPT) control verb (see below) should not be used
  6914. within a script run group, because it causes an immediate exit from the
  6915. group, bypassing the script run checking.
  6916. CONDITIONAL GROUPS
  6917. It is possible to cause the matching process to obey a pattern fragment
  6918. conditionally or to choose between two alternative fragments, depending
  6919. on the result of an assertion, or whether a specific capture group has
  6920. already been matched. The two possible forms of conditional group are:
  6921. (?(condition)yes-pattern)
  6922. (?(condition)yes-pattern|no-pattern)
  6923. If the condition is satisfied, the yes-pattern is used; otherwise the
  6924. no-pattern (if present) is used. An absent no-pattern is equivalent to
  6925. an empty string (it always matches). If there are more than two alter-
  6926. natives in the group, a compile-time error occurs. Each of the two al-
  6927. ternatives may itself contain nested groups of any form, including con-
  6928. ditional groups; the restriction to two alternatives applies only at
  6929. the level of the condition itself. This pattern fragment is an example
  6930. where the alternatives are complex:
  6931. (?(1) (A|B|C) | (D | (?(2)E|F) | E) )
  6932. There are five kinds of condition: references to capture groups, refer-
  6933. ences to recursion, two pseudo-conditions called DEFINE and VERSION,
  6934. and assertions.
  6935. Checking for a used capture group by number
  6936. If the text between the parentheses consists of a sequence of digits,
  6937. the condition is true if a capture group of that number has previously
  6938. matched. If there is more than one capture group with the same number
  6939. (see the earlier section about duplicate group numbers), the condition
  6940. is true if any of them have matched. An alternative notation, which is
  6941. a PCRE2 extension, not supported by Perl, is to precede the digits with
  6942. a plus or minus sign. In this case, the group number is relative rather
  6943. than absolute. The most recently opened capture group (which could be
  6944. enclosing this condition) can be referenced by (?(-1), the next most
  6945. recent by (?(-2), and so on. Inside loops it can also make sense to re-
  6946. fer to subsequent groups. The next capture group to be opened can be
  6947. referenced as (?(+1), and so on. The value zero in any of these forms
  6948. is not used; it provokes a compile-time error.
  6949. Consider the following pattern, which contains non-significant white
  6950. space to make it more readable (assume the PCRE2_EXTENDED option) and
  6951. to divide it into three parts for ease of discussion:
  6952. ( \( )? [^()]+ (?(1) \) )
  6953. The first part matches an optional opening parenthesis, and if that
  6954. character is present, sets it as the first captured substring. The sec-
  6955. ond part matches one or more characters that are not parentheses. The
  6956. third part is a conditional group that tests whether or not the first
  6957. capture group matched. If it did, that is, if subject started with an
  6958. opening parenthesis, the condition is true, and so the yes-pattern is
  6959. executed and a closing parenthesis is required. Otherwise, since no-
  6960. pattern is not present, the conditional group matches nothing. In other
  6961. words, this pattern matches a sequence of non-parentheses, optionally
  6962. enclosed in parentheses.
  6963. If you were embedding this pattern in a larger one, you could use a
  6964. relative reference:
  6965. ...other stuff... ( \( )? [^()]+ (?(-1) \) ) ...
  6966. This makes the fragment independent of the parentheses in the larger
  6967. pattern.
  6968. Checking for a used capture group by name
  6969. Perl uses the syntax (?(<name>)...) or (?('name')...) to test for a
  6970. used capture group by name. For compatibility with earlier versions of
  6971. PCRE1, which had this facility before Perl, the syntax (?(name)...) is
  6972. also recognized. Note, however, that undelimited names consisting of
  6973. the letter R followed by digits are ambiguous (see the following sec-
  6974. tion). Rewriting the above example to use a named group gives this:
  6975. (?<OPEN> \( )? [^()]+ (?(<OPEN>) \) )
  6976. If the name used in a condition of this kind is a duplicate, the test
  6977. is applied to all groups of the same name, and is true if any one of
  6978. them has matched.
  6979. Checking for pattern recursion
  6980. "Recursion" in this sense refers to any subroutine-like call from one
  6981. part of the pattern to another, whether or not it is actually recur-
  6982. sive. See the sections entitled "Recursive patterns" and "Groups as
  6983. subroutines" below for details of recursion and subroutine calls.
  6984. If a condition is the string (R), and there is no capture group with
  6985. the name R, the condition is true if matching is currently in a recur-
  6986. sion or subroutine call to the whole pattern or any capture group. If
  6987. digits follow the letter R, and there is no group with that name, the
  6988. condition is true if the most recent call is into a group with the
  6989. given number, which must exist somewhere in the overall pattern. This
  6990. is a contrived example that is equivalent to a+b:
  6991. ((?(R1)a+|(?1)b))
  6992. However, in both cases, if there is a capture group with a matching
  6993. name, the condition tests for its being set, as described in the sec-
  6994. tion above, instead of testing for recursion. For example, creating a
  6995. group with the name R1 by adding (?<R1>) to the above pattern com-
  6996. pletely changes its meaning.
  6997. If a name preceded by ampersand follows the letter R, for example:
  6998. (?(R&name)...)
  6999. the condition is true if the most recent recursion is into a group of
  7000. that name (which must exist within the pattern).
  7001. This condition does not check the entire recursion stack. It tests only
  7002. the current level. If the name used in a condition of this kind is a
  7003. duplicate, the test is applied to all groups of the same name, and is
  7004. true if any one of them is the most recent recursion.
  7005. At "top level", all these recursion test conditions are false.
  7006. Defining capture groups for use by reference only
  7007. If the condition is the string (DEFINE), the condition is always false,
  7008. even if there is a group with the name DEFINE. In this case, there may
  7009. be only one alternative in the rest of the conditional group. It is al-
  7010. ways skipped if control reaches this point in the pattern; the idea of
  7011. DEFINE is that it can be used to define subroutines that can be refer-
  7012. enced from elsewhere. (The use of subroutines is described below.) For
  7013. example, a pattern to match an IPv4 address such as "192.168.23.245"
  7014. could be written like this (ignore white space and line breaks):
  7015. (?(DEFINE) (?<byte> 2[0-4]\d | 25[0-5] | 1\d\d | [1-9]?\d) )
  7016. \b (?&byte) (\.(?&byte)){3} \b
  7017. The first part of the pattern is a DEFINE group inside which another
  7018. group named "byte" is defined. This matches an individual component of
  7019. an IPv4 address (a number less than 256). When matching takes place,
  7020. this part of the pattern is skipped because DEFINE acts like a false
  7021. condition. The rest of the pattern uses references to the named group
  7022. to match the four dot-separated components of an IPv4 address, insist-
  7023. ing on a word boundary at each end.
  7024. Checking the PCRE2 version
  7025. Programs that link with a PCRE2 library can check the version by call-
  7026. ing pcre2_config() with appropriate arguments. Users of applications
  7027. that do not have access to the underlying code cannot do this. A spe-
  7028. cial "condition" called VERSION exists to allow such users to discover
  7029. which version of PCRE2 they are dealing with by using this condition to
  7030. match a string such as "yesno". VERSION must be followed either by "="
  7031. or ">=" and a version number. For example:
  7032. (?(VERSION>=10.4)yes|no)
  7033. This pattern matches "yes" if the PCRE2 version is greater or equal to
  7034. 10.4, or "no" otherwise. The fractional part of the version number may
  7035. not contain more than two digits.
  7036. Assertion conditions
  7037. If the condition is not in any of the above formats, it must be a
  7038. parenthesized assertion. This may be a positive or negative lookahead
  7039. or lookbehind assertion. However, it must be a traditional atomic as-
  7040. sertion, not one of the non-atomic assertions.
  7041. Consider this pattern, again containing non-significant white space,
  7042. and with the two alternatives on the second line:
  7043. (?(?=[^a-z]*[a-z])
  7044. \d{2}-[a-z]{3}-\d{2} | \d{2}-\d{2}-\d{2} )
  7045. The condition is a positive lookahead assertion that matches an op-
  7046. tional sequence of non-letters followed by a letter. In other words, it
  7047. tests for the presence of at least one letter in the subject. If a let-
  7048. ter is found, the subject is matched against the first alternative;
  7049. otherwise it is matched against the second. This pattern matches
  7050. strings in one of the two forms dd-aaa-dd or dd-dd-dd, where aaa are
  7051. letters and dd are digits.
  7052. When an assertion that is a condition contains capture groups, any cap-
  7053. turing that occurs in a matching branch is retained afterwards, for
  7054. both positive and negative assertions, because matching always contin-
  7055. ues after the assertion, whether it succeeds or fails. (Compare non-
  7056. conditional assertions, for which captures are retained only for posi-
  7057. tive assertions that succeed.)
  7058. COMMENTS
  7059. There are two ways of including comments in patterns that are processed
  7060. by PCRE2. In both cases, the start of the comment must not be in a
  7061. character class, nor in the middle of any other sequence of related
  7062. characters such as (?: or a group name or number. The characters that
  7063. make up a comment play no part in the pattern matching.
  7064. The sequence (?# marks the start of a comment that continues up to the
  7065. next closing parenthesis. Nested parentheses are not permitted. If the
  7066. PCRE2_EXTENDED or PCRE2_EXTENDED_MORE option is set, an unescaped #
  7067. character also introduces a comment, which in this case continues to
  7068. immediately after the next newline character or character sequence in
  7069. the pattern. Which characters are interpreted as newlines is controlled
  7070. by an option passed to the compiling function or by a special sequence
  7071. at the start of the pattern, as described in the section entitled "New-
  7072. line conventions" above. Note that the end of this type of comment is a
  7073. literal newline sequence in the pattern; escape sequences that happen
  7074. to represent a newline do not count. For example, consider this pattern
  7075. when PCRE2_EXTENDED is set, and the default newline convention (a sin-
  7076. gle linefeed character) is in force:
  7077. abc #comment \n still comment
  7078. On encountering the # character, pcre2_compile() skips along, looking
  7079. for a newline in the pattern. The sequence \n is still literal at this
  7080. stage, so it does not terminate the comment. Only an actual character
  7081. with the code value 0x0a (the default newline) does so.
  7082. RECURSIVE PATTERNS
  7083. Consider the problem of matching a string in parentheses, allowing for
  7084. unlimited nested parentheses. Without the use of recursion, the best
  7085. that can be done is to use a pattern that matches up to some fixed
  7086. depth of nesting. It is not possible to handle an arbitrary nesting
  7087. depth.
  7088. For some time, Perl has provided a facility that allows regular expres-
  7089. sions to recurse (amongst other things). It does this by interpolating
  7090. Perl code in the expression at run time, and the code can refer to the
  7091. expression itself. A Perl pattern using code interpolation to solve the
  7092. parentheses problem can be created like this:
  7093. $re = qr{\( (?: (?>[^()]+) | (?p{$re}) )* \)}x;
  7094. The (?p{...}) item interpolates Perl code at run time, and in this case
  7095. refers recursively to the pattern in which it appears.
  7096. Obviously, PCRE2 cannot support the interpolation of Perl code. In-
  7097. stead, it supports special syntax for recursion of the entire pattern,
  7098. and also for individual capture group recursion. After its introduction
  7099. in PCRE1 and Python, this kind of recursion was subsequently introduced
  7100. into Perl at release 5.10.
  7101. A special item that consists of (? followed by a number greater than
  7102. zero and a closing parenthesis is a recursive subroutine call of the
  7103. capture group of the given number, provided that it occurs inside that
  7104. group. (If not, it is a non-recursive subroutine call, which is de-
  7105. scribed in the next section.) The special item (?R) or (?0) is a recur-
  7106. sive call of the entire regular expression.
  7107. This PCRE2 pattern solves the nested parentheses problem (assume the
  7108. PCRE2_EXTENDED option is set so that white space is ignored):
  7109. \( ( [^()]++ | (?R) )* \)
  7110. First it matches an opening parenthesis. Then it matches any number of
  7111. substrings which can either be a sequence of non-parentheses, or a re-
  7112. cursive match of the pattern itself (that is, a correctly parenthesized
  7113. substring). Finally there is a closing parenthesis. Note the use of a
  7114. possessive quantifier to avoid backtracking into sequences of non-
  7115. parentheses.
  7116. If this were part of a larger pattern, you would not want to recurse
  7117. the entire pattern, so instead you could use this:
  7118. ( \( ( [^()]++ | (?1) )* \) )
  7119. We have put the pattern into parentheses, and caused the recursion to
  7120. refer to them instead of the whole pattern.
  7121. In a larger pattern, keeping track of parenthesis numbers can be
  7122. tricky. This is made easier by the use of relative references. Instead
  7123. of (?1) in the pattern above you can write (?-2) to refer to the second
  7124. most recently opened parentheses preceding the recursion. In other
  7125. words, a negative number counts capturing parentheses leftwards from
  7126. the point at which it is encountered.
  7127. Be aware however, that if duplicate capture group numbers are in use,
  7128. relative references refer to the earliest group with the appropriate
  7129. number. Consider, for example:
  7130. (?|(a)|(b)) (c) (?-2)
  7131. The first two capture groups (a) and (b) are both numbered 1, and group
  7132. (c) is number 2. When the reference (?-2) is encountered, the second
  7133. most recently opened parentheses has the number 1, but it is the first
  7134. such group (the (a) group) to which the recursion refers. This would be
  7135. the same if an absolute reference (?1) was used. In other words, rela-
  7136. tive references are just a shorthand for computing a group number.
  7137. It is also possible to refer to subsequent capture groups, by writing
  7138. references such as (?+2). However, these cannot be recursive because
  7139. the reference is not inside the parentheses that are referenced. They
  7140. are always non-recursive subroutine calls, as described in the next
  7141. section.
  7142. An alternative approach is to use named parentheses. The Perl syntax
  7143. for this is (?&name); PCRE1's earlier syntax (?P>name) is also sup-
  7144. ported. We could rewrite the above example as follows:
  7145. (?<pn> \( ( [^()]++ | (?&pn) )* \) )
  7146. If there is more than one group with the same name, the earliest one is
  7147. used.
  7148. The example pattern that we have been looking at contains nested unlim-
  7149. ited repeats, and so the use of a possessive quantifier for matching
  7150. strings of non-parentheses is important when applying the pattern to
  7151. strings that do not match. For example, when this pattern is applied to
  7152. (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()
  7153. it yields "no match" quickly. However, if a possessive quantifier is
  7154. not used, the match runs for a very long time indeed because there are
  7155. so many different ways the + and * repeats can carve up the subject,
  7156. and all have to be tested before failure can be reported.
  7157. At the end of a match, the values of capturing parentheses are those
  7158. from the outermost level. If you want to obtain intermediate values, a
  7159. callout function can be used (see below and the pcre2callout documenta-
  7160. tion). If the pattern above is matched against
  7161. (ab(cd)ef)
  7162. the value for the inner capturing parentheses (numbered 2) is "ef",
  7163. which is the last value taken on at the top level. If a capture group
  7164. is not matched at the top level, its final captured value is unset,
  7165. even if it was (temporarily) set at a deeper level during the matching
  7166. process.
  7167. Do not confuse the (?R) item with the condition (R), which tests for
  7168. recursion. Consider this pattern, which matches text in angle brack-
  7169. ets, allowing for arbitrary nesting. Only digits are allowed in nested
  7170. brackets (that is, when recursing), whereas any characters are permit-
  7171. ted at the outer level.
  7172. < (?: (?(R) \d++ | [^<>]*+) | (?R)) * >
  7173. In this pattern, (?(R) is the start of a conditional group, with two
  7174. different alternatives for the recursive and non-recursive cases. The
  7175. (?R) item is the actual recursive call.
  7176. Differences in recursion processing between PCRE2 and Perl
  7177. Some former differences between PCRE2 and Perl no longer exist.
  7178. Before release 10.30, recursion processing in PCRE2 differed from Perl
  7179. in that a recursive subroutine call was always treated as an atomic
  7180. group. That is, once it had matched some of the subject string, it was
  7181. never re-entered, even if it contained untried alternatives and there
  7182. was a subsequent matching failure. (Historical note: PCRE implemented
  7183. recursion before Perl did.)
  7184. Starting with release 10.30, recursive subroutine calls are no longer
  7185. treated as atomic. That is, they can be re-entered to try unused alter-
  7186. natives if there is a matching failure later in the pattern. This is
  7187. now compatible with the way Perl works. If you want a subroutine call
  7188. to be atomic, you must explicitly enclose it in an atomic group.
  7189. Supporting backtracking into recursions simplifies certain types of re-
  7190. cursive pattern. For example, this pattern matches palindromic strings:
  7191. ^((.)(?1)\2|.?)$
  7192. The second branch in the group matches a single central character in
  7193. the palindrome when there are an odd number of characters, or nothing
  7194. when there are an even number of characters, but in order to work it
  7195. has to be able to try the second case when the rest of the pattern
  7196. match fails. If you want to match typical palindromic phrases, the pat-
  7197. tern has to ignore all non-word characters, which can be done like
  7198. this:
  7199. ^\W*+((.)\W*+(?1)\W*+\2|\W*+.?)\W*+$
  7200. If run with the PCRE2_CASELESS option, this pattern matches phrases
  7201. such as "A man, a plan, a canal: Panama!". Note the use of the posses-
  7202. sive quantifier *+ to avoid backtracking into sequences of non-word
  7203. characters. Without this, PCRE2 takes a great deal longer (ten times or
  7204. more) to match typical phrases, and Perl takes so long that you think
  7205. it has gone into a loop.
  7206. Another way in which PCRE2 and Perl used to differ in their recursion
  7207. processing is in the handling of captured values. Formerly in Perl,
  7208. when a group was called recursively or as a subroutine (see the next
  7209. section), it had no access to any values that were captured outside the
  7210. recursion, whereas in PCRE2 these values can be referenced. Consider
  7211. this pattern:
  7212. ^(.)(\1|a(?2))
  7213. This pattern matches "bab". The first capturing parentheses match "b",
  7214. then in the second group, when the backreference \1 fails to match "b",
  7215. the second alternative matches "a" and then recurses. In the recursion,
  7216. \1 does now match "b" and so the whole match succeeds. This match used
  7217. to fail in Perl, but in later versions (I tried 5.024) it now works.
  7218. GROUPS AS SUBROUTINES
  7219. If the syntax for a recursive group call (either by number or by name)
  7220. is used outside the parentheses to which it refers, it operates a bit
  7221. like a subroutine in a programming language. More accurately, PCRE2
  7222. treats the referenced group as an independent subpattern which it tries
  7223. to match at the current matching position. The called group may be de-
  7224. fined before or after the reference. A numbered reference can be ab-
  7225. solute or relative, as in these examples:
  7226. (...(absolute)...)...(?2)...
  7227. (...(relative)...)...(?-1)...
  7228. (...(?+1)...(relative)...
  7229. An earlier example pointed out that the pattern
  7230. (sens|respons)e and \1ibility
  7231. matches "sense and sensibility" and "response and responsibility", but
  7232. not "sense and responsibility". If instead the pattern
  7233. (sens|respons)e and (?1)ibility
  7234. is used, it does match "sense and responsibility" as well as the other
  7235. two strings. Another example is given in the discussion of DEFINE
  7236. above.
  7237. Like recursions, subroutine calls used to be treated as atomic, but
  7238. this changed at PCRE2 release 10.30, so backtracking into subroutine
  7239. calls can now occur. However, any capturing parentheses that are set
  7240. during the subroutine call revert to their previous values afterwards.
  7241. Processing options such as case-independence are fixed when a group is
  7242. defined, so if it is used as a subroutine, such options cannot be
  7243. changed for different calls. For example, consider this pattern:
  7244. (abc)(?i:(?-1))
  7245. It matches "abcabc". It does not match "abcABC" because the change of
  7246. processing option does not affect the called group.
  7247. The behaviour of backtracking control verbs in groups when called as
  7248. subroutines is described in the section entitled "Backtracking verbs in
  7249. subroutines" below.
  7250. ONIGURUMA SUBROUTINE SYNTAX
  7251. For compatibility with Oniguruma, the non-Perl syntax \g followed by a
  7252. name or a number enclosed either in angle brackets or single quotes, is
  7253. an alternative syntax for calling a group as a subroutine, possibly re-
  7254. cursively. Here are two of the examples used above, rewritten using
  7255. this syntax:
  7256. (?<pn> \( ( (?>[^()]+) | \g<pn> )* \) )
  7257. (sens|respons)e and \g'1'ibility
  7258. PCRE2 supports an extension to Oniguruma: if a number is preceded by a
  7259. plus or a minus sign it is taken as a relative reference. For example:
  7260. (abc)(?i:\g<-1>)
  7261. Note that \g{...} (Perl syntax) and \g<...> (Oniguruma syntax) are not
  7262. synonymous. The former is a backreference; the latter is a subroutine
  7263. call.
  7264. CALLOUTS
  7265. Perl has a feature whereby using the sequence (?{...}) causes arbitrary
  7266. Perl code to be obeyed in the middle of matching a regular expression.
  7267. This makes it possible, amongst other things, to extract different sub-
  7268. strings that match the same pair of parentheses when there is a repeti-
  7269. tion.
  7270. PCRE2 provides a similar feature, but of course it cannot obey arbi-
  7271. trary Perl code. The feature is called "callout". The caller of PCRE2
  7272. provides an external function by putting its entry point in a match
  7273. context using the function pcre2_set_callout(), and then passing that
  7274. context to pcre2_match() or pcre2_dfa_match(). If no match context is
  7275. passed, or if the callout entry point is set to NULL, callouts are dis-
  7276. abled.
  7277. Within a regular expression, (?C<arg>) indicates a point at which the
  7278. external function is to be called. There are two kinds of callout:
  7279. those with a numerical argument and those with a string argument. (?C)
  7280. on its own with no argument is treated as (?C0). A numerical argument
  7281. allows the application to distinguish between different callouts.
  7282. String arguments were added for release 10.20 to make it possible for
  7283. script languages that use PCRE2 to embed short scripts within patterns
  7284. in a similar way to Perl.
  7285. During matching, when PCRE2 reaches a callout point, the external func-
  7286. tion is called. It is provided with the number or string argument of
  7287. the callout, the position in the pattern, and one item of data that is
  7288. also set in the match block. The callout function may cause matching to
  7289. proceed, to backtrack, or to fail.
  7290. By default, PCRE2 implements a number of optimizations at matching
  7291. time, and one side-effect is that sometimes callouts are skipped. If
  7292. you need all possible callouts to happen, you need to set options that
  7293. disable the relevant optimizations. More details, including a complete
  7294. description of the programming interface to the callout function, are
  7295. given in the pcre2callout documentation.
  7296. Callouts with numerical arguments
  7297. If you just want to have a means of identifying different callout
  7298. points, put a number less than 256 after the letter C. For example,
  7299. this pattern has two callout points:
  7300. (?C1)abc(?C2)def
  7301. If the PCRE2_AUTO_CALLOUT flag is passed to pcre2_compile(), numerical
  7302. callouts are automatically installed before each item in the pattern.
  7303. They are all numbered 255. If there is a conditional group in the pat-
  7304. tern whose condition is an assertion, an additional callout is inserted
  7305. just before the condition. An explicit callout may also be set at this
  7306. position, as in this example:
  7307. (?(?C9)(?=a)abc|def)
  7308. Note that this applies only to assertion conditions, not to other types
  7309. of condition.
  7310. Callouts with string arguments
  7311. A delimited string may be used instead of a number as a callout argu-
  7312. ment. The starting delimiter must be one of ` ' " ^ % # $ { and the
  7313. ending delimiter is the same as the start, except for {, where the end-
  7314. ing delimiter is }. If the ending delimiter is needed within the
  7315. string, it must be doubled. For example:
  7316. (?C'ab ''c'' d')xyz(?C{any text})pqr
  7317. The doubling is removed before the string is passed to the callout
  7318. function.
  7319. BACKTRACKING CONTROL
  7320. There are a number of special "Backtracking Control Verbs" (to use
  7321. Perl's terminology) that modify the behaviour of backtracking during
  7322. matching. They are generally of the form (*VERB) or (*VERB:NAME). Some
  7323. verbs take either form, and may behave differently depending on whether
  7324. or not a name argument is present. The names are not required to be
  7325. unique within the pattern.
  7326. By default, for compatibility with Perl, a name is any sequence of
  7327. characters that does not include a closing parenthesis. The name is not
  7328. processed in any way, and it is not possible to include a closing
  7329. parenthesis in the name. This can be changed by setting the
  7330. PCRE2_ALT_VERBNAMES option, but the result is no longer Perl-compati-
  7331. ble.
  7332. When PCRE2_ALT_VERBNAMES is set, backslash processing is applied to
  7333. verb names and only an unescaped closing parenthesis terminates the
  7334. name. However, the only backslash items that are permitted are \Q, \E,
  7335. and sequences such as \x{100} that define character code points. Char-
  7336. acter type escapes such as \d are faulted.
  7337. A closing parenthesis can be included in a name either as \) or between
  7338. \Q and \E. In addition to backslash processing, if the PCRE2_EXTENDED
  7339. or PCRE2_EXTENDED_MORE option is also set, unescaped whitespace in verb
  7340. names is skipped, and #-comments are recognized, exactly as in the rest
  7341. of the pattern. PCRE2_EXTENDED and PCRE2_EXTENDED_MORE do not affect
  7342. verb names unless PCRE2_ALT_VERBNAMES is also set.
  7343. The maximum length of a name is 255 in the 8-bit library and 65535 in
  7344. the 16-bit and 32-bit libraries. If the name is empty, that is, if the
  7345. closing parenthesis immediately follows the colon, the effect is as if
  7346. the colon were not there. Any number of these verbs may occur in a pat-
  7347. tern. Except for (*ACCEPT), they may not be quantified.
  7348. Since these verbs are specifically related to backtracking, most of
  7349. them can be used only when the pattern is to be matched using the tra-
  7350. ditional matching function, because that uses a backtracking algorithm.
  7351. With the exception of (*FAIL), which behaves like a failing negative
  7352. assertion, the backtracking control verbs cause an error if encountered
  7353. by the DFA matching function.
  7354. The behaviour of these verbs in repeated groups, assertions, and in
  7355. capture groups called as subroutines (whether or not recursively) is
  7356. documented below.
  7357. Optimizations that affect backtracking verbs
  7358. PCRE2 contains some optimizations that are used to speed up matching by
  7359. running some checks at the start of each match attempt. For example, it
  7360. may know the minimum length of matching subject, or that a particular
  7361. character must be present. When one of these optimizations bypasses the
  7362. running of a match, any included backtracking verbs will not, of
  7363. course, be processed. You can suppress the start-of-match optimizations
  7364. by setting the PCRE2_NO_START_OPTIMIZE option when calling pcre2_com-
  7365. pile(), or by starting the pattern with (*NO_START_OPT). There is more
  7366. discussion of this option in the section entitled "Compiling a pattern"
  7367. in the pcre2api documentation.
  7368. Experiments with Perl suggest that it too has similar optimizations,
  7369. and like PCRE2, turning them off can change the result of a match.
  7370. Verbs that act immediately
  7371. The following verbs act as soon as they are encountered.
  7372. (*ACCEPT) or (*ACCEPT:NAME)
  7373. This verb causes the match to end successfully, skipping the remainder
  7374. of the pattern. However, when it is inside a capture group that is
  7375. called as a subroutine, only that group is ended successfully. Matching
  7376. then continues at the outer level. If (*ACCEPT) in triggered in a posi-
  7377. tive assertion, the assertion succeeds; in a negative assertion, the
  7378. assertion fails.
  7379. If (*ACCEPT) is inside capturing parentheses, the data so far is cap-
  7380. tured. For example:
  7381. A((?:A|B(*ACCEPT)|C)D)
  7382. This matches "AB", "AAD", or "ACD"; when it matches "AB", "B" is cap-
  7383. tured by the outer parentheses.
  7384. (*ACCEPT) is the only backtracking verb that is allowed to be quanti-
  7385. fied because an ungreedy quantification with a minimum of zero acts
  7386. only when a backtrack happens. Consider, for example,
  7387. (A(*ACCEPT)??B)C
  7388. where A, B, and C may be complex expressions. After matching "A", the
  7389. matcher processes "BC"; if that fails, causing a backtrack, (*ACCEPT)
  7390. is triggered and the match succeeds. In both cases, all but C is cap-
  7391. tured. Whereas (*COMMIT) (see below) means "fail on backtrack", a re-
  7392. peated (*ACCEPT) of this type means "succeed on backtrack".
  7393. Warning: (*ACCEPT) should not be used within a script run group, be-
  7394. cause it causes an immediate exit from the group, bypassing the script
  7395. run checking.
  7396. (*FAIL) or (*FAIL:NAME)
  7397. This verb causes a matching failure, forcing backtracking to occur. It
  7398. may be abbreviated to (*F). It is equivalent to (?!) but easier to
  7399. read. The Perl documentation notes that it is probably useful only when
  7400. combined with (?{}) or (??{}). Those are, of course, Perl features that
  7401. are not present in PCRE2. The nearest equivalent is the callout fea-
  7402. ture, as for example in this pattern:
  7403. a+(?C)(*FAIL)
  7404. A match with the string "aaaa" always fails, but the callout is taken
  7405. before each backtrack happens (in this example, 10 times).
  7406. (*ACCEPT:NAME) and (*FAIL:NAME) behave the same as (*MARK:NAME)(*AC-
  7407. CEPT) and (*MARK:NAME)(*FAIL), respectively, that is, a (*MARK) is
  7408. recorded just before the verb acts.
  7409. Recording which path was taken
  7410. There is one verb whose main purpose is to track how a match was ar-
  7411. rived at, though it also has a secondary use in conjunction with ad-
  7412. vancing the match starting point (see (*SKIP) below).
  7413. (*MARK:NAME) or (*:NAME)
  7414. A name is always required with this verb. For all the other backtrack-
  7415. ing control verbs, a NAME argument is optional.
  7416. When a match succeeds, the name of the last-encountered mark name on
  7417. the matching path is passed back to the caller as described in the sec-
  7418. tion entitled "Other information about the match" in the pcre2api docu-
  7419. mentation. This applies to all instances of (*MARK) and other verbs,
  7420. including those inside assertions and atomic groups. However, there are
  7421. differences in those cases when (*MARK) is used in conjunction with
  7422. (*SKIP) as described below.
  7423. The mark name that was last encountered on the matching path is passed
  7424. back. A verb without a NAME argument is ignored for this purpose. Here
  7425. is an example of pcre2test output, where the "mark" modifier requests
  7426. the retrieval and outputting of (*MARK) data:
  7427. re> /X(*MARK:A)Y|X(*MARK:B)Z/mark
  7428. data> XY
  7429. 0: XY
  7430. MK: A
  7431. XZ
  7432. 0: XZ
  7433. MK: B
  7434. The (*MARK) name is tagged with "MK:" in this output, and in this exam-
  7435. ple it indicates which of the two alternatives matched. This is a more
  7436. efficient way of obtaining this information than putting each alterna-
  7437. tive in its own capturing parentheses.
  7438. If a verb with a name is encountered in a positive assertion that is
  7439. true, the name is recorded and passed back if it is the last-encoun-
  7440. tered. This does not happen for negative assertions or failing positive
  7441. assertions.
  7442. After a partial match or a failed match, the last encountered name in
  7443. the entire match process is returned. For example:
  7444. re> /X(*MARK:A)Y|X(*MARK:B)Z/mark
  7445. data> XP
  7446. No match, mark = B
  7447. Note that in this unanchored example the mark is retained from the
  7448. match attempt that started at the letter "X" in the subject. Subsequent
  7449. match attempts starting at "P" and then with an empty string do not get
  7450. as far as the (*MARK) item, but nevertheless do not reset it.
  7451. If you are interested in (*MARK) values after failed matches, you
  7452. should probably set the PCRE2_NO_START_OPTIMIZE option (see above) to
  7453. ensure that the match is always attempted.
  7454. Verbs that act after backtracking
  7455. The following verbs do nothing when they are encountered. Matching con-
  7456. tinues with what follows, but if there is a subsequent match failure,
  7457. causing a backtrack to the verb, a failure is forced. That is, back-
  7458. tracking cannot pass to the left of the verb. However, when one of
  7459. these verbs appears inside an atomic group or in a lookaround assertion
  7460. that is true, its effect is confined to that group, because once the
  7461. group has been matched, there is never any backtracking into it. Back-
  7462. tracking from beyond an assertion or an atomic group ignores the entire
  7463. group, and seeks a preceding backtracking point.
  7464. These verbs differ in exactly what kind of failure occurs when back-
  7465. tracking reaches them. The behaviour described below is what happens
  7466. when the verb is not in a subroutine or an assertion. Subsequent sec-
  7467. tions cover these special cases.
  7468. (*COMMIT) or (*COMMIT:NAME)
  7469. This verb causes the whole match to fail outright if there is a later
  7470. matching failure that causes backtracking to reach it. Even if the pat-
  7471. tern is unanchored, no further attempts to find a match by advancing
  7472. the starting point take place. If (*COMMIT) is the only backtracking
  7473. verb that is encountered, once it has been passed pcre2_match() is com-
  7474. mitted to finding a match at the current starting point, or not at all.
  7475. For example:
  7476. a+(*COMMIT)b
  7477. This matches "xxaab" but not "aacaab". It can be thought of as a kind
  7478. of dynamic anchor, or "I've started, so I must finish."
  7479. The behaviour of (*COMMIT:NAME) is not the same as (*MARK:NAME)(*COM-
  7480. MIT). It is like (*MARK:NAME) in that the name is remembered for pass-
  7481. ing back to the caller. However, (*SKIP:NAME) searches only for names
  7482. that are set with (*MARK), ignoring those set by any of the other back-
  7483. tracking verbs.
  7484. If there is more than one backtracking verb in a pattern, a different
  7485. one that follows (*COMMIT) may be triggered first, so merely passing
  7486. (*COMMIT) during a match does not always guarantee that a match must be
  7487. at this starting point.
  7488. Note that (*COMMIT) at the start of a pattern is not the same as an an-
  7489. chor, unless PCRE2's start-of-match optimizations are turned off, as
  7490. shown in this output from pcre2test:
  7491. re> /(*COMMIT)abc/
  7492. data> xyzabc
  7493. 0: abc
  7494. data>
  7495. re> /(*COMMIT)abc/no_start_optimize
  7496. data> xyzabc
  7497. No match
  7498. For the first pattern, PCRE2 knows that any match must start with "a",
  7499. so the optimization skips along the subject to "a" before applying the
  7500. pattern to the first set of data. The match attempt then succeeds. The
  7501. second pattern disables the optimization that skips along to the first
  7502. character. The pattern is now applied starting at "x", and so the
  7503. (*COMMIT) causes the match to fail without trying any other starting
  7504. points.
  7505. (*PRUNE) or (*PRUNE:NAME)
  7506. This verb causes the match to fail at the current starting position in
  7507. the subject if there is a later matching failure that causes backtrack-
  7508. ing to reach it. If the pattern is unanchored, the normal "bumpalong"
  7509. advance to the next starting character then happens. Backtracking can
  7510. occur as usual to the left of (*PRUNE), before it is reached, or when
  7511. matching to the right of (*PRUNE), but if there is no match to the
  7512. right, backtracking cannot cross (*PRUNE). In simple cases, the use of
  7513. (*PRUNE) is just an alternative to an atomic group or possessive quan-
  7514. tifier, but there are some uses of (*PRUNE) that cannot be expressed in
  7515. any other way. In an anchored pattern (*PRUNE) has the same effect as
  7516. (*COMMIT).
  7517. The behaviour of (*PRUNE:NAME) is not the same as (*MARK:NAME)(*PRUNE).
  7518. It is like (*MARK:NAME) in that the name is remembered for passing back
  7519. to the caller. However, (*SKIP:NAME) searches only for names set with
  7520. (*MARK), ignoring those set by other backtracking verbs.
  7521. (*SKIP)
  7522. This verb, when given without a name, is like (*PRUNE), except that if
  7523. the pattern is unanchored, the "bumpalong" advance is not to the next
  7524. character, but to the position in the subject where (*SKIP) was encoun-
  7525. tered. (*SKIP) signifies that whatever text was matched leading up to
  7526. it cannot be part of a successful match if there is a later mismatch.
  7527. Consider:
  7528. a+(*SKIP)b
  7529. If the subject is "aaaac...", after the first match attempt fails
  7530. (starting at the first character in the string), the starting point
  7531. skips on to start the next attempt at "c". Note that a possessive quan-
  7532. tifier does not have the same effect as this example; although it would
  7533. suppress backtracking during the first match attempt, the second at-
  7534. tempt would start at the second character instead of skipping on to
  7535. "c".
  7536. If (*SKIP) is used to specify a new starting position that is the same
  7537. as the starting position of the current match, or (by being inside a
  7538. lookbehind) earlier, the position specified by (*SKIP) is ignored, and
  7539. instead the normal "bumpalong" occurs.
  7540. (*SKIP:NAME)
  7541. When (*SKIP) has an associated name, its behaviour is modified. When
  7542. such a (*SKIP) is triggered, the previous path through the pattern is
  7543. searched for the most recent (*MARK) that has the same name. If one is
  7544. found, the "bumpalong" advance is to the subject position that corre-
  7545. sponds to that (*MARK) instead of to where (*SKIP) was encountered. If
  7546. no (*MARK) with a matching name is found, the (*SKIP) is ignored.
  7547. The search for a (*MARK) name uses the normal backtracking mechanism,
  7548. which means that it does not see (*MARK) settings that are inside
  7549. atomic groups or assertions, because they are never re-entered by back-
  7550. tracking. Compare the following pcre2test examples:
  7551. re> /a(?>(*MARK:X))(*SKIP:X)(*F)|(.)/
  7552. data: abc
  7553. 0: a
  7554. 1: a
  7555. data:
  7556. re> /a(?:(*MARK:X))(*SKIP:X)(*F)|(.)/
  7557. data: abc
  7558. 0: b
  7559. 1: b
  7560. In the first example, the (*MARK) setting is in an atomic group, so it
  7561. is not seen when (*SKIP:X) triggers, causing the (*SKIP) to be ignored.
  7562. This allows the second branch of the pattern to be tried at the first
  7563. character position. In the second example, the (*MARK) setting is not
  7564. in an atomic group. This allows (*SKIP:X) to find the (*MARK) when it
  7565. backtracks, and this causes a new matching attempt to start at the sec-
  7566. ond character. This time, the (*MARK) is never seen because "a" does
  7567. not match "b", so the matcher immediately jumps to the second branch of
  7568. the pattern.
  7569. Note that (*SKIP:NAME) searches only for names set by (*MARK:NAME). It
  7570. ignores names that are set by other backtracking verbs.
  7571. (*THEN) or (*THEN:NAME)
  7572. This verb causes a skip to the next innermost alternative when back-
  7573. tracking reaches it. That is, it cancels any further backtracking
  7574. within the current alternative. Its name comes from the observation
  7575. that it can be used for a pattern-based if-then-else block:
  7576. ( COND1 (*THEN) FOO | COND2 (*THEN) BAR | COND3 (*THEN) BAZ ) ...
  7577. If the COND1 pattern matches, FOO is tried (and possibly further items
  7578. after the end of the group if FOO succeeds); on failure, the matcher
  7579. skips to the second alternative and tries COND2, without backtracking
  7580. into COND1. If that succeeds and BAR fails, COND3 is tried. If subse-
  7581. quently BAZ fails, there are no more alternatives, so there is a back-
  7582. track to whatever came before the entire group. If (*THEN) is not in-
  7583. side an alternation, it acts like (*PRUNE).
  7584. The behaviour of (*THEN:NAME) is not the same as (*MARK:NAME)(*THEN).
  7585. It is like (*MARK:NAME) in that the name is remembered for passing back
  7586. to the caller. However, (*SKIP:NAME) searches only for names set with
  7587. (*MARK), ignoring those set by other backtracking verbs.
  7588. A group that does not contain a | character is just a part of the en-
  7589. closing alternative; it is not a nested alternation with only one al-
  7590. ternative. The effect of (*THEN) extends beyond such a group to the en-
  7591. closing alternative. Consider this pattern, where A, B, etc. are com-
  7592. plex pattern fragments that do not contain any | characters at this
  7593. level:
  7594. A (B(*THEN)C) | D
  7595. If A and B are matched, but there is a failure in C, matching does not
  7596. backtrack into A; instead it moves to the next alternative, that is, D.
  7597. However, if the group containing (*THEN) is given an alternative, it
  7598. behaves differently:
  7599. A (B(*THEN)C | (*FAIL)) | D
  7600. The effect of (*THEN) is now confined to the inner group. After a fail-
  7601. ure in C, matching moves to (*FAIL), which causes the whole group to
  7602. fail because there are no more alternatives to try. In this case,
  7603. matching does backtrack into A.
  7604. Note that a conditional group is not considered as having two alterna-
  7605. tives, because only one is ever used. In other words, the | character
  7606. in a conditional group has a different meaning. Ignoring white space,
  7607. consider:
  7608. ^.*? (?(?=a) a | b(*THEN)c )
  7609. If the subject is "ba", this pattern does not match. Because .*? is un-
  7610. greedy, it initially matches zero characters. The condition (?=a) then
  7611. fails, the character "b" is matched, but "c" is not. At this point,
  7612. matching does not backtrack to .*? as might perhaps be expected from
  7613. the presence of the | character. The conditional group is part of the
  7614. single alternative that comprises the whole pattern, and so the match
  7615. fails. (If there was a backtrack into .*?, allowing it to match "b",
  7616. the match would succeed.)
  7617. The verbs just described provide four different "strengths" of control
  7618. when subsequent matching fails. (*THEN) is the weakest, carrying on the
  7619. match at the next alternative. (*PRUNE) comes next, failing the match
  7620. at the current starting position, but allowing an advance to the next
  7621. character (for an unanchored pattern). (*SKIP) is similar, except that
  7622. the advance may be more than one character. (*COMMIT) is the strongest,
  7623. causing the entire match to fail.
  7624. More than one backtracking verb
  7625. If more than one backtracking verb is present in a pattern, the one
  7626. that is backtracked onto first acts. For example, consider this pat-
  7627. tern, where A, B, etc. are complex pattern fragments:
  7628. (A(*COMMIT)B(*THEN)C|ABD)
  7629. If A matches but B fails, the backtrack to (*COMMIT) causes the entire
  7630. match to fail. However, if A and B match, but C fails, the backtrack to
  7631. (*THEN) causes the next alternative (ABD) to be tried. This behaviour
  7632. is consistent, but is not always the same as Perl's. It means that if
  7633. two or more backtracking verbs appear in succession, all but the last
  7634. of them has no effect. Consider this example:
  7635. ...(*COMMIT)(*PRUNE)...
  7636. If there is a matching failure to the right, backtracking onto (*PRUNE)
  7637. causes it to be triggered, and its action is taken. There can never be
  7638. a backtrack onto (*COMMIT).
  7639. Backtracking verbs in repeated groups
  7640. PCRE2 sometimes differs from Perl in its handling of backtracking verbs
  7641. in repeated groups. For example, consider:
  7642. /(a(*COMMIT)b)+ac/
  7643. If the subject is "abac", Perl matches unless its optimizations are
  7644. disabled, but PCRE2 always fails because the (*COMMIT) in the second
  7645. repeat of the group acts.
  7646. Backtracking verbs in assertions
  7647. (*FAIL) in any assertion has its normal effect: it forces an immediate
  7648. backtrack. The behaviour of the other backtracking verbs depends on
  7649. whether or not the assertion is standalone or acting as the condition
  7650. in a conditional group.
  7651. (*ACCEPT) in a standalone positive assertion causes the assertion to
  7652. succeed without any further processing; captured strings and a mark
  7653. name (if set) are retained. In a standalone negative assertion, (*AC-
  7654. CEPT) causes the assertion to fail without any further processing; cap-
  7655. tured substrings and any mark name are discarded.
  7656. If the assertion is a condition, (*ACCEPT) causes the condition to be
  7657. true for a positive assertion and false for a negative one; captured
  7658. substrings are retained in both cases.
  7659. The remaining verbs act only when a later failure causes a backtrack to
  7660. reach them. This means that, for the Perl-compatible assertions, their
  7661. effect is confined to the assertion, because Perl lookaround assertions
  7662. are atomic. A backtrack that occurs after such an assertion is complete
  7663. does not jump back into the assertion. Note in particular that a
  7664. (*MARK) name that is set in an assertion is not "seen" by an instance
  7665. of (*SKIP:NAME) later in the pattern.
  7666. PCRE2 now supports non-atomic positive assertions, as described in the
  7667. section entitled "Non-atomic assertions" above. These assertions must
  7668. be standalone (not used as conditions). They are not Perl-compatible.
  7669. For these assertions, a later backtrack does jump back into the asser-
  7670. tion, and therefore verbs such as (*COMMIT) can be triggered by back-
  7671. tracks from later in the pattern.
  7672. The effect of (*THEN) is not allowed to escape beyond an assertion. If
  7673. there are no more branches to try, (*THEN) causes a positive assertion
  7674. to be false, and a negative assertion to be true.
  7675. The other backtracking verbs are not treated specially if they appear
  7676. in a standalone positive assertion. In a conditional positive asser-
  7677. tion, backtracking (from within the assertion) into (*COMMIT), (*SKIP),
  7678. or (*PRUNE) causes the condition to be false. However, for both stand-
  7679. alone and conditional negative assertions, backtracking into (*COMMIT),
  7680. (*SKIP), or (*PRUNE) causes the assertion to be true, without consider-
  7681. ing any further alternative branches.
  7682. Backtracking verbs in subroutines
  7683. These behaviours occur whether or not the group is called recursively.
  7684. (*ACCEPT) in a group called as a subroutine causes the subroutine match
  7685. to succeed without any further processing. Matching then continues af-
  7686. ter the subroutine call. Perl documents this behaviour. Perl's treat-
  7687. ment of the other verbs in subroutines is different in some cases.
  7688. (*FAIL) in a group called as a subroutine has its normal effect: it
  7689. forces an immediate backtrack.
  7690. (*COMMIT), (*SKIP), and (*PRUNE) cause the subroutine match to fail
  7691. when triggered by being backtracked to in a group called as a subrou-
  7692. tine. There is then a backtrack at the outer level.
  7693. (*THEN), when triggered, skips to the next alternative in the innermost
  7694. enclosing group that has alternatives (its normal behaviour). However,
  7695. if there is no such group within the subroutine's group, the subroutine
  7696. match fails and there is a backtrack at the outer level.
  7697. SEE ALSO
  7698. pcre2api(3), pcre2callout(3), pcre2matching(3), pcre2syntax(3),
  7699. pcre2(3).
  7700. AUTHOR
  7701. Philip Hazel
  7702. Retired from University Computing Service
  7703. Cambridge, England.
  7704. REVISION
  7705. Last updated: 04 June 2024
  7706. Copyright (c) 1997-2024 University of Cambridge.
  7707. PCRE2 10.44 04 June 2024 PCRE2PATTERN(3)
  7708. ------------------------------------------------------------------------------
  7709. PCRE2PERFORM(3) Library Functions Manual PCRE2PERFORM(3)
  7710. NAME
  7711. PCRE2 - Perl-compatible regular expressions (revised API)
  7712. PCRE2 PERFORMANCE
  7713. Two aspects of performance are discussed below: memory usage and pro-
  7714. cessing time. The way you express your pattern as a regular expression
  7715. can affect both of them.
  7716. COMPILED PATTERN MEMORY USAGE
  7717. Patterns are compiled by PCRE2 into a reasonably efficient interpretive
  7718. code, so that most simple patterns do not use much memory for storing
  7719. the compiled version. However, there is one case where the memory usage
  7720. of a compiled pattern can be unexpectedly large. If a parenthesized
  7721. group has a quantifier with a minimum greater than 1 and/or a limited
  7722. maximum, the whole group is repeated in the compiled code. For example,
  7723. the pattern
  7724. (abc|def){2,4}
  7725. is compiled as if it were
  7726. (abc|def)(abc|def)((abc|def)(abc|def)?)?
  7727. (Technical aside: It is done this way so that backtrack points within
  7728. each of the repetitions can be independently maintained.)
  7729. For regular expressions whose quantifiers use only small numbers, this
  7730. is not usually a problem. However, if the numbers are large, and par-
  7731. ticularly if such repetitions are nested, the memory usage can become
  7732. an embarrassment. For example, the very simple pattern
  7733. ((ab){1,1000}c){1,3}
  7734. uses over 50KiB when compiled using the 8-bit library. When PCRE2 is
  7735. compiled with its default internal pointer size of two bytes, the size
  7736. limit on a compiled pattern is 65535 code units in the 8-bit and 16-bit
  7737. libraries, and this is reached with the above pattern if the outer rep-
  7738. etition is increased from 3 to 4. PCRE2 can be compiled to use larger
  7739. internal pointers and thus handle larger compiled patterns, but it is
  7740. better to try to rewrite your pattern to use less memory if you can.
  7741. One way of reducing the memory usage for such patterns is to make use
  7742. of PCRE2's "subroutine" facility. Re-writing the above pattern as
  7743. ((ab)(?2){0,999}c)(?1){0,2}
  7744. reduces the memory requirements to around 16KiB, and indeed it remains
  7745. under 20KiB even with the outer repetition increased to 100. However,
  7746. this kind of pattern is not always exactly equivalent, because any cap-
  7747. tures within subroutine calls are lost when the subroutine completes.
  7748. If this is not a problem, this kind of rewriting will allow you to
  7749. process patterns that PCRE2 cannot otherwise handle. The matching per-
  7750. formance of the two different versions of the pattern are roughly the
  7751. same. (This applies from release 10.30 - things were different in ear-
  7752. lier releases.)
  7753. STACK AND HEAP USAGE AT RUN TIME
  7754. From release 10.30, the interpretive (non-JIT) version of pcre2_match()
  7755. uses very little system stack at run time. In earlier releases recur-
  7756. sive function calls could use a great deal of stack, and this could
  7757. cause problems, but this usage has been eliminated. Backtracking posi-
  7758. tions are now explicitly remembered in memory frames controlled by the
  7759. code.
  7760. The size of each frame depends on the size of pointer variables and the
  7761. number of capturing parenthesized groups in the pattern being matched.
  7762. On a 64-bit system the frame size for a pattern with no captures is 128
  7763. bytes. For each capturing group the size increases by 16 bytes.
  7764. Until release 10.41, an initial 20KiB frames vector was allocated on
  7765. the system stack, but this still caused some issues for multi-thread
  7766. applications where each thread has a very small stack. From release
  7767. 10.41 backtracking memory frames are always held in heap memory. An
  7768. initial heap allocation is obtained the first time any match data block
  7769. is passed to pcre2_match(). This is remembered with the match data
  7770. block and re-used if that block is used for another match. It is freed
  7771. when the match data block itself is freed.
  7772. The size of the initial block is the larger of 20KiB or ten times the
  7773. pattern's frame size, unless the heap limit is less than this, in which
  7774. case the heap limit is used. If the initial block proves to be too
  7775. small during matching, it is replaced by a larger block, subject to the
  7776. heap limit. The heap limit is checked only when a new block is to be
  7777. allocated. Reducing the heap limit between calls to pcre2_match() with
  7778. the same match data block does not affect the saved block.
  7779. In contrast to pcre2_match(), pcre2_dfa_match() does use recursive
  7780. function calls, but only for processing atomic groups, lookaround as-
  7781. sertions, and recursion within the pattern. The original version of the
  7782. code used to allocate quite large internal workspace vectors on the
  7783. stack, which caused some problems for some patterns in environments
  7784. with small stacks. From release 10.32 the code for pcre2_dfa_match()
  7785. has been re-factored to use heap memory when necessary for internal
  7786. workspace when recursing, though recursive function calls are still
  7787. used.
  7788. The "match depth" parameter can be used to limit the depth of function
  7789. recursion, and the "match heap" parameter to limit heap memory in
  7790. pcre2_dfa_match().
  7791. PROCESSING TIME
  7792. Certain items in regular expression patterns are processed more effi-
  7793. ciently than others. It is more efficient to use a character class like
  7794. [aeiou] than a set of single-character alternatives such as
  7795. (a|e|i|o|u). In general, the simplest construction that provides the
  7796. required behaviour is usually the most efficient. Jeffrey Friedl's book
  7797. contains a lot of useful general discussion about optimizing regular
  7798. expressions for efficient performance. This document contains a few ob-
  7799. servations about PCRE2.
  7800. Using Unicode character properties (the \p, \P, and \X escapes) is
  7801. slow, because PCRE2 has to use a multi-stage table lookup whenever it
  7802. needs a character's property. If you can find an alternative pattern
  7803. that does not use character properties, it will probably be faster.
  7804. By default, the escape sequences \b, \d, \s, and \w, and the POSIX
  7805. character classes such as [:alpha:] do not use Unicode properties,
  7806. partly for backwards compatibility, and partly for performance reasons.
  7807. However, you can set the PCRE2_UCP option or start the pattern with
  7808. (*UCP) if you want Unicode character properties to be used. This can
  7809. double the matching time for items such as \d, when matched with
  7810. pcre2_match(); the performance loss is less with a DFA matching func-
  7811. tion, and in both cases there is not much difference for \b.
  7812. When a pattern begins with .* not in atomic parentheses, nor in paren-
  7813. theses that are the subject of a backreference, and the PCRE2_DOTALL
  7814. option is set, the pattern is implicitly anchored by PCRE2, since it
  7815. can match only at the start of a subject string. If the pattern has
  7816. multiple top-level branches, they must all be anchorable. The optimiza-
  7817. tion can be disabled by the PCRE2_NO_DOTSTAR_ANCHOR option, and is au-
  7818. tomatically disabled if the pattern contains (*PRUNE) or (*SKIP).
  7819. If PCRE2_DOTALL is not set, PCRE2 cannot make this optimization, be-
  7820. cause the dot metacharacter does not then match a newline, and if the
  7821. subject string contains newlines, the pattern may match from the char-
  7822. acter immediately following one of them instead of from the very start.
  7823. For example, the pattern
  7824. .*second
  7825. matches the subject "first\nand second" (where \n stands for a newline
  7826. character), with the match starting at the seventh character. In order
  7827. to do this, PCRE2 has to retry the match starting after every newline
  7828. in the subject.
  7829. If you are using such a pattern with subject strings that do not con-
  7830. tain newlines, the best performance is obtained by setting
  7831. PCRE2_DOTALL, or starting the pattern with ^.* or ^.*? to indicate ex-
  7832. plicit anchoring. That saves PCRE2 from having to scan along the sub-
  7833. ject looking for a newline to restart at.
  7834. Beware of patterns that contain nested indefinite repeats. These can
  7835. take a long time to run when applied to a string that does not match.
  7836. Consider the pattern fragment
  7837. ^(a+)*
  7838. This can match "aaaa" in 16 different ways, and this number increases
  7839. very rapidly as the string gets longer. (The * repeat can match 0, 1,
  7840. 2, 3, or 4 times, and for each of those cases other than 0 or 4, the +
  7841. repeats can match different numbers of times.) When the remainder of
  7842. the pattern is such that the entire match is going to fail, PCRE2 has
  7843. in principle to try every possible variation, and this can take an ex-
  7844. tremely long time, even for relatively short strings.
  7845. An optimization catches some of the more simple cases such as
  7846. (a+)*b
  7847. where a literal character follows. Before embarking on the standard
  7848. matching procedure, PCRE2 checks that there is a "b" later in the sub-
  7849. ject string, and if there is not, it fails the match immediately. How-
  7850. ever, when there is no following literal this optimization cannot be
  7851. used. You can see the difference by comparing the behaviour of
  7852. (a+)*\d
  7853. with the pattern above. The former gives a failure almost instantly
  7854. when applied to a whole line of "a" characters, whereas the latter
  7855. takes an appreciable time with strings longer than about 20 characters.
  7856. In many cases, the solution to this kind of performance issue is to use
  7857. an atomic group or a possessive quantifier. This can often reduce mem-
  7858. ory requirements as well. As another example, consider this pattern:
  7859. ([^<]|<(?!inet))+
  7860. It matches from wherever it starts until it encounters "<inet" or the
  7861. end of the data, and is the kind of pattern that might be used when
  7862. processing an XML file. Each iteration of the outer parentheses matches
  7863. either one character that is not "<" or a "<" that is not followed by
  7864. "inet". However, each time a parenthesis is processed, a backtracking
  7865. position is passed, so this formulation uses a memory frame for each
  7866. matched character. For a long string, a lot of memory is required. Con-
  7867. sider now this rewritten pattern, which matches exactly the same
  7868. strings:
  7869. ([^<]++|<(?!inet))+
  7870. This runs much faster, because sequences of characters that do not con-
  7871. tain "<" are "swallowed" in one item inside the parentheses, and a pos-
  7872. sessive quantifier is used to stop any backtracking into the runs of
  7873. non-"<" characters. This version also uses a lot less memory because
  7874. entry to a new set of parentheses happens only when a "<" character
  7875. that is not followed by "inet" is encountered (and we assume this is
  7876. relatively rare).
  7877. This example shows that one way of optimizing performance when matching
  7878. long subject strings is to write repeated parenthesized subpatterns to
  7879. match more than one character whenever possible.
  7880. SETTING RESOURCE LIMITS
  7881. You can set limits on the amount of processing that takes place when
  7882. matching, and on the amount of heap memory that is used. The default
  7883. values of the limits are very large, and unlikely ever to operate. They
  7884. can be changed when PCRE2 is built, and they can also be set when
  7885. pcre2_match() or pcre2_dfa_match() is called. For details of these in-
  7886. terfaces, see the pcre2build documentation and the section entitled
  7887. "The match context" in the pcre2api documentation.
  7888. The pcre2test test program has a modifier called "find_limits" which,
  7889. if applied to a subject line, causes it to find the smallest limits
  7890. that allow a pattern to match. This is done by repeatedly matching with
  7891. different limits.
  7892. AUTHOR
  7893. Philip Hazel
  7894. Retired from University Computing Service
  7895. Cambridge, England.
  7896. REVISION
  7897. Last updated: 27 July 2022
  7898. Copyright (c) 1997-2022 University of Cambridge.
  7899. PCRE2 10.41 27 July 2022 PCRE2PERFORM(3)
  7900. ------------------------------------------------------------------------------
  7901. PCRE2POSIX(3) Library Functions Manual PCRE2POSIX(3)
  7902. NAME
  7903. PCRE2 - Perl-compatible regular expressions (revised API)
  7904. SYNOPSIS
  7905. #include <pcre2posix.h>
  7906. int pcre2_regcomp(regex_t *preg, const char *pattern,
  7907. int cflags);
  7908. int pcre2_regexec(const regex_t *preg, const char *string,
  7909. size_t nmatch, regmatch_t pmatch[], int eflags);
  7910. size_t pcre2_regerror(int errcode, const regex_t *preg,
  7911. char *errbuf, size_t errbuf_size);
  7912. void pcre2_regfree(regex_t *preg);
  7913. DESCRIPTION
  7914. This set of functions provides a POSIX-style API for the PCRE2 regular
  7915. expression 8-bit library. There are no POSIX-style wrappers for PCRE2's
  7916. 16-bit and 32-bit libraries. See the pcre2api documentation for a de-
  7917. scription of PCRE2's native API, which contains much additional func-
  7918. tionality.
  7919. IMPORTANT NOTE: The functions described here are NOT thread-safe, and
  7920. should not be used in multi-threaded applications. They are also lim-
  7921. ited to processing subjects that are not bigger than 2GB. Use the na-
  7922. tive API instead.
  7923. These functions are wrapper functions that ultimately call the PCRE2
  7924. native API. Their prototypes are defined in the pcre2posix.h header
  7925. file, and they all have unique names starting with pcre2_. However, the
  7926. pcre2posix.h header also contains macro definitions that convert the
  7927. standard POSIX names such regcomp() into pcre2_regcomp() etc. This
  7928. means that a program can use the usual POSIX names without running the
  7929. risk of accidentally linking with POSIX functions from a different li-
  7930. brary.
  7931. On Unix-like systems the PCRE2 POSIX library is called libpcre2-posix,
  7932. so can be accessed by adding -lpcre2-posix to the command for linking
  7933. an application. Because the POSIX functions call the native ones, it is
  7934. also necessary to add -lpcre2-8.
  7935. On Windows systems, if you are linking to a DLL version of the library,
  7936. it is recommended that PCRE2POSIX_SHARED is defined before including
  7937. the pcre2posix.h header, as it will allow for a more efficient way to
  7938. invoke the functions by adding the __declspec(dllimport) decorator.
  7939. Although they were not defined as prototypes in pcre2posix.h, releases
  7940. 10.33 to 10.36 of the library contained functions with the POSIX names
  7941. regcomp() etc. These simply passed their arguments to the PCRE2 func-
  7942. tions. These functions were provided for backwards compatibility with
  7943. earlier versions of PCRE2, which had only POSIX names. However, this
  7944. has proved troublesome in situations where a program links with several
  7945. libraries, some of which use PCRE2's POSIX interface while others use
  7946. the real POSIX functions. For this reason, the POSIX names have been
  7947. removed since release 10.37.
  7948. Calling the header file pcre2posix.h avoids any conflict with other
  7949. POSIX libraries. It can, of course, be renamed or aliased as regex.h,
  7950. which is the "correct" name, if there is no clash. It provides two
  7951. structure types, regex_t for compiled internal forms, and regmatch_t
  7952. for returning captured substrings. It also defines some constants whose
  7953. names start with "REG_"; these are used for setting options and identi-
  7954. fying error codes.
  7955. USING THE POSIX FUNCTIONS
  7956. Note that these functions are just POSIX-style wrappers for PCRE2's na-
  7957. tive API. They do not give POSIX regular expression behaviour, and
  7958. they are not thread-safe or even POSIX compatible.
  7959. Those POSIX option bits that can reasonably be mapped to PCRE2 native
  7960. options have been implemented. In addition, the option REG_EXTENDED is
  7961. defined with the value zero. This has no effect, but since programs
  7962. that are written to the POSIX interface often use it, this makes it
  7963. easier to slot in PCRE2 as a replacement library. Other POSIX options
  7964. are not even defined.
  7965. There are also some options that are not defined by POSIX. These have
  7966. been added at the request of users who want to make use of certain
  7967. PCRE2-specific features via the POSIX calling interface or to add BSD
  7968. or GNU functionality.
  7969. When PCRE2 is called via these functions, it is only the API that is
  7970. POSIX-like in style. The syntax and semantics of the regular expres-
  7971. sions themselves are still those of Perl, subject to the setting of
  7972. various PCRE2 options, as described below. "POSIX-like in style" means
  7973. that the API approximates to the POSIX definition; it is not fully
  7974. POSIX-compatible, and in multi-unit encoding domains it is probably
  7975. even less compatible.
  7976. The descriptions below use the actual names of the functions, but, as
  7977. described above, the standard POSIX names (without the pcre2_ prefix)
  7978. may also be used.
  7979. COMPILING A PATTERN
  7980. The function pcre2_regcomp() is called to compile a pattern into an in-
  7981. ternal form. By default, the pattern is a C string terminated by a bi-
  7982. nary zero (but see REG_PEND below). The preg argument is a pointer to a
  7983. regex_t structure that is used as a base for storing information about
  7984. the compiled regular expression. It is also used for input when
  7985. REG_PEND is set. The regex_t structure used by pcre2_regcomp() is de-
  7986. fined in pcre2posix.h and is not the same as the structure used by
  7987. other libraries that provide POSIX-style matching.
  7988. The argument cflags is either zero, or contains one or more of the bits
  7989. defined by the following macros:
  7990. REG_DOTALL
  7991. The PCRE2_DOTALL option is set when the regular expression is passed
  7992. for compilation to the native function. Note that REG_DOTALL is not
  7993. part of the POSIX standard.
  7994. REG_ICASE
  7995. The PCRE2_CASELESS option is set when the regular expression is passed
  7996. for compilation to the native function.
  7997. REG_NEWLINE
  7998. The PCRE2_MULTILINE option is set when the regular expression is passed
  7999. for compilation to the native function. Note that this does not mimic
  8000. the defined POSIX behaviour for REG_NEWLINE (see the following sec-
  8001. tion).
  8002. REG_NOSPEC
  8003. The PCRE2_LITERAL option is set when the regular expression is passed
  8004. for compilation to the native function. This disables all meta charac-
  8005. ters in the pattern, causing it to be treated as a literal string. The
  8006. only other options that are allowed with REG_NOSPEC are REG_ICASE,
  8007. REG_NOSUB, REG_PEND, and REG_UTF. Note that REG_NOSPEC is not part of
  8008. the POSIX standard.
  8009. REG_NOSUB
  8010. When a pattern that is compiled with this flag is passed to
  8011. pcre2_regexec() for matching, the nmatch and pmatch arguments are ig-
  8012. nored, and no captured strings are returned. Versions of the PCRE li-
  8013. brary prior to 10.22 used to set the PCRE2_NO_AUTO_CAPTURE compile op-
  8014. tion, but this no longer happens because it disables the use of back-
  8015. references.
  8016. REG_PEND
  8017. If this option is set, the reg_endp field in the preg structure (which
  8018. has the type const char *) must be set to point to the character beyond
  8019. the end of the pattern before calling pcre2_regcomp(). The pattern it-
  8020. self may now contain binary zeros, which are treated as data charac-
  8021. ters. Without REG_PEND, a binary zero terminates the pattern and the
  8022. re_endp field is ignored. This is a GNU extension to the POSIX standard
  8023. and should be used with caution in software intended to be portable to
  8024. other systems.
  8025. REG_UCP
  8026. The PCRE2_UCP option is set when the regular expression is passed for
  8027. compilation to the native function. This causes PCRE2 to use Unicode
  8028. properties when matching \d, \w, etc., instead of just recognizing
  8029. ASCII values. Note that REG_UCP is not part of the POSIX standard.
  8030. REG_UNGREEDY
  8031. The PCRE2_UNGREEDY option is set when the regular expression is passed
  8032. for compilation to the native function. Note that REG_UNGREEDY is not
  8033. part of the POSIX standard.
  8034. REG_UTF
  8035. The PCRE2_UTF option is set when the regular expression is passed for
  8036. compilation to the native function. This causes the pattern itself and
  8037. all data strings used for matching it to be treated as UTF-8 strings.
  8038. Note that REG_UTF is not part of the POSIX standard.
  8039. In the absence of these flags, no options are passed to the native
  8040. function. This means that the regex is compiled with PCRE2 default se-
  8041. mantics. In particular, the way it handles newline characters in the
  8042. subject string is the Perl way, not the POSIX way. Note that setting
  8043. PCRE2_MULTILINE has only some of the effects specified for REG_NEWLINE.
  8044. It does not affect the way newlines are matched by the dot metacharac-
  8045. ter (they are not) or by a negative class such as [^a] (they are).
  8046. The yield of pcre2_regcomp() is zero on success, and non-zero other-
  8047. wise. The preg structure is filled in on success, and one other member
  8048. of the structure (as well as re_endp) is public: re_nsub contains the
  8049. number of capturing subpatterns in the regular expression. Various er-
  8050. ror codes are defined in the header file.
  8051. NOTE: If the yield of pcre2_regcomp() is non-zero, you must not attempt
  8052. to use the contents of the preg structure. If, for example, you pass it
  8053. to pcre2_regexec(), the result is undefined and your program is likely
  8054. to crash.
  8055. MATCHING NEWLINE CHARACTERS
  8056. This area is not simple, because POSIX and Perl take different views of
  8057. things. It is not possible to get PCRE2 to obey POSIX semantics, but
  8058. then PCRE2 was never intended to be a POSIX engine. The following table
  8059. lists the different possibilities for matching newline characters in
  8060. Perl and PCRE2:
  8061. Default Change with
  8062. . matches newline no PCRE2_DOTALL
  8063. newline matches [^a] yes not changeable
  8064. $ matches \n at end yes PCRE2_DOLLAR_ENDONLY
  8065. $ matches \n in middle no PCRE2_MULTILINE
  8066. ^ matches \n in middle no PCRE2_MULTILINE
  8067. This is the equivalent table for a POSIX-compatible pattern matcher:
  8068. Default Change with
  8069. . matches newline yes REG_NEWLINE
  8070. newline matches [^a] yes REG_NEWLINE
  8071. $ matches \n at end no REG_NEWLINE
  8072. $ matches \n in middle no REG_NEWLINE
  8073. ^ matches \n in middle no REG_NEWLINE
  8074. This behaviour is not what happens when PCRE2 is called via its POSIX
  8075. API. By default, PCRE2's behaviour is the same as Perl's, except that
  8076. there is no equivalent for PCRE2_DOLLAR_ENDONLY in Perl. In both PCRE2
  8077. and Perl, there is no way to stop newline from matching [^a].
  8078. Default POSIX newline handling can be obtained by setting PCRE2_DOTALL
  8079. and PCRE2_DOLLAR_ENDONLY when calling pcre2_compile() directly, but
  8080. there is no way to make PCRE2 behave exactly as for the REG_NEWLINE ac-
  8081. tion. When using the POSIX API, passing REG_NEWLINE to PCRE2's
  8082. pcre2_regcomp() function causes PCRE2_MULTILINE to be passed to
  8083. pcre2_compile(), and REG_DOTALL passes PCRE2_DOTALL. There is no way to
  8084. pass PCRE2_DOLLAR_ENDONLY.
  8085. MATCHING A PATTERN
  8086. The function pcre2_regexec() is called to match a compiled pattern preg
  8087. against a given string, which is by default terminated by a zero byte
  8088. (but see REG_STARTEND below), subject to the options in eflags. These
  8089. can be:
  8090. REG_NOTBOL
  8091. The PCRE2_NOTBOL option is set when calling the underlying PCRE2 match-
  8092. ing function.
  8093. REG_NOTEMPTY
  8094. The PCRE2_NOTEMPTY option is set when calling the underlying PCRE2
  8095. matching function. Note that REG_NOTEMPTY is not part of the POSIX
  8096. standard. However, setting this option can give more POSIX-like behav-
  8097. iour in some situations.
  8098. REG_NOTEOL
  8099. The PCRE2_NOTEOL option is set when calling the underlying PCRE2 match-
  8100. ing function.
  8101. REG_STARTEND
  8102. When this option is set, the subject string starts at string +
  8103. pmatch[0].rm_so and ends at string + pmatch[0].rm_eo, which should
  8104. point to the first character beyond the string. There may be binary ze-
  8105. ros within the subject string, and indeed, using REG_STARTEND is the
  8106. only way to pass a subject string that contains a binary zero.
  8107. Whatever the value of pmatch[0].rm_so, the offsets of the matched
  8108. string and any captured substrings are still given relative to the
  8109. start of string itself. (Before PCRE2 release 10.30 these were given
  8110. relative to string + pmatch[0].rm_so, but this differs from other im-
  8111. plementations.)
  8112. This is a BSD extension, compatible with but not specified by IEEE
  8113. Standard 1003.2 (POSIX.2), and should be used with caution in software
  8114. intended to be portable to other systems. Note that a non-zero rm_so
  8115. does not imply REG_NOTBOL; REG_STARTEND affects only the location and
  8116. length of the string, not how it is matched. Setting REG_STARTEND and
  8117. passing pmatch as NULL are mutually exclusive; the error REG_INVARG is
  8118. returned.
  8119. If the pattern was compiled with the REG_NOSUB flag, no data about any
  8120. matched strings is returned. The nmatch and pmatch arguments of
  8121. pcre2_regexec() are ignored (except possibly as input for REG_STAR-
  8122. TEND).
  8123. The value of nmatch may be zero, and the value pmatch may be NULL (un-
  8124. less REG_STARTEND is set); in both these cases no data about any
  8125. matched strings is returned.
  8126. Otherwise, the portion of the string that was matched, and also any
  8127. captured substrings, are returned via the pmatch argument, which points
  8128. to an array of nmatch structures of type regmatch_t, containing the
  8129. members rm_so and rm_eo. These contain the byte offset to the first
  8130. character of each substring and the offset to the first character after
  8131. the end of each substring, respectively. The 0th element of the vector
  8132. relates to the entire portion of string that was matched; subsequent
  8133. elements relate to the capturing subpatterns of the regular expression.
  8134. Unused entries in the array have both structure members set to -1.
  8135. regmatch_t as well as the regoff_t typedef it uses are defined in
  8136. pcre2posix.h and are not warranted to have the same size or layout as
  8137. other similarly named types from other libraries that provide POSIX-
  8138. style matching.
  8139. A successful match yields a zero return; various error codes are de-
  8140. fined in the header file, of which REG_NOMATCH is the "expected" fail-
  8141. ure code.
  8142. ERROR MESSAGES
  8143. The pcre2_regerror() function maps a non-zero errorcode from either
  8144. pcre2_regcomp() or pcre2_regexec() to a printable message. If preg is
  8145. not NULL, the error should have arisen from the use of that structure.
  8146. A message terminated by a binary zero is placed in errbuf. If the
  8147. buffer is too short, only the first errbuf_size - 1 characters of the
  8148. error message are used. The yield of the function is the size of buffer
  8149. needed to hold the whole message, including the terminating zero. This
  8150. value is greater than errbuf_size if the message was truncated.
  8151. MEMORY USAGE
  8152. Compiling a regular expression causes memory to be allocated and asso-
  8153. ciated with the preg structure. The function pcre2_regfree() frees all
  8154. such memory, after which preg may no longer be used as a compiled ex-
  8155. pression.
  8156. AUTHOR
  8157. Philip Hazel
  8158. Retired from University Computing Service
  8159. Cambridge, England.
  8160. REVISION
  8161. Last updated: 19 January 2024
  8162. Copyright (c) 1997-2024 University of Cambridge.
  8163. PCRE2 10.43 19 January 2024 PCRE2POSIX(3)
  8164. ------------------------------------------------------------------------------
  8165. PCRE2SAMPLE(3) Library Functions Manual PCRE2SAMPLE(3)
  8166. NAME
  8167. PCRE2 - Perl-compatible regular expressions (revised API)
  8168. PCRE2 SAMPLE PROGRAM
  8169. A simple, complete demonstration program to get you started with using
  8170. PCRE2 is supplied in the file pcre2demo.c in the src directory in the
  8171. PCRE2 distribution. A listing of this program is given in the pcre2demo
  8172. documentation. If you do not have a copy of the PCRE2 distribution, you
  8173. can save this listing to re-create the contents of pcre2demo.c.
  8174. The demonstration program compiles the regular expression that is its
  8175. first argument, and matches it against the subject string in its second
  8176. argument. No PCRE2 options are set, and default character tables are
  8177. used. If matching succeeds, the program outputs the portion of the sub-
  8178. ject that matched, together with the contents of any captured sub-
  8179. strings.
  8180. If the -g option is given on the command line, the program then goes on
  8181. to check for further matches of the same regular expression in the same
  8182. subject string. The logic is a little bit tricky because of the possi-
  8183. bility of matching an empty string. Comments in the code explain what
  8184. is going on.
  8185. The code in pcre2demo.c is an 8-bit program that uses the PCRE2 8-bit
  8186. library. It handles strings and characters that are stored in 8-bit
  8187. code units. By default, one character corresponds to one code unit,
  8188. but if the pattern starts with "(*UTF)", both it and the subject are
  8189. treated as UTF-8 strings, where characters may occupy multiple code
  8190. units.
  8191. If PCRE2 is installed in the standard include and library directories
  8192. for your operating system, you should be able to compile the demonstra-
  8193. tion program using a command like this:
  8194. cc -o pcre2demo pcre2demo.c -lpcre2-8
  8195. If PCRE2 is installed elsewhere, you may need to add additional options
  8196. to the command line. For example, on a Unix-like system that has PCRE2
  8197. installed in /usr/local, you can compile the demonstration program us-
  8198. ing a command like this:
  8199. cc -o pcre2demo -I/usr/local/include pcre2demo.c \
  8200. -L/usr/local/lib -lpcre2-8
  8201. Once you have built the demonstration program, you can run simple tests
  8202. like this:
  8203. ./pcre2demo 'cat|dog' 'the cat sat on the mat'
  8204. ./pcre2demo -g 'cat|dog' 'the dog sat on the cat'
  8205. Note that there is a much more comprehensive test program, called
  8206. pcre2test, which supports many more facilities for testing regular ex-
  8207. pressions using all three PCRE2 libraries (8-bit, 16-bit, and 32-bit,
  8208. though not all three need be installed). The pcre2demo program is pro-
  8209. vided as a relatively simple coding example.
  8210. If you try to run pcre2demo when PCRE2 is not installed in the standard
  8211. library directory, you may get an error like this on some operating
  8212. systems (e.g. Solaris):
  8213. ld.so.1: pcre2demo: fatal: libpcre2-8.so.0: open failed: No such file
  8214. or directory
  8215. This is caused by the way shared library support works on those sys-
  8216. tems. You need to add
  8217. -R/usr/local/lib
  8218. (for example) to the compile command to get round this problem.
  8219. AUTHOR
  8220. Philip Hazel
  8221. Retired from University Computing Service
  8222. Cambridge, England.
  8223. REVISION
  8224. Last updated: 02 February 2016
  8225. Copyright (c) 1997-2016 University of Cambridge.
  8226. PCRE2 10.22 02 February 2016 PCRE2SAMPLE(3)
  8227. ------------------------------------------------------------------------------
  8228. PCRE2SERIALIZE(3) Library Functions Manual PCRE2SERIALIZE(3)
  8229. NAME
  8230. PCRE2 - Perl-compatible regular expressions (revised API)
  8231. SAVING AND RE-USING PRECOMPILED PCRE2 PATTERNS
  8232. int32_t pcre2_serialize_decode(pcre2_code **codes,
  8233. int32_t number_of_codes, const uint8_t *bytes,
  8234. pcre2_general_context *gcontext);
  8235. int32_t pcre2_serialize_encode(const pcre2_code **codes,
  8236. int32_t number_of_codes, uint8_t **serialized_bytes,
  8237. PCRE2_SIZE *serialized_size, pcre2_general_context *gcontext);
  8238. void pcre2_serialize_free(uint8_t *bytes);
  8239. int32_t pcre2_serialize_get_number_of_codes(const uint8_t *bytes);
  8240. If you are running an application that uses a large number of regular
  8241. expression patterns, it may be useful to store them in a precompiled
  8242. form instead of having to compile them every time the application is
  8243. run. However, if you are using the just-in-time optimization feature,
  8244. it is not possible to save and reload the JIT data, because it is posi-
  8245. tion-dependent. The host on which the patterns are reloaded must be
  8246. running the same version of PCRE2, with the same code unit width, and
  8247. must also have the same endianness, pointer width and PCRE2_SIZE type.
  8248. For example, patterns compiled on a 32-bit system using PCRE2's 16-bit
  8249. library cannot be reloaded on a 64-bit system, nor can they be reloaded
  8250. using the 8-bit library.
  8251. Note that "serialization" in PCRE2 does not convert compiled patterns
  8252. to an abstract format like Java or .NET serialization. The serialized
  8253. output is really just a bytecode dump, which is why it can only be re-
  8254. loaded in the same environment as the one that created it. Hence the
  8255. restrictions mentioned above. Applications that are not statically
  8256. linked with a fixed version of PCRE2 must be prepared to recompile pat-
  8257. terns from their sources, in order to be immune to PCRE2 upgrades.
  8258. SECURITY CONCERNS
  8259. The facility for saving and restoring compiled patterns is intended for
  8260. use within individual applications. As such, the data supplied to
  8261. pcre2_serialize_decode() is expected to be trusted data, not data from
  8262. arbitrary external sources. There is only some simple consistency
  8263. checking, not complete validation of what is being re-loaded. Corrupted
  8264. data may cause undefined results. For example, if the length field of a
  8265. pattern in the serialized data is corrupted, the deserializing code may
  8266. read beyond the end of the byte stream that is passed to it.
  8267. SAVING COMPILED PATTERNS
  8268. Before compiled patterns can be saved they must be serialized, which in
  8269. PCRE2 means converting the pattern to a stream of bytes. A single byte
  8270. stream may contain any number of compiled patterns, but they must all
  8271. use the same character tables. A single copy of the tables is included
  8272. in the byte stream (its size is 1088 bytes). For more details of char-
  8273. acter tables, see the section on locale support in the pcre2api docu-
  8274. mentation.
  8275. The function pcre2_serialize_encode() creates a serialized byte stream
  8276. from a list of compiled patterns. Its first two arguments specify the
  8277. list, being a pointer to a vector of pointers to compiled patterns, and
  8278. the length of the vector. The third and fourth arguments point to vari-
  8279. ables which are set to point to the created byte stream and its length,
  8280. respectively. The final argument is a pointer to a general context,
  8281. which can be used to specify custom memory management functions. If
  8282. this argument is NULL, malloc() is used to obtain memory for the byte
  8283. stream. The yield of the function is the number of serialized patterns,
  8284. or one of the following negative error codes:
  8285. PCRE2_ERROR_BADDATA the number of patterns is zero or less
  8286. PCRE2_ERROR_BADMAGIC mismatch of id bytes in one of the patterns
  8287. PCRE2_ERROR_NOMEMORY memory allocation failed
  8288. PCRE2_ERROR_MIXEDTABLES the patterns do not all use the same tables
  8289. PCRE2_ERROR_NULL the 1st, 3rd, or 4th argument is NULL
  8290. PCRE2_ERROR_BADMAGIC means either that a pattern's code has been cor-
  8291. rupted, or that a slot in the vector does not point to a compiled pat-
  8292. tern.
  8293. Once a set of patterns has been serialized you can save the data in any
  8294. appropriate manner. Here is sample code that compiles two patterns and
  8295. writes them to a file. It assumes that the variable fd refers to a file
  8296. that is open for output. The error checking that should be present in a
  8297. real application has been omitted for simplicity.
  8298. int errorcode;
  8299. uint8_t *bytes;
  8300. PCRE2_SIZE erroroffset;
  8301. PCRE2_SIZE bytescount;
  8302. pcre2_code *list_of_codes[2];
  8303. list_of_codes[0] = pcre2_compile("first pattern",
  8304. PCRE2_ZERO_TERMINATED, 0, &errorcode, &erroroffset, NULL);
  8305. list_of_codes[1] = pcre2_compile("second pattern",
  8306. PCRE2_ZERO_TERMINATED, 0, &errorcode, &erroroffset, NULL);
  8307. errorcode = pcre2_serialize_encode(list_of_codes, 2, &bytes,
  8308. &bytescount, NULL);
  8309. errorcode = fwrite(bytes, 1, bytescount, fd);
  8310. Note that the serialized data is binary data that may contain any of
  8311. the 256 possible byte values. On systems that make a distinction be-
  8312. tween binary and non-binary data, be sure that the file is opened for
  8313. binary output.
  8314. Serializing a set of patterns leaves the original data untouched, so
  8315. they can still be used for matching. Their memory must eventually be
  8316. freed in the usual way by calling pcre2_code_free(). When you have fin-
  8317. ished with the byte stream, it too must be freed by calling pcre2_seri-
  8318. alize_free(). If this function is called with a NULL argument, it re-
  8319. turns immediately without doing anything.
  8320. RE-USING PRECOMPILED PATTERNS
  8321. In order to re-use a set of saved patterns you must first make the se-
  8322. rialized byte stream available in main memory (for example, by reading
  8323. from a file). The management of this memory block is up to the applica-
  8324. tion. You can use the pcre2_serialize_get_number_of_codes() function to
  8325. find out how many compiled patterns are in the serialized data without
  8326. actually decoding the patterns:
  8327. uint8_t *bytes = <serialized data>;
  8328. int32_t number_of_codes = pcre2_serialize_get_number_of_codes(bytes);
  8329. The pcre2_serialize_decode() function reads a byte stream and recreates
  8330. the compiled patterns in new memory blocks, setting pointers to them in
  8331. a vector. The first two arguments are a pointer to a suitable vector
  8332. and its length, and the third argument points to a byte stream. The fi-
  8333. nal argument is a pointer to a general context, which can be used to
  8334. specify custom memory management functions for the decoded patterns. If
  8335. this argument is NULL, malloc() and free() are used. After deserializa-
  8336. tion, the byte stream is no longer needed and can be discarded.
  8337. pcre2_code *list_of_codes[2];
  8338. uint8_t *bytes = <serialized data>;
  8339. int32_t number_of_codes =
  8340. pcre2_serialize_decode(list_of_codes, 2, bytes, NULL);
  8341. If the vector is not large enough for all the patterns in the byte
  8342. stream, it is filled with those that fit, and the remainder are ig-
  8343. nored. The yield of the function is the number of decoded patterns, or
  8344. one of the following negative error codes:
  8345. PCRE2_ERROR_BADDATA second argument is zero or less
  8346. PCRE2_ERROR_BADMAGIC mismatch of id bytes in the data
  8347. PCRE2_ERROR_BADMODE mismatch of code unit size or PCRE2 version
  8348. PCRE2_ERROR_BADSERIALIZEDDATA other sanity check failure
  8349. PCRE2_ERROR_MEMORY memory allocation failed
  8350. PCRE2_ERROR_NULL first or third argument is NULL
  8351. PCRE2_ERROR_BADMAGIC may mean that the data is corrupt, or that it was
  8352. compiled on a system with different endianness.
  8353. Decoded patterns can be used for matching in the usual way, and must be
  8354. freed by calling pcre2_code_free(). However, be aware that there is a
  8355. potential race issue if you are using multiple patterns that were de-
  8356. coded from a single byte stream in a multithreaded application. A sin-
  8357. gle copy of the character tables is used by all the decoded patterns
  8358. and a reference count is used to arrange for its memory to be automati-
  8359. cally freed when the last pattern is freed, but there is no locking on
  8360. this reference count. Therefore, if you want to call pcre2_code_free()
  8361. for these patterns in different threads, you must arrange your own
  8362. locking, and ensure that pcre2_code_free() cannot be called by two
  8363. threads at the same time.
  8364. If a pattern was processed by pcre2_jit_compile() before being serial-
  8365. ized, the JIT data is discarded and so is no longer available after a
  8366. save/restore cycle. You can, however, process a restored pattern with
  8367. pcre2_jit_compile() if you wish.
  8368. AUTHOR
  8369. Philip Hazel
  8370. Retired from University Computing Service
  8371. Cambridge, England.
  8372. REVISION
  8373. Last updated: 27 June 2018
  8374. Copyright (c) 1997-2018 University of Cambridge.
  8375. PCRE2 10.32 27 June 2018 PCRE2SERIALIZE(3)
  8376. ------------------------------------------------------------------------------
  8377. PCRE2SYNTAX(3) Library Functions Manual PCRE2SYNTAX(3)
  8378. NAME
  8379. PCRE2 - Perl-compatible regular expressions (revised API)
  8380. PCRE2 REGULAR EXPRESSION SYNTAX SUMMARY
  8381. The full syntax and semantics of the regular expressions that are sup-
  8382. ported by PCRE2 are described in the pcre2pattern documentation. This
  8383. document contains a quick-reference summary of the syntax.
  8384. QUOTING
  8385. \x where x is non-alphanumeric is a literal x
  8386. \Q...\E treat enclosed characters as literal
  8387. Note that white space inside \Q...\E is always treated as literal, even
  8388. if PCRE2_EXTENDED is set, causing most other white space to be ignored.
  8389. BRACED ITEMS
  8390. With one exception, wherever brace characters { and } are required to
  8391. enclose data for constructions such as \g{2} or \k{name}, space and/or
  8392. horizontal tab characters that follow { or precede } are allowed and
  8393. are ignored. In the case of quantifiers, they may also appear before or
  8394. after the comma. The exception is \u{...} which is not Perl-compatible
  8395. and is recognized only when PCRE2_EXTRA_ALT_BSUX is set. This is an EC-
  8396. MAScript compatibility feature, and follows ECMAScript's behaviour.
  8397. ESCAPED CHARACTERS
  8398. This table applies to ASCII and Unicode environments. An unrecognized
  8399. escape sequence causes an error.
  8400. \a alarm, that is, the BEL character (hex 07)
  8401. \cx "control-x", where x is a non-control ASCII character
  8402. \e escape (hex 1B)
  8403. \f form feed (hex 0C)
  8404. \n newline (hex 0A)
  8405. \r carriage return (hex 0D)
  8406. \t tab (hex 09)
  8407. \0dd character with octal code 0dd
  8408. \ddd character with octal code ddd, or backreference
  8409. \o{ddd..} character with octal code ddd..
  8410. \N{U+hh..} character with Unicode code point hh.. (Unicode mode only)
  8411. \xhh character with hex code hh
  8412. \x{hh..} character with hex code hh..
  8413. If PCRE2_ALT_BSUX or PCRE2_EXTRA_ALT_BSUX is set ("ALT_BSUX mode"), the
  8414. following are also recognized:
  8415. \U the character "U"
  8416. \uhhhh character with hex code hhhh
  8417. \u{hh..} character with hex code hh.. but only for EXTRA_ALT_BSUX
  8418. When \x is not followed by {, from zero to two hexadecimal digits are
  8419. read, but in ALT_BSUX mode \x must be followed by two hexadecimal dig-
  8420. its to be recognized as a hexadecimal escape; otherwise it matches a
  8421. literal "x". Likewise, if \u (in ALT_BSUX mode) is not followed by
  8422. four hexadecimal digits or (in EXTRA_ALT_BSUX mode) a sequence of hex
  8423. digits in curly brackets, it matches a literal "u".
  8424. Note that \0dd is always an octal code. The treatment of backslash fol-
  8425. lowed by a non-zero digit is complicated; for details see the section
  8426. "Non-printing characters" in the pcre2pattern documentation, where de-
  8427. tails of escape processing in EBCDIC environments are also given.
  8428. \N{U+hh..} is synonymous with \x{hh..} in PCRE2 but is not supported in
  8429. EBCDIC environments. Note that \N not followed by an opening curly
  8430. bracket has a different meaning (see below).
  8431. CHARACTER TYPES
  8432. . any character except newline;
  8433. in dotall mode, any character whatsoever
  8434. \C one code unit, even in UTF mode (best avoided)
  8435. \d a decimal digit
  8436. \D a character that is not a decimal digit
  8437. \h a horizontal white space character
  8438. \H a character that is not a horizontal white space character
  8439. \N a character that is not a newline
  8440. \p{xx} a character with the xx property
  8441. \P{xx} a character without the xx property
  8442. \R a newline sequence
  8443. \s a white space character
  8444. \S a character that is not a white space character
  8445. \v a vertical white space character
  8446. \V a character that is not a vertical white space character
  8447. \w a "word" character
  8448. \W a "non-word" character
  8449. \X a Unicode extended grapheme cluster
  8450. \C is dangerous because it may leave the current matching point in the
  8451. middle of a UTF-8 or UTF-16 character. The application can lock out the
  8452. use of \C by setting the PCRE2_NEVER_BACKSLASH_C option. It is also
  8453. possible to build PCRE2 with the use of \C permanently disabled.
  8454. By default, \d, \s, and \w match only ASCII characters, even in UTF-8
  8455. mode or in the 16-bit and 32-bit libraries. However, if locale-specific
  8456. matching is happening, \s and \w may also match characters with code
  8457. points in the range 128-255. If the PCRE2_UCP option is set, the behav-
  8458. iour of these escape sequences is changed to use Unicode properties and
  8459. they match many more characters, but there are some option settings
  8460. that can restrict individual sequences to matching only ASCII charac-
  8461. ters.
  8462. Property descriptions in \p and \P are matched caselessly; hyphens, un-
  8463. derscores, and white space are ignored, in accordance with Unicode's
  8464. "loose matching" rules.
  8465. GENERAL CATEGORY PROPERTIES FOR \p and \P
  8466. C Other
  8467. Cc Control
  8468. Cf Format
  8469. Cn Unassigned
  8470. Co Private use
  8471. Cs Surrogate
  8472. L Letter
  8473. Ll Lower case letter
  8474. Lm Modifier letter
  8475. Lo Other letter
  8476. Lt Title case letter
  8477. Lu Upper case letter
  8478. Lc Ll, Lu, or Lt
  8479. L& Ll, Lu, or Lt
  8480. M Mark
  8481. Mc Spacing mark
  8482. Me Enclosing mark
  8483. Mn Non-spacing mark
  8484. N Number
  8485. Nd Decimal number
  8486. Nl Letter number
  8487. No Other number
  8488. P Punctuation
  8489. Pc Connector punctuation
  8490. Pd Dash punctuation
  8491. Pe Close punctuation
  8492. Pf Final punctuation
  8493. Pi Initial punctuation
  8494. Po Other punctuation
  8495. Ps Open punctuation
  8496. S Symbol
  8497. Sc Currency symbol
  8498. Sk Modifier symbol
  8499. Sm Mathematical symbol
  8500. So Other symbol
  8501. Z Separator
  8502. Zl Line separator
  8503. Zp Paragraph separator
  8504. Zs Space separator
  8505. PCRE2 SPECIAL CATEGORY PROPERTIES FOR \p and \P
  8506. Xan Alphanumeric: union of properties L and N
  8507. Xps POSIX space: property Z or tab, NL, VT, FF, CR
  8508. Xsp Perl space: property Z or tab, NL, VT, FF, CR
  8509. Xuc Universally-named character: one that can be
  8510. represented by a Universal Character Name
  8511. Xwd Perl word: property Xan or underscore
  8512. Perl and POSIX space are now the same. Perl added VT to its space char-
  8513. acter set at release 5.18.
  8514. BINARY PROPERTIES FOR \p AND \P
  8515. Unicode defines a number of binary properties, that is, properties
  8516. whose only values are true or false. You can obtain a list of those
  8517. that are recognized by \p and \P, along with their abbreviations, by
  8518. running this command:
  8519. pcre2test -LP
  8520. SCRIPT MATCHING WITH \p AND \P
  8521. Many script names and their 4-letter abbreviations are recognized in
  8522. \p{sc:...} or \p{scx:...} items, or on their own with \p (and also \P
  8523. of course). You can obtain a list of these scripts by running this com-
  8524. mand:
  8525. pcre2test -LS
  8526. THE BIDI_CLASS PROPERTY FOR \p AND \P
  8527. \p{Bidi_Class:<class>} matches a character with the given class
  8528. \p{BC:<class>} matches a character with the given class
  8529. The recognized classes are:
  8530. AL Arabic letter
  8531. AN Arabic number
  8532. B paragraph separator
  8533. BN boundary neutral
  8534. CS common separator
  8535. EN European number
  8536. ES European separator
  8537. ET European terminator
  8538. FSI first strong isolate
  8539. L left-to-right
  8540. LRE left-to-right embedding
  8541. LRI left-to-right isolate
  8542. LRO left-to-right override
  8543. NSM non-spacing mark
  8544. ON other neutral
  8545. PDF pop directional format
  8546. PDI pop directional isolate
  8547. R right-to-left
  8548. RLE right-to-left embedding
  8549. RLI right-to-left isolate
  8550. RLO right-to-left override
  8551. S segment separator
  8552. WS which space
  8553. CHARACTER CLASSES
  8554. [...] positive character class
  8555. [^...] negative character class
  8556. [x-y] range (can be used for hex characters)
  8557. [[:xxx:]] positive POSIX named set
  8558. [[:^xxx:]] negative POSIX named set
  8559. alnum alphanumeric
  8560. alpha alphabetic
  8561. ascii 0-127
  8562. blank space or tab
  8563. cntrl control character
  8564. digit decimal digit
  8565. graph printing, excluding space
  8566. lower lower case letter
  8567. print printing, including space
  8568. punct printing, excluding alphanumeric
  8569. space white space
  8570. upper upper case letter
  8571. word same as \w
  8572. xdigit hexadecimal digit
  8573. In PCRE2, POSIX character set names recognize only ASCII characters by
  8574. default, but some of them use Unicode properties if PCRE2_UCP is set.
  8575. You can use \Q...\E inside a character class.
  8576. QUANTIFIERS
  8577. ? 0 or 1, greedy
  8578. ?+ 0 or 1, possessive
  8579. ?? 0 or 1, lazy
  8580. * 0 or more, greedy
  8581. *+ 0 or more, possessive
  8582. *? 0 or more, lazy
  8583. + 1 or more, greedy
  8584. ++ 1 or more, possessive
  8585. +? 1 or more, lazy
  8586. {n} exactly n
  8587. {n,m} at least n, no more than m, greedy
  8588. {n,m}+ at least n, no more than m, possessive
  8589. {n,m}? at least n, no more than m, lazy
  8590. {n,} n or more, greedy
  8591. {n,}+ n or more, possessive
  8592. {n,}? n or more, lazy
  8593. {,m} zero up to m, greedy
  8594. {,m}+ zero up to m, possessive
  8595. {,m}? zero up to m, lazy
  8596. ANCHORS AND SIMPLE ASSERTIONS
  8597. \b word boundary
  8598. \B not a word boundary
  8599. ^ start of subject
  8600. also after an internal newline in multiline mode
  8601. (after any newline if PCRE2_ALT_CIRCUMFLEX is set)
  8602. \A start of subject
  8603. $ end of subject
  8604. also before newline at end of subject
  8605. also before internal newline in multiline mode
  8606. \Z end of subject
  8607. also before newline at end of subject
  8608. \z end of subject
  8609. \G first matching position in subject
  8610. REPORTED MATCH POINT SETTING
  8611. \K set reported start of match
  8612. From release 10.38 \K is not permitted by default in lookaround asser-
  8613. tions, for compatibility with Perl. However, if the PCRE2_EXTRA_AL-
  8614. LOW_LOOKAROUND_BSK option is set, the previous behaviour is re-enabled.
  8615. When this option is set, \K is honoured in positive assertions, but ig-
  8616. nored in negative ones.
  8617. ALTERNATION
  8618. expr|expr|expr...
  8619. CAPTURING
  8620. (...) capture group
  8621. (?<name>...) named capture group (Perl)
  8622. (?'name'...) named capture group (Perl)
  8623. (?P<name>...) named capture group (Python)
  8624. (?:...) non-capture group
  8625. (?|...) non-capture group; reset group numbers for
  8626. capture groups in each alternative
  8627. In non-UTF modes, names may contain underscores and ASCII letters and
  8628. digits; in UTF modes, any Unicode letters and Unicode decimal digits
  8629. are permitted. In both cases, a name must not start with a digit.
  8630. ATOMIC GROUPS
  8631. (?>...) atomic non-capture group
  8632. (*atomic:...) atomic non-capture group
  8633. COMMENT
  8634. (?#....) comment (not nestable)
  8635. OPTION SETTING
  8636. Changes of these options within a group are automatically cancelled at
  8637. the end of the group.
  8638. (?a) all ASCII options
  8639. (?aD) restrict \d to ASCII in UCP mode
  8640. (?aS) restrict \s to ASCII in UCP mode
  8641. (?aW) restrict \w to ASCII in UCP mode
  8642. (?aP) restrict all POSIX classes to ASCII in UCP mode
  8643. (?aT) restrict POSIX digit classes to ASCII in UCP mode
  8644. (?i) caseless
  8645. (?J) allow duplicate named groups
  8646. (?m) multiline
  8647. (?n) no auto capture
  8648. (?r) restrict caseless to either ASCII or non-ASCII
  8649. (?s) single line (dotall)
  8650. (?U) default ungreedy (lazy)
  8651. (?x) ignore white space except in classes or \Q...\E
  8652. (?xx) as (?x) but also ignore space and tab in classes
  8653. (?-...) unset the given option(s)
  8654. (?^) unset imnrsx options
  8655. (?aP) implies (?aT) as well, though this has no additional effect. How-
  8656. ever, it means that (?-aP) is really (?-PT) which disables all ASCII
  8657. restrictions for POSIX classes.
  8658. Unsetting x or xx unsets both. Several options may be set at once, and
  8659. a mixture of setting and unsetting such as (?i-x) is allowed, but there
  8660. may be only one hyphen. Setting (but no unsetting) is allowed after (?^
  8661. for example (?^in). An option setting may appear at the start of a non-
  8662. capture group, for example (?i:...).
  8663. The following are recognized only at the very start of a pattern or af-
  8664. ter one of the newline or \R options with similar syntax. More than one
  8665. of them may appear. For the first three, d is a decimal number.
  8666. (*LIMIT_DEPTH=d) set the backtracking limit to d
  8667. (*LIMIT_HEAP=d) set the heap size limit to d * 1024 bytes
  8668. (*LIMIT_MATCH=d) set the match limit to d
  8669. (*NOTEMPTY) set PCRE2_NOTEMPTY when matching
  8670. (*NOTEMPTY_ATSTART) set PCRE2_NOTEMPTY_ATSTART when matching
  8671. (*NO_AUTO_POSSESS) no auto-possessification (PCRE2_NO_AUTO_POSSESS)
  8672. (*NO_DOTSTAR_ANCHOR) no .* anchoring (PCRE2_NO_DOTSTAR_ANCHOR)
  8673. (*NO_JIT) disable JIT optimization
  8674. (*NO_START_OPT) no start-match optimization (PCRE2_NO_START_OPTIMIZE)
  8675. (*UTF) set appropriate UTF mode for the library in use
  8676. (*UCP) set PCRE2_UCP (use Unicode properties for \d etc)
  8677. Note that LIMIT_DEPTH, LIMIT_HEAP, and LIMIT_MATCH can only reduce the
  8678. value of the limits set by the caller of pcre2_match() or
  8679. pcre2_dfa_match(), not increase them. LIMIT_RECURSION is an obsolete
  8680. synonym for LIMIT_DEPTH. The application can lock out the use of (*UTF)
  8681. and (*UCP) by setting the PCRE2_NEVER_UTF or PCRE2_NEVER_UCP options,
  8682. respectively, at compile time.
  8683. NEWLINE CONVENTION
  8684. These are recognized only at the very start of the pattern or after op-
  8685. tion settings with a similar syntax.
  8686. (*CR) carriage return only
  8687. (*LF) linefeed only
  8688. (*CRLF) carriage return followed by linefeed
  8689. (*ANYCRLF) all three of the above
  8690. (*ANY) any Unicode newline sequence
  8691. (*NUL) the NUL character (binary zero)
  8692. WHAT \R MATCHES
  8693. These are recognized only at the very start of the pattern or after op-
  8694. tion setting with a similar syntax.
  8695. (*BSR_ANYCRLF) CR, LF, or CRLF
  8696. (*BSR_UNICODE) any Unicode newline sequence
  8697. LOOKAHEAD AND LOOKBEHIND ASSERTIONS
  8698. (?=...) )
  8699. (*pla:...) ) positive lookahead
  8700. (*positive_lookahead:...) )
  8701. (?!...) )
  8702. (*nla:...) ) negative lookahead
  8703. (*negative_lookahead:...) )
  8704. (?<=...) )
  8705. (*plb:...) ) positive lookbehind
  8706. (*positive_lookbehind:...) )
  8707. (?<!...) )
  8708. (*nlb:...) ) negative lookbehind
  8709. (*negative_lookbehind:...) )
  8710. Each top-level branch of a lookbehind must have a limit for the number
  8711. of characters it matches. If any branch can match a variable number of
  8712. characters, the maximum for each branch is limited to a value set by
  8713. the caller of pcre2_compile() or defaulted. The default is set when
  8714. PCRE2 is built (ultimate default 255). If every branch matches a fixed
  8715. number of characters, the limit for each branch is 65535 characters.
  8716. NON-ATOMIC LOOKAROUND ASSERTIONS
  8717. These assertions are specific to PCRE2 and are not Perl-compatible.
  8718. (?*...) )
  8719. (*napla:...) ) synonyms
  8720. (*non_atomic_positive_lookahead:...) )
  8721. (?<*...) )
  8722. (*naplb:...) ) synonyms
  8723. (*non_atomic_positive_lookbehind:...) )
  8724. SCRIPT RUNS
  8725. (*script_run:...) ) script run, can be backtracked into
  8726. (*sr:...) )
  8727. (*atomic_script_run:...) ) atomic script run
  8728. (*asr:...) )
  8729. BACKREFERENCES
  8730. \n reference by number (can be ambiguous)
  8731. \gn reference by number
  8732. \g{n} reference by number
  8733. \g+n relative reference by number (PCRE2 extension)
  8734. \g-n relative reference by number
  8735. \g{+n} relative reference by number (PCRE2 extension)
  8736. \g{-n} relative reference by number
  8737. \k<name> reference by name (Perl)
  8738. \k'name' reference by name (Perl)
  8739. \g{name} reference by name (Perl)
  8740. \k{name} reference by name (.NET)
  8741. (?P=name) reference by name (Python)
  8742. SUBROUTINE REFERENCES (POSSIBLY RECURSIVE)
  8743. (?R) recurse whole pattern
  8744. (?n) call subroutine by absolute number
  8745. (?+n) call subroutine by relative number
  8746. (?-n) call subroutine by relative number
  8747. (?&name) call subroutine by name (Perl)
  8748. (?P>name) call subroutine by name (Python)
  8749. \g<name> call subroutine by name (Oniguruma)
  8750. \g'name' call subroutine by name (Oniguruma)
  8751. \g<n> call subroutine by absolute number (Oniguruma)
  8752. \g'n' call subroutine by absolute number (Oniguruma)
  8753. \g<+n> call subroutine by relative number (PCRE2 extension)
  8754. \g'+n' call subroutine by relative number (PCRE2 extension)
  8755. \g<-n> call subroutine by relative number (PCRE2 extension)
  8756. \g'-n' call subroutine by relative number (PCRE2 extension)
  8757. CONDITIONAL PATTERNS
  8758. (?(condition)yes-pattern)
  8759. (?(condition)yes-pattern|no-pattern)
  8760. (?(n) absolute reference condition
  8761. (?(+n) relative reference condition (PCRE2 extension)
  8762. (?(-n) relative reference condition (PCRE2 extension)
  8763. (?(<name>) named reference condition (Perl)
  8764. (?('name') named reference condition (Perl)
  8765. (?(name) named reference condition (PCRE2, deprecated)
  8766. (?(R) overall recursion condition
  8767. (?(Rn) specific numbered group recursion condition
  8768. (?(R&name) specific named group recursion condition
  8769. (?(DEFINE) define groups for reference
  8770. (?(VERSION[>]=n.m) test PCRE2 version
  8771. (?(assert) assertion condition
  8772. Note the ambiguity of (?(R) and (?(Rn) which might be named reference
  8773. conditions or recursion tests. Such a condition is interpreted as a
  8774. reference condition if the relevant named group exists.
  8775. BACKTRACKING CONTROL
  8776. All backtracking control verbs may be in the form (*VERB:NAME). For
  8777. (*MARK) the name is mandatory, for the others it is optional. (*SKIP)
  8778. changes its behaviour if :NAME is present. The others just set a name
  8779. for passing back to the caller, but this is not a name that (*SKIP) can
  8780. see. The following act immediately they are reached:
  8781. (*ACCEPT) force successful match
  8782. (*FAIL) force backtrack; synonym (*F)
  8783. (*MARK:NAME) set name to be passed back; synonym (*:NAME)
  8784. The following act only when a subsequent match failure causes a back-
  8785. track to reach them. They all force a match failure, but they differ in
  8786. what happens afterwards. Those that advance the start-of-match point do
  8787. so only if the pattern is not anchored.
  8788. (*COMMIT) overall failure, no advance of starting point
  8789. (*PRUNE) advance to next starting character
  8790. (*SKIP) advance to current matching position
  8791. (*SKIP:NAME) advance to position corresponding to an earlier
  8792. (*MARK:NAME); if not found, the (*SKIP) is ignored
  8793. (*THEN) local failure, backtrack to next alternation
  8794. The effect of one of these verbs in a group called as a subroutine is
  8795. confined to the subroutine call.
  8796. CALLOUTS
  8797. (?C) callout (assumed number 0)
  8798. (?Cn) callout with numerical data n
  8799. (?C"text") callout with string data
  8800. The allowed string delimiters are ` ' " ^ % # $ (which are the same for
  8801. the start and the end), and the starting delimiter { matched with the
  8802. ending delimiter }. To encode the ending delimiter within the string,
  8803. double it.
  8804. SEE ALSO
  8805. pcre2pattern(3), pcre2api(3), pcre2callout(3), pcre2matching(3),
  8806. pcre2(3).
  8807. AUTHOR
  8808. Philip Hazel
  8809. Retired from University Computing Service
  8810. Cambridge, England.
  8811. REVISION
  8812. Last updated: 12 October 2023
  8813. Copyright (c) 1997-2023 University of Cambridge.
  8814. PCRE2 10.43 12 October 2023 PCRE2SYNTAX(3)
  8815. ------------------------------------------------------------------------------
  8816. PCRE2UNICODE(3) Library Functions Manual PCRE2UNICODE(3)
  8817. NAME
  8818. PCRE - Perl-compatible regular expressions (revised API)
  8819. UNICODE AND UTF SUPPORT
  8820. PCRE2 is normally built with Unicode support, though if you do not need
  8821. it, you can build it without, in which case the library will be
  8822. smaller. With Unicode support, PCRE2 has knowledge of Unicode character
  8823. properties and can process strings of text in UTF-8, UTF-16, and UTF-32
  8824. format (depending on the code unit width), but this is not the default.
  8825. Unless specifically requested, PCRE2 treats each code unit in a string
  8826. as one character.
  8827. There are two ways of telling PCRE2 to switch to UTF mode, where char-
  8828. acters may consist of more than one code unit and the range of values
  8829. is constrained. The program can call pcre2_compile() with the PCRE2_UTF
  8830. option, or the pattern may start with the sequence (*UTF). However,
  8831. the latter facility can be locked out by the PCRE2_NEVER_UTF option.
  8832. That is, the programmer can prevent the supplier of the pattern from
  8833. switching to UTF mode.
  8834. Note that the PCRE2_MATCH_INVALID_UTF option (see below) forces
  8835. PCRE2_UTF to be set.
  8836. In UTF mode, both the pattern and any subject strings that are matched
  8837. against it are treated as UTF strings instead of strings of individual
  8838. one-code-unit characters. There are also some other changes to the way
  8839. characters are handled, as documented below.
  8840. UNICODE PROPERTY SUPPORT
  8841. When PCRE2 is built with Unicode support, the escape sequences \p{..},
  8842. \P{..}, and \X can be used. This is not dependent on the PCRE2_UTF set-
  8843. ting. The Unicode properties that can be tested are a subset of those
  8844. that Perl supports. Currently they are limited to the general category
  8845. properties such as Lu for an upper case letter or Nd for a decimal num-
  8846. ber, the derived properties Any and LC (synonym L&), the Unicode script
  8847. names such as Arabic or Han, Bidi_Class, Bidi_Control, and a few binary
  8848. properties.
  8849. The full lists are given in the pcre2pattern and pcre2syntax documenta-
  8850. tion. In general, only the short names for properties are supported.
  8851. For example, \p{L} matches a letter. Its longer synonym, \p{Letter}, is
  8852. not supported. Furthermore, in Perl, many properties may optionally be
  8853. prefixed by "Is", for compatibility with Perl 5.6. PCRE2 does not sup-
  8854. port this.
  8855. WIDE CHARACTERS AND UTF MODES
  8856. Code points less than 256 can be specified in patterns by either braced
  8857. or unbraced hexadecimal escape sequences (for example, \x{b3} or \xb3).
  8858. Larger values have to use braced sequences. Unbraced octal code points
  8859. up to \777 are also recognized; larger ones can be coded using \o{...}.
  8860. The escape sequence \N{U+<hex digits>} is recognized as another way of
  8861. specifying a Unicode character by code point in a UTF mode. It is not
  8862. allowed in non-UTF mode.
  8863. In UTF mode, repeat quantifiers apply to complete UTF characters, not
  8864. to individual code units.
  8865. In UTF mode, the dot metacharacter matches one UTF character instead of
  8866. a single code unit.
  8867. In UTF mode, capture group names are not restricted to ASCII, and may
  8868. contain any Unicode letters and decimal digits, as well as underscore.
  8869. The escape sequence \C can be used to match a single code unit in UTF
  8870. mode, but its use can lead to some strange effects because it breaks up
  8871. multi-unit characters (see the description of \C in the pcre2pattern
  8872. documentation). For this reason, there is a build-time option that dis-
  8873. ables support for \C completely. There is also a less draconian com-
  8874. pile-time option for locking out the use of \C when a pattern is com-
  8875. piled.
  8876. The use of \C is not supported by the alternative matching function
  8877. pcre2_dfa_match() when in UTF-8 or UTF-16 mode, that is, when a charac-
  8878. ter may consist of more than one code unit. The use of \C in these
  8879. modes provokes a match-time error. Also, the JIT optimization does not
  8880. support \C in these modes. If JIT optimization is requested for a UTF-8
  8881. or UTF-16 pattern that contains \C, it will not succeed, and so when
  8882. pcre2_match() is called, the matching will be carried out by the inter-
  8883. pretive function.
  8884. The character escapes \b, \B, \d, \D, \s, \S, \w, and \W correctly test
  8885. characters of any code value, but, by default, the characters that
  8886. PCRE2 recognizes as digits, spaces, or word characters remain the same
  8887. set as in non-UTF mode, all with code points less than 256. This re-
  8888. mains true even when PCRE2 is built to include Unicode support, because
  8889. to do otherwise would slow down matching in many common cases. Note
  8890. that this also applies to \b and \B, because they are defined in terms
  8891. of \w and \W. If you want to test for a wider sense of, say, "digit",
  8892. you can use explicit Unicode property tests such as \p{Nd}. Alterna-
  8893. tively, if you set the PCRE2_UCP option, the way that the character es-
  8894. capes work is changed so that Unicode properties are used to determine
  8895. which characters match, though there are some options that suppress
  8896. this for individual escapes. For details see the section on generic
  8897. character types in the pcre2pattern documentation.
  8898. Like the escapes, characters that match the POSIX named character
  8899. classes are all low-valued characters unless the PCRE2_UCP option is
  8900. set, but there is an option to override this.
  8901. In contrast to the character escapes and character classes, the special
  8902. horizontal and vertical white space escapes (\h, \H, \v, and \V) do
  8903. match all the appropriate Unicode characters, whether or not PCRE2_UCP
  8904. is set.
  8905. UNICODE CASE-EQUIVALENCE
  8906. If either PCRE2_UTF or PCRE2_UCP is set, upper/lower case processing
  8907. makes use of Unicode properties except for characters whose code points
  8908. are less than 128 and that have at most two case-equivalent values. For
  8909. these, a direct table lookup is used for speed. A few Unicode charac-
  8910. ters such as Greek sigma have more than two code points that are case-
  8911. equivalent, and these are treated specially. Setting PCRE2_UCP without
  8912. PCRE2_UTF allows Unicode-style case processing for non-UTF character
  8913. encodings such as UCS-2.
  8914. There are two ASCII characters (S and K) that, in addition to their
  8915. ASCII lower case equivalents, have a non-ASCII one as well (long S and
  8916. Kelvin sign). Recognition of these non-ASCII characters as case-equiv-
  8917. alent to their ASCII counterparts can be disabled by setting the
  8918. PCRE2_EXTRA_CASELESS_RESTRICT option. When this is set, all characters
  8919. in a case equivalence must either be ASCII or non-ASCII; there can be
  8920. no mixing.
  8921. SCRIPT RUNS
  8922. The pattern constructs (*script_run:...) and (*atomic_script_run:...),
  8923. with synonyms (*sr:...) and (*asr:...), verify that the string matched
  8924. within the parentheses is a script run. In concept, a script run is a
  8925. sequence of characters that are all from the same Unicode script. How-
  8926. ever, because some scripts are commonly used together, and because some
  8927. diacritical and other marks are used with multiple scripts, it is not
  8928. that simple.
  8929. Every Unicode character has a Script property, mostly with a value cor-
  8930. responding to the name of a script, such as Latin, Greek, or Cyrillic.
  8931. There are also three special values:
  8932. "Unknown" is used for code points that have not been assigned, and also
  8933. for the surrogate code points. In the PCRE2 32-bit library, characters
  8934. whose code points are greater than the Unicode maximum (U+10FFFF),
  8935. which are accessible only in non-UTF mode, are assigned the Unknown
  8936. script.
  8937. "Common" is used for characters that are used with many scripts. These
  8938. include punctuation, emoji, mathematical, musical, and currency sym-
  8939. bols, and the ASCII digits 0 to 9.
  8940. "Inherited" is used for characters such as diacritical marks that mod-
  8941. ify a previous character. These are considered to take on the script of
  8942. the character that they modify.
  8943. Some Inherited characters are used with many scripts, but many of them
  8944. are only normally used with a small number of scripts. For example,
  8945. U+102E0 (Coptic Epact thousands mark) is used only with Arabic and Cop-
  8946. tic. In order to make it possible to check this, a Unicode property
  8947. called Script Extension exists. Its value is a list of scripts that ap-
  8948. ply to the character. For the majority of characters, the list contains
  8949. just one script, the same one as the Script property. However, for
  8950. characters such as U+102E0 more than one Script is listed. There are
  8951. also some Common characters that have a single, non-Common script in
  8952. their Script Extension list.
  8953. The next section describes the basic rules for deciding whether a given
  8954. string of characters is a script run. Note, however, that there are
  8955. some special cases involving the Chinese Han script, and an additional
  8956. constraint for decimal digits. These are covered in subsequent sec-
  8957. tions.
  8958. Basic script run rules
  8959. A string that is less than two characters long is a script run. This is
  8960. the only case in which an Unknown character can be part of a script
  8961. run. Longer strings are checked using only the Script Extensions prop-
  8962. erty, not the basic Script property.
  8963. If a character's Script Extension property is the single value "Inher-
  8964. ited", it is always accepted as part of a script run. This is also true
  8965. for the property "Common", subject to the checking of decimal digits
  8966. described below. All the remaining characters in a script run must have
  8967. at least one script in common in their Script Extension lists. In set-
  8968. theoretic terminology, the intersection of all the sets of scripts must
  8969. not be empty.
  8970. A simple example is an Internet name such as "google.com". The letters
  8971. are all in the Latin script, and the dot is Common, so this string is a
  8972. script run. However, the Cyrillic letter "o" looks exactly the same as
  8973. the Latin "o"; a string that looks the same, but with Cyrillic "o"s is
  8974. not a script run.
  8975. More interesting examples involve characters with more than one script
  8976. in their Script Extension. Consider the following characters:
  8977. U+060C Arabic comma
  8978. U+06D4 Arabic full stop
  8979. The first has the Script Extension list Arabic, Hanifi Rohingya, Syr-
  8980. iac, and Thaana; the second has just Arabic and Hanifi Rohingya. Both
  8981. of them could appear in script runs of either Arabic or Hanifi Ro-
  8982. hingya. The first could also appear in Syriac or Thaana script runs,
  8983. but the second could not.
  8984. The Chinese Han script
  8985. The Chinese Han script is commonly used in conjunction with other
  8986. scripts for writing certain languages. Japanese uses the Hiragana and
  8987. Katakana scripts together with Han; Korean uses Hangul and Han; Tai-
  8988. wanese Mandarin uses Bopomofo and Han. These three combinations are
  8989. treated as special cases when checking script runs and are, in effect,
  8990. "virtual scripts". Thus, a script run may contain a mixture of Hira-
  8991. gana, Katakana, and Han, or a mixture of Hangul and Han, or a mixture
  8992. of Bopomofo and Han, but not, for example, a mixture of Hangul and
  8993. Bopomofo and Han. PCRE2 (like Perl) follows Unicode's Technical Stan-
  8994. dard 39 ("Unicode Security Mechanisms", http://unicode.org/re-
  8995. ports/tr39/) in allowing such mixtures.
  8996. Decimal digits
  8997. Unicode contains many sets of 10 decimal digits in different scripts,
  8998. and some scripts (including the Common script) contain more than one
  8999. set. Some of these decimal digits them are visually indistinguishable
  9000. from the common ASCII digits. In addition to the script checking de-
  9001. scribed above, if a script run contains any decimal digits, they must
  9002. all come from the same set of 10 adjacent characters.
  9003. VALIDITY OF UTF STRINGS
  9004. When the PCRE2_UTF option is set, the strings passed as patterns and
  9005. subjects are (by default) checked for validity on entry to the relevant
  9006. functions. If an invalid UTF string is passed, a negative error code is
  9007. returned. The code unit offset to the offending character can be ex-
  9008. tracted from the match data block by calling pcre2_get_startchar(),
  9009. which is used for this purpose after a UTF error.
  9010. In some situations, you may already know that your strings are valid,
  9011. and therefore want to skip these checks in order to improve perfor-
  9012. mance, for example in the case of a long subject string that is being
  9013. scanned repeatedly. If you set the PCRE2_NO_UTF_CHECK option at com-
  9014. pile time or at match time, PCRE2 assumes that the pattern or subject
  9015. it is given (respectively) contains only valid UTF code unit sequences.
  9016. If you pass an invalid UTF string when PCRE2_NO_UTF_CHECK is set, the
  9017. result is undefined and your program may crash or loop indefinitely or
  9018. give incorrect results. There is, however, one mode of matching that
  9019. can handle invalid UTF subject strings. This is enabled by passing
  9020. PCRE2_MATCH_INVALID_UTF to pcre2_compile() and is discussed below in
  9021. the next section. The rest of this section covers the case when
  9022. PCRE2_MATCH_INVALID_UTF is not set.
  9023. Passing PCRE2_NO_UTF_CHECK to pcre2_compile() just disables the UTF
  9024. check for the pattern; it does not also apply to subject strings. If
  9025. you want to disable the check for a subject string you must pass this
  9026. same option to pcre2_match() or pcre2_dfa_match().
  9027. UTF-16 and UTF-32 strings can indicate their endianness by special code
  9028. knows as a byte-order mark (BOM). The PCRE2 functions do not handle
  9029. this, expecting strings to be in host byte order.
  9030. Unless PCRE2_NO_UTF_CHECK is set, a UTF string is checked before any
  9031. other processing takes place. In the case of pcre2_match() and
  9032. pcre2_dfa_match() calls with a non-zero starting offset, the check is
  9033. applied only to that part of the subject that could be inspected during
  9034. matching, and there is a check that the starting offset points to the
  9035. first code unit of a character or to the end of the subject. If there
  9036. are no lookbehind assertions in the pattern, the check starts at the
  9037. starting offset. Otherwise, it starts at the length of the longest
  9038. lookbehind before the starting offset, or at the start of the subject
  9039. if there are not that many characters before the starting offset. Note
  9040. that the sequences \b and \B are one-character lookbehinds.
  9041. In addition to checking the format of the string, there is a check to
  9042. ensure that all code points lie in the range U+0 to U+10FFFF, excluding
  9043. the surrogate area. The so-called "non-character" code points are not
  9044. excluded because Unicode corrigendum #9 makes it clear that they should
  9045. not be.
  9046. Characters in the "Surrogate Area" of Unicode are reserved for use by
  9047. UTF-16, where they are used in pairs to encode code points with values
  9048. greater than 0xFFFF. The code points that are encoded by UTF-16 pairs
  9049. are available independently in the UTF-8 and UTF-32 encodings. (In
  9050. other words, the whole surrogate thing is a fudge for UTF-16 which un-
  9051. fortunately messes up UTF-8 and UTF-32.)
  9052. Setting PCRE2_NO_UTF_CHECK at compile time does not disable the error
  9053. that is given if an escape sequence for an invalid Unicode code point
  9054. is encountered in the pattern. If you want to allow escape sequences
  9055. such as \x{d800} (a surrogate code point) you can set the PCRE2_EX-
  9056. TRA_ALLOW_SURROGATE_ESCAPES extra option. However, this is possible
  9057. only in UTF-8 and UTF-32 modes, because these values are not repre-
  9058. sentable in UTF-16.
  9059. Errors in UTF-8 strings
  9060. The following negative error codes are given for invalid UTF-8 strings:
  9061. PCRE2_ERROR_UTF8_ERR1
  9062. PCRE2_ERROR_UTF8_ERR2
  9063. PCRE2_ERROR_UTF8_ERR3
  9064. PCRE2_ERROR_UTF8_ERR4
  9065. PCRE2_ERROR_UTF8_ERR5
  9066. The string ends with a truncated UTF-8 character; the code specifies
  9067. how many bytes are missing (1 to 5). Although RFC 3629 restricts UTF-8
  9068. characters to be no longer than 4 bytes, the encoding scheme (origi-
  9069. nally defined by RFC 2279) allows for up to 6 bytes, and this is
  9070. checked first; hence the possibility of 4 or 5 missing bytes.
  9071. PCRE2_ERROR_UTF8_ERR6
  9072. PCRE2_ERROR_UTF8_ERR7
  9073. PCRE2_ERROR_UTF8_ERR8
  9074. PCRE2_ERROR_UTF8_ERR9
  9075. PCRE2_ERROR_UTF8_ERR10
  9076. The two most significant bits of the 2nd, 3rd, 4th, 5th, or 6th byte of
  9077. the character do not have the binary value 0b10 (that is, either the
  9078. most significant bit is 0, or the next bit is 1).
  9079. PCRE2_ERROR_UTF8_ERR11
  9080. PCRE2_ERROR_UTF8_ERR12
  9081. A character that is valid by the RFC 2279 rules is either 5 or 6 bytes
  9082. long; these code points are excluded by RFC 3629.
  9083. PCRE2_ERROR_UTF8_ERR13
  9084. A 4-byte character has a value greater than 0x10ffff; these code points
  9085. are excluded by RFC 3629.
  9086. PCRE2_ERROR_UTF8_ERR14
  9087. A 3-byte character has a value in the range 0xd800 to 0xdfff; this
  9088. range of code points are reserved by RFC 3629 for use with UTF-16, and
  9089. so are excluded from UTF-8.
  9090. PCRE2_ERROR_UTF8_ERR15
  9091. PCRE2_ERROR_UTF8_ERR16
  9092. PCRE2_ERROR_UTF8_ERR17
  9093. PCRE2_ERROR_UTF8_ERR18
  9094. PCRE2_ERROR_UTF8_ERR19
  9095. A 2-, 3-, 4-, 5-, or 6-byte character is "overlong", that is, it codes
  9096. for a value that can be represented by fewer bytes, which is invalid.
  9097. For example, the two bytes 0xc0, 0xae give the value 0x2e, whose cor-
  9098. rect coding uses just one byte.
  9099. PCRE2_ERROR_UTF8_ERR20
  9100. The two most significant bits of the first byte of a character have the
  9101. binary value 0b10 (that is, the most significant bit is 1 and the sec-
  9102. ond is 0). Such a byte can only validly occur as the second or subse-
  9103. quent byte of a multi-byte character.
  9104. PCRE2_ERROR_UTF8_ERR21
  9105. The first byte of a character has the value 0xfe or 0xff. These values
  9106. can never occur in a valid UTF-8 string.
  9107. Errors in UTF-16 strings
  9108. The following negative error codes are given for invalid UTF-16
  9109. strings:
  9110. PCRE2_ERROR_UTF16_ERR1 Missing low surrogate at end of string
  9111. PCRE2_ERROR_UTF16_ERR2 Invalid low surrogate follows high surrogate
  9112. PCRE2_ERROR_UTF16_ERR3 Isolated low surrogate
  9113. Errors in UTF-32 strings
  9114. The following negative error codes are given for invalid UTF-32
  9115. strings:
  9116. PCRE2_ERROR_UTF32_ERR1 Surrogate character (0xd800 to 0xdfff)
  9117. PCRE2_ERROR_UTF32_ERR2 Code point is greater than 0x10ffff
  9118. MATCHING IN INVALID UTF STRINGS
  9119. You can run pattern matches on subject strings that may contain invalid
  9120. UTF sequences if you call pcre2_compile() with the PCRE2_MATCH_IN-
  9121. VALID_UTF option. This is supported by pcre2_match(), including JIT
  9122. matching, but not by pcre2_dfa_match(). When PCRE2_MATCH_INVALID_UTF is
  9123. set, it forces PCRE2_UTF to be set as well. Note, however, that the
  9124. pattern itself must be a valid UTF string.
  9125. If you do not set PCRE2_MATCH_INVALID_UTF when calling pcre2_compile,
  9126. and you are not certain that your subject strings are valid UTF se-
  9127. quences, you should not make use of the JIT "fast path" function
  9128. pcre2_jit_match() because it bypasses sanity checks, including the one
  9129. for UTF validity. An invalid string may cause undefined behaviour, in-
  9130. cluding looping, crashing, or giving the wrong answer.
  9131. Setting PCRE2_MATCH_INVALID_UTF does not affect what pcre2_compile()
  9132. generates, but if pcre2_jit_compile() is subsequently called, it does
  9133. generate different code. If JIT is not used, the option affects the be-
  9134. haviour of the interpretive code in pcre2_match(). When PCRE2_MATCH_IN-
  9135. VALID_UTF is set at compile time, PCRE2_NO_UTF_CHECK is ignored at
  9136. match time.
  9137. In this mode, an invalid code unit sequence in the subject never
  9138. matches any pattern item. It does not match dot, it does not match
  9139. \p{Any}, it does not even match negative items such as [^X]. A lookbe-
  9140. hind assertion fails if it encounters an invalid sequence while moving
  9141. the current point backwards. In other words, an invalid UTF code unit
  9142. sequence acts as a barrier which no match can cross.
  9143. You can also think of this as the subject being split up into fragments
  9144. of valid UTF, delimited internally by invalid code unit sequences. The
  9145. pattern is matched fragment by fragment. The result of a successful
  9146. match, however, is given as code unit offsets in the entire subject
  9147. string in the usual way. There are a few points to consider:
  9148. The internal boundaries are not interpreted as the beginnings or ends
  9149. of lines and so do not match circumflex or dollar characters in the
  9150. pattern.
  9151. If pcre2_match() is called with an offset that points to an invalid
  9152. UTF-sequence, that sequence is skipped, and the match starts at the
  9153. next valid UTF character, or the end of the subject.
  9154. At internal fragment boundaries, \b and \B behave in the same way as at
  9155. the beginning and end of the subject. For example, a sequence such as
  9156. \bWORD\b would match an instance of WORD that is surrounded by invalid
  9157. UTF code units.
  9158. Using PCRE2_MATCH_INVALID_UTF, an application can run matches on arbi-
  9159. trary data, knowing that any matched strings that are returned are
  9160. valid UTF. This can be useful when searching for UTF text in executable
  9161. or other binary files.
  9162. Note, however, that the 16-bit and 32-bit PCRE2 libraries process
  9163. strings as sequences of uint16_t or uint32_t code points. They cannot
  9164. find valid UTF sequences within an arbitrary string of bytes unless
  9165. such sequences are suitably aligned.
  9166. AUTHOR
  9167. Philip Hazel
  9168. Retired from University Computing Service
  9169. Cambridge, England.
  9170. REVISION
  9171. Last updated: 12 October 2023
  9172. Copyright (c) 1997-2023 University of Cambridge.
  9173. PCRE2 10.43 04 February 2023 PCRE2UNICODE(3)
  9174. ------------------------------------------------------------------------------