PCRE2DEMO(3)
okay so this is PCRE2DEMO(3) from the Library Functions Manual, and bestie, it's literally the demo C program for PCRE2 β part 1 of 2, so buckle up π
π NAME π
PCRE2DEMO β A demonstration C program for PCRE2. periodt β¨
πΈ SOURCE CODE πΈ
okay so here's the full source drop, and it's giving exact-copy energy β every line below is the source code as it appears, no edits, no cap π«Ά
/*************************************************
* PCRE2 DEMONSTRATION PROGRAM *
*************************************************/
/* This is a demonstration program to illustrate a straightforward way of
using the PCRE2 regular expression library from a C program. See the
pcre2sample documentation for a short discussion ("man pcre2sample" if you have
the PCRE2 man pages installed). PCRE2 is a revised API for the library, and is
incompatible with the original PCRE API.
There are actually three libraries, each supporting a different code unit
width. This demonstration program uses the 8-bit library. The default is to
process each code unit as a separate character, but if the pattern begins with
"(*UTF)", both it and the subject are treated as UTF-8 strings, where
characters may occupy multiple code units.
In Unix-like environments, if PCRE2 is installed in your standard system
libraries, you should be able to compile this program using this command:
cc -Wall pcre2demo.c -lpcre2-8 -o pcre2demo
If PCRE2 is not installed in a standard place, it is likely to be installed
with support for the pkg-config mechanism. If you have pkg-config, you can
compile this program using this command:
cc -Wall pcre2demo.c `pkg-config --cflags --libs libpcre2-8` -o pcre2demo
If you do not have pkg-config, you may have to use something like this:
cc -Wall pcre2demo.c -I/usr/local/include -L/usr/local/lib \
-R/usr/local/lib -lpcre2-8 -o pcre2demo
Replace "/usr/local/include" and "/usr/local/lib" with wherever the include and
library files for PCRE2 are installed on your system. Only some operating
systems (Solaris is one) use the -R option.
Building under Windows:
If you want to statically link this program against a non-dll .a file, you must
define PCRE2_STATIC before including pcre2.h, so in this environment, uncomment
the following line. */
/* #define PCRE2_STATIC */
/* The PCRE2_CODE_UNIT_WIDTH macro must be defined before including pcre2.h.
For a program that uses only one code unit width, setting it to 8, 16, or 32
makes it possible to use generic function names such as pcre2_compile(). Note
that just changing 8 to 16 (for example) is not sufficient to convert this
program to process 16-bit characters. Even in a fully 16-bit environment, where
string-handling functions such as strcmp() and printf() work with 16-bit
characters, the code for handling the table of named substrings will still need
to be modified. */
#define PCRE2_CODE_UNIT_WIDTH 8
#include <stdio.h>
#include <string.h>
#include <pcre2.h>
/**************************************************************************
* Here is the program. The API includes the concept of "contexts" for *
* setting up unusual interface requirements for compiling and matching, *
* such as custom memory managers and non-standard newline definitions. *
* This program does not do any of this, so it makes no use of contexts, *
* always passing NULL where a context could be given. *
**************************************************************************/
int main(int argc, char **argv)
{
pcre2_code *re;
PCRE2_SPTR pattern; /* PCRE2_SPTR is a pointer to unsigned code units of */
PCRE2_SPTR subject; /* the appropriate width (in this case, 8 bits). */
PCRE2_SPTR name_table;
int errornumber;
int find_all, caseless_match;
int i;
int rc;
uint32_t namecount;
uint32_t name_entry_size;
PCRE2_SIZE erroroffset;
PCRE2_SIZE *ovector;
PCRE2_SIZE ovector_last[2];
PCRE2_SIZE subject_length;
pcre2_match_data *match_data;
/**************************************************************************
* First, sort out the command line. Options: *
* - "-g" to request repeated matching to find all occurrences, *
* like Perl's /g option. We set the variable find_all to a non-zero *
* value if the -g option is present. *
* - "-i" to request caseless matching, like Perl's /i option. We set the *
* variable caseless_match to PCRE2_CASELESS if the -i option is *
* present. *
**************************************************************************/
find_all = 0;
caseless_match = 0;
for (i = 1; i < argc; i++)
{
if (strcmp(argv[i], "-g") == 0) find_all = 1;
else if (strcmp(argv[i], "-i") == 0) caseless_match = PCRE2_CASELESS;
else if (argv[i][0] == '-')
{
printf("Unrecognised option %s\n", argv[i]);
return 1;
}
else break;
}
/* After the options, we require exactly two arguments, which are the pattern,
and the subject string. */
if (argc - i != 2)
{
printf("Exactly two arguments required: a regex and a subject string\n");
return 1;
}
/* Pattern and subject are char arguments, so they can be straightforwardly
cast to PCRE2_SPTR because we are working in 8-bit code units. The subject
length is cast to PCRE2_SIZE for completeness, though PCRE2_SIZE is in fact
defined to be size_t. */
pattern = (PCRE2_SPTR)argv[i];
subject = (PCRE2_SPTR)argv[i+1];
subject_length = (PCRE2_SIZE)strlen((char *)subject);
/*************************************************************************
* Now we are going to compile the regular expression pattern, and handle *
* any errors that are detected. *
*************************************************************************/
re = pcre2_compile(
pattern, /* the pattern */
PCRE2_ZERO_TERMINATED, /* indicates pattern is zero-terminated */
caseless_match, /* possibly enable caseless */
&errornumber, /* for error number */
&erroroffset, /* for error offset */
NULL); /* use default compile context */
/* Compilation failed: print the error message and exit. */
if (re == NULL)
{
PCRE2_UCHAR buffer[256];
pcre2_get_error_message(errornumber, buffer, sizeof(buffer));
printf("PCRE2 compilation failed at offset %d: %s\n", (int)erroroffset,
buffer);
return 1;
}
/*************************************************************************
* If the compilation succeeded, we call PCRE2 again, in order to do a *
* pattern match against the subject string. This does just ONE match. If *
* further matching is needed, it will be done below. Before running the *
* match we must set up a match_data block for holding the result. Using *
* pcre2_match_data_create_from_pattern() ensures that the block is *
* exactly the right size for the number of capturing parentheses in the *
* pattern. If you need to know the actual size of a match_data block as *
* a number of bytes, you can find it like this: *
* *
* PCRE2_SIZE match_data_size = pcre2_get_match_data_size(match_data); *
*************************************************************************/
match_data = pcre2_match_data_create_from_pattern(re, NULL);
/* Now run the match. */
rc = pcre2_match(
re, /* the compiled pattern */
subject, /* the subject string */
subject_length, /* the length of the subject */
0, /* start at offset 0 in the subject */
0, /* default options */
match_data, /* block for storing the result */
NULL); /* use default match context */
/* Matching failed: handle error cases */
if (rc < 0)
{
switch(rc)
{
case PCRE2_ERROR_NOMATCH: printf("No match\n"); break;
/*
Handle other special cases if you like
*/
default: printf("Matching error %d\n", rc); break;
}
pcre2_match_data_free(match_data); /* Release memory used for the match */
pcre2_code_free(re); /* data and the compiled pattern. */
return 1;
}
/* Match succeeded. Get a pointer to the output vector, where string offsets
are stored. */
ovector = pcre2_get_ovector_pointer(match_data);
printf("Match succeeded at offset %d\n", (int)ovector[0]);
/*************************************************************************
* We have found the first match within the subject string. If the output *
* vector wasn't big enough, say so. Then output any substrings that were *
* captured. *
*************************************************************************/
/* The output vector wasn't big enough. This should not happen, because we used
pcre2_match_data_create_from_pattern() above. */
if (rc == 0)
printf("ovector was not big enough for all the captured substrings\n");
/* Since release 10.38 PCRE2 has locked out the use of \K in lookaround
assertions. This is the recommended behaviour. However, the option
PCRE2_EXTRA_ALLOW_LOOKAROUND_BSK allows applications to re-enable the old
behaviour. If that is set, it is possible to run patterns such as /(?=.\K)/ that
use \K in an assertion to set the start of a match later than its end. In this
demonstration program, we show how to detect this case, although it cannot arise
because the option is never set. */
if (ovector[0] > ovector[1])
{
printf("\\K was used in an assertion to set the match start after its end.\n"
"From end to start the match was: %.*s\n", (int)(ovector[0] - ovector[1]),
(char *)(subject + ovector[1]));
printf("Run abandoned\n");
pcre2_match_data_free(match_data);
pcre2_code_free(re);
return 1;
}
/* Show substrings stored in the output vector by number. Obviously, in a real
application you might want to do things other than print them. */
for (i = 0; i < rc; i++)
{
PCRE2_SPTR substring_start = subject + ovector[2*i];
PCRE2_SIZE substring_length = ovector[2*i+1] - ovector[2*i];
printf("%2d: %.*s\n", i, (int)substring_length, (char *)substring_start);
}
/**************************************************************************
* That concludes the basic part of this demonstration program. We have *
* compiled a pattern, and performed a single match. The code that follows *
* shows first how to access named substrings, and then how to code for *
* repeated matches on the same subject. *
**************************************************************************/
/* See if there are any named substrings, and if so, show them by name. First
we have to extract the count of named parentheses from the pattern. */
(void)pcre2_pattern_info(
re, /* the compiled pattern */
PCRE2_INFO_NAMECOUNT, /* get the number of named substrings */
&namecount); /* where to put the answer */
if (namecount == 0)
printf("No named substrings\n");
part 1 ends right here, bestie β part 2 is literally loading with the rest of the source code π β¨
Okay bestie, so we're in the else branch β meaning namecount was not zero, so this pattern actually has named groups. Time to flex. π
else
{
PCRE2_SPTR tabptr;
printf("Named substrings\n");
/* Before we can access the substrings, we must extract the table for
translating names to numbers, and the size of each entry in the table. */
(void)pcre2_pattern_info(
re, /* the compiled pattern */
PCRE2_INFO_NAMETABLE, /* address of the table */
&name_table); /* where to put the answer */
(void)pcre2_pattern_info(
re, /* the compiled pattern */
PCRE2_INFO_NAMEENTRYSIZE, /* size of each entry in the table */
&name_entry_size); /* where to put the answer */
So real talk: you can't just grab names out of thin air. You legit have to ask the compiled pattern for the name table first (PCRE2_INFO_NAMETABLE gives you its address, stored into name_table), and then ask how big each entry in that table is (PCRE2_INFO_NAMEENTRYSIZE, landing in name_entry_size). The (void) casts are just "yeah I know I'm ignoring the return value, don't @ me" β the program doesn't check the info calls' results.
Then the actual scan:
/* Now we can scan the table and, for each entry, print the number, the name,
and the substring itself. In the 8-bit library the number is held in two
bytes, most significant first. */
tabptr = name_table;
for (i = 0; i < namecount; i++)
{
int n = (tabptr[0] << 8) | tabptr[1];
printf("(%d) %*s: %.*s\n", n, name_entry_size - 3, tabptr + 2,
(int)(ovector[2*n+1] - ovector[2*n]), subject + ovector[2*n]);
tabptr += name_entry_size;
}
}
Not me manually un-packing bytes in the year of our lord π β in the 8-bit library the group number lives in two bytes, most significant first, hence (tabptr[0] << 8) | tabptr[1] becoming n. Then the printf does the most: %*s with width name_entry_size - 3 prints the name (the -3 accounts for the two number bytes plus the terminator), tabptr + 2 skips past those number bytes, and %.*s with length (int)(ovector[2*n+1] - ovector[2*n]) starting at subject + ovector[2*n] prints the matched substring. Then tabptr += name_entry_size; hops to the next entry. Cute, iconic, done. π
Now the big mood shift β the -g era:
/*************************************************************************
* If the "-g" option was given on the command line, we want to continue *
* to search for additional matches in the subject string, in a similar *
* way to the /g option in Perl. This turns out to be trickier than you *
* might think because of the possibility of matching an empty string. *
* *
* To help with this task, PCRE2 provides the pcre2_next_match() helper. *
*************************************************************************/
if (!find_all) /* Check for -g */
{
pcre2_match_data_free(match_data); /* Release the memory that was used */
pcre2_code_free(re); /* for the match data and the pattern. */
return 0; /* Exit the program. */
}
So if find_all is false (no -g on the command line), we're out β free the match_data, free the compiled pattern re, and return 0; to exit the program happy. β¨
Fr fr though, the comment is dropping lore: finding subsequent matches is trickier than you might think because an empty-string match is a whole thing. That's exactly why pcre2_next_match() exists as a helper.
π the loop for second and subsequent matches
/* Loop for second and subsequent matches */
ovector_last[0] = ovector[0];
ovector_last[1] = ovector[1];
for (;;)
{
PCRE2_SIZE start_offset;
uint32_t options;
/* After each successful match, we use pcre2_next_match() to obtain the match
parameters for subsequent match attempts. */
if (!pcre2_next_match(match_data, &start_offset, &options))
break;
We stash the first match's ovector[0] and ovector[1] into ovector_last so we can compare later (that's the vibe check on progress), then it's an infinite for (;;) with two locals: PCRE2_SIZE start_offset; and uint32_t options;. pcre2_next_match(match_data, &start_offset, &options) hands us the parameters for round two β and if it returns false, we break; out. No cap.
/* Run the next matching operation */
rc = pcre2_match(
re, /* the compiled pattern */
subject, /* the subject string */
subject_length, /* the length of the subject */
start_offset, /* starting offset in the subject */
options, /* options */
match_data, /* block for storing the result */
NULL); /* use default match context */
/* If this match attempt fails, exit the loop for subsequent matches. */
if (rc == PCRE2_ERROR_NOMATCH)
break;
/* Other matching errors are not recoverable. */
if (rc < 0)
{
printf("Matching error %d\n", rc);
pcre2_match_data_free(match_data);
pcre2_code_free(re);
return 1;
}
Same seven-argument pcre2_match as before, except start_offset and options come from the helper now, and the match context is NULL (default match context, bestie). PCRE2_ERROR_NOMATCH β break; and we're done searching. Any other negative rc is not recoverable: print Matching error %d\n, free the match data, free the pattern, return 1;.
π¨ the "is this loop even moving" safety era
/* This demonstration program depends on pcre2_next_match() to ensure that the
loop for second and subsequent matches does not run forever. However, it would
be robust practice for a production application to verify this. The following
block of code shows how to do this. This error case is not reachable unless
there is a bug in PCRE2.
Because this program does not set the PCRE2_EXTRA_ALLOW_LOOKAROUND_BSK option,
the logic is simple. We verify that either ovector[1] has advanced, or that we
have an empty match touching the end of a previous non-empty match. See the
API documentation for guidance if your application uses
PCRE2_EXTRA_ALLOW_LOOKAROUND_BSK and searches for multiple matches. */
if (!(ovector[1] > ovector_last[1] ||
(ovector[1] == ovector[0] && ovector_last[1] > ovector_last[0] &&
ovector[1] == ovector_last[1])))
{
printf("\\K was used in an assertion to yield non-advancing matches.\n");
printf("Run abandoned\n");
pcre2_match_data_free(match_data);
pcre2_code_free(re);
return 1;
}
ovector_last[0] = ovector[0];
ovector_last[1] = ovector[1];
The tea here π΅: this demo relies on pcre2_next_match() to guarantee the loop doesn't run forever, but a real production app should verify that itself. That's what this block demonstrates. Note the caveat β this error case is not reachable unless there is a bug in PCRE2, and because the program does not set PCRE2_EXTRA_ALLOW_LOOKAROUND_BSK, the logic stays simple: either ovector[1] advanced, or we've got an empty match touching the end of a previous non-empty match. If neither? Print \K was used in an assertion to yield non-advancing matches. and Run abandoned, clean up, return 1;. Then update ovector_last and keep it pushing. (If your app does use PCRE2_EXTRA_ALLOW_LOOKAROUND_BSK and searches for multiple matches, the API documentation is your bestie.)
β match succeeded again, let's print
/* Match succeeded. */
printf("\nMatch succeeded again at offset %d\n", (int)ovector[0]);
/* The match succeeded, but the output vector wasn't big enough. This
should not happen. */
if (rc == 0)
printf("ovector was not big enough for all the captured substrings\n");
Offset printed, cast to int. And if rc == 0, the output vector wasn't big enough for all the captured substrings β which the comment swears should not happen, but the check is there anyway because we're thorough like that. π
/* We guard against patterns such as /(?=.\K)/ that use \K in an assertion to
set the start of a match later than its end. As explained above, this case
should not occur because this demonstration program does not set the
PCRE2_EXTRA_ALLOW_LOOKAROUND_BSK option, however, we do include code showing
how to detect it. */
if (ovector[0] > ovector[1])
{
printf("\\K was used in an assertion to set the match start after its end.\n"
"From end to start the match was: %.*s\n", (int)(ovector[0] - ovector[1]),
(char *)(subject + ovector[1]));
printf("Run abandoned\n");
pcre2_match_data_free(match_data);
pcre2_code_free(re);
return 1;
}
Patterns like /(?=.\K)/ can use \K inside an assertion to put the match start after its end β cursed behaviour, ngl. Again, it shouldn't occur here because the program doesn't set PCRE2_EXTRA_ALLOW_LOOKAROUND_BSK, but the detection code is included for the culture. ovector[0] > ovector[1] β print the warning plus From end to start the match was: %.*s\n (length (int)(ovector[0] - ovector[1]), starting at (char *)(subject + ovector[1])), then Run abandoned, free everything, return 1;. π
π¨οΈ print the substrings, again but with feeling
/* As before, show substrings stored in the output vector by number, and then
also any named substrings. */
for (i = 0; i < rc; i++)
{
PCRE2_SPTR substring_start = subject + ovector[2*i];
size_t substring_length = ovector[2*i+1] - ovector[2*i];
printf("%2d: %.*s\n", i, (int)substring_length, (char *)substring_start);
}
if (namecount == 0)
printf("No named substrings\n");
else
{
PCRE2_SPTR tabptr = name_table;
printf("Named substrings\n");
for (i = 0; i < namecount; i++)
{
int n = (tabptr[0] << 8) | tabptr[1];
printf("(%d) %*s: %.*s\n", n, name_entry_size - 3, tabptr + 2,
(int)(ovector[2*n+1] - ovector[2*n]), subject + ovector[2*n]);
tabptr += name_entry_size;
}
}
} /* End of loop to find second and subsequent matches */
Numbered substrings first: substring_start is subject + ovector[2*i], substring_length is ovector[2*i+1] - ovector[2*i], printed with "%2d: %.*s\n". Then, if namecount == 0 it's a cute little No named substrings; otherwise it's the same name-table scan from before, with tabptr re-declared and initialized right there to name_table, printing (%d) %*s: %.*s\n per entry and stepping by name_entry_size. And boom β that closes the loop. π
π«Ά the grand finale
printf("\n");
pcre2_match_data_free(match_data);
pcre2_code_free(re);
return 0;
}
/* End of pcre2demo.c */
A polite blank line, free match_data, free re, return 0;, close the brace β and that's the whole file. /* End of pcre2demo.c */ β periodt. π
That's the entire program, bestie. You just walked through compiling a pattern, running a single match, printing numbered and named substrings, and looping over every subsequent match safely. Genuinely iconic behaviour from pcre2demo.c. β¨π
And that's a wrap on PCRE2DEMO(3) β this page lives in PCRE2 10.47, dated 24 March 2025. Go write something cursed with \K in it, you've earned it. π¦πΈπ
π¦ where this page comes from
- fedora 43: pcre2-devel 10.47-1.fc43 Β· BSD-3-Clause AND FSFULLR AND X11 AND GPL-2.0-or-later AND FSFAP AND FSFUL AND GPL-3.0-or-later
- fedora 43: pcre2-devel 10.47-1.fc43 Β· BSD-3-Clause AND FSFULLR AND X11 AND GPL-2.0-or-later AND FSFAP AND FSFUL AND GPL-3.0-or-later
- fedora 44: pcre2-devel 10.47-1.fc44.1 Β· BSD-3-Clause AND FSFULLR AND X11 AND GPL-2.0-or-later AND FSFAP AND FSFUL AND GPL-3.0-or-later
- fedora 44: pcre2-devel 10.47-1.fc44.1 Β· BSD-3-Clause AND FSFULLR AND X11 AND GPL-2.0-or-later AND FSFAP AND FSFUL AND GPL-3.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms