1 /*************************************************
2 * PCRE2 DEMONSTRATION PROGRAM *
3 *************************************************/
5 /* This is a demonstration program to illustrate a straightforward way of
6 using the PCRE2 regular expression library from a C program. See the
7 pcre2sample documentation for a short discussion ("man pcre2sample" if you have
8 the PCRE2 man pages installed). PCRE2 is a revised API for the library, and is
9 incompatible with the original PCRE API.
11 There are actually three libraries, each supporting a different code unit
12 width. This demonstration program uses the 8-bit library. The default is to
13 process each code unit as a separate character, but if the pattern begins with
14 "(*UTF)", both it and the subject are treated as UTF-8 strings, where
15 characters may occupy multiple code units.
17 In Unix-like environments, if PCRE2 is installed in your standard system
18 libraries, you should be able to compile this program using this command:
20 cc -Wall pcre2demo.c -lpcre2-8 -o pcre2demo
22 If PCRE2 is not installed in a standard place, it is likely to be installed
23 with support for the pkg-config mechanism. If you have pkg-config, you can
24 compile this program using this command:
26 cc -Wall pcre2demo.c `pkg-config --cflags --libs libpcre2-8` -o pcre2demo
28 If you do not have pkg-config, you may have to use something like this:
30 cc -Wall pcre2demo.c -I/usr/local/include -L/usr/local/lib \
31 -R/usr/local/lib -lpcre2-8 -o pcre2demo
33 Replace "/usr/local/include" and "/usr/local/lib" with wherever the include and
34 library files for PCRE2 are installed on your system. Only some operating
35 systems (Solaris is one) use the -R option.
37 Building under Windows:
39 If you want to statically link this program against a non-dll .a file, you must
40 define PCRE2_STATIC before including pcre2.h, so in this environment, uncomment
41 the following line. */
43 /* #define PCRE2_STATIC */
45 /* The PCRE2_CODE_UNIT_WIDTH macro must be defined before including pcre2.h.
46 For a program that uses only one code unit width, setting it to 8, 16, or 32
47 makes it possible to use generic function names such as pcre2_compile(). Note
48 that just changing 8 to 16 (for example) is not sufficient to convert this
49 program to process 16-bit characters. Even in a fully 16-bit environment, where
50 string-handling functions such as strcmp() and printf() work with 16-bit
51 characters, the code for handling the table of named substrings will still need
54 #define PCRE2_CODE_UNIT_WIDTH 8
61 /**************************************************************************
62 * Here is the program. The API includes the concept of "contexts" for *
63 * setting up unusual interface requirements for compiling and matching, *
64 * such as custom memory managers and non-standard newline definitions. *
65 * This program does not do any of this, so it makes no use of contexts, *
66 * always passing NULL where a context could be given. *
67 **************************************************************************/
69 int main(int argc, char **argv)
72 PCRE2_SPTR pattern; /* PCRE2_SPTR is a pointer to unsigned code units of */
73 PCRE2_SPTR subject; /* the appropriate width (in this case, 8 bits). */
74 PCRE2_SPTR name_table;
85 uint32_t name_entry_size;
88 PCRE2_SIZE erroroffset;
91 size_t subject_length;
92 pcre2_match_data *match_data;
96 /**************************************************************************
97 * First, sort out the command line. There is only one possible option at *
98 * the moment, "-g" to request repeated matching to find all occurrences, *
99 * like Perl's /g option. We set the variable find_all to a non-zero value *
100 * if the -g option is present. *
101 **************************************************************************/
104 for (i = 1; i < argc; i++)
106 if (strcmp(argv[i], "-g") == 0) find_all = 1;
107 else if (argv[i][0] == '-')
109 printf("Unrecognised option %s\n", argv[i]);
115 /* After the options, we require exactly two arguments, which are the pattern,
116 and the subject string. */
120 printf("Exactly two arguments required: a regex and a subject string\n");
124 /* As pattern and subject are char arguments, they can be straightforwardly
125 cast to PCRE2_SPTR as we are working in 8-bit code units. */
127 pattern = (PCRE2_SPTR)argv[i];
128 subject = (PCRE2_SPTR)argv[i+1];
129 subject_length = strlen((char *)subject);
132 /*************************************************************************
133 * Now we are going to compile the regular expression pattern, and handle *
134 * any errors that are detected. *
135 *************************************************************************/
138 pattern, /* the pattern */
139 PCRE2_ZERO_TERMINATED, /* indicates pattern is zero-terminated */
140 0, /* default options */
141 &errornumber, /* for error number */
142 &erroroffset, /* for error offset */
143 NULL); /* use default compile context */
145 /* Compilation failed: print the error message and exit. */
149 PCRE2_UCHAR buffer[256];
150 pcre2_get_error_message(errornumber, buffer, sizeof(buffer));
151 printf("PCRE2 compilation failed at offset %d: %s\n", (int)erroroffset,
157 /*************************************************************************
158 * If the compilation succeeded, we call PCRE again, in order to do a *
159 * pattern match against the subject string. This does just ONE match. If *
160 * further matching is needed, it will be done below. Before running the *
161 * match we must set up a match_data block for holding the result. *
162 *************************************************************************/
164 /* Using this function ensures that the block is exactly the right size for
165 the number of capturing parentheses in the pattern. */
167 match_data = pcre2_match_data_create_from_pattern(re, NULL);
170 re, /* the compiled pattern */
171 subject, /* the subject string */
172 subject_length, /* the length of the subject */
173 0, /* start at offset 0 in the subject */
174 0, /* default options */
175 match_data, /* block for storing the result */
176 NULL); /* use default match context */
178 /* Matching failed: handle error cases */
184 case PCRE2_ERROR_NOMATCH: printf("No match\n"); break;
186 Handle other special cases if you like
188 default: printf("Matching error %d\n", rc); break;
190 pcre2_match_data_free(match_data); /* Release memory used for the match */
191 pcre2_code_free(re); /* data and the compiled pattern. */
195 /* Match succeded. Get a pointer to the output vector, where string offsets are
198 ovector = pcre2_get_ovector_pointer(match_data);
199 printf("Match succeeded at offset %d\n", (int)ovector[0]);
202 /*************************************************************************
203 * We have found the first match within the subject string. If the output *
204 * vector wasn't big enough, say so. Then output any substrings that were *
206 *************************************************************************/
208 /* The output vector wasn't big enough. This should not happen, because we used
209 pcre2_match_data_create_from_pattern() above. */
212 printf("ovector was not big enough for all the captured substrings\n");
214 /* We must guard against patterns such as /(?=.\K)/ that use \K in an assertion
215 to set the start of a match later than its end. In this demonstration program,
216 we just detect this case and give up. */
218 if (ovector[0] > ovector[1])
220 printf("\\K was used in an assertion to set the match start after its end.\n"
221 "From end to start the match was: %.*s\n", (int)(ovector[0] - ovector[1]),
222 (char *)(subject + ovector[1]));
223 printf("Run abandoned\n");
224 pcre2_match_data_free(match_data);
229 /* Show substrings stored in the output vector by number. Obviously, in a real
230 application you might want to do things other than print them. */
232 for (i = 0; i < rc; i++)
234 PCRE2_SPTR substring_start = subject + ovector[2*i];
235 size_t substring_length = ovector[2*i+1] - ovector[2*i];
236 printf("%2d: %.*s\n", i, (int)substring_length, (char *)substring_start);
240 /**************************************************************************
241 * That concludes the basic part of this demonstration program. We have *
242 * compiled a pattern, and performed a single match. The code that follows *
243 * shows first how to access named substrings, and then how to code for *
244 * repeated matches on the same subject. *
245 **************************************************************************/
247 /* See if there are any named substrings, and if so, show them by name. First
248 we have to extract the count of named parentheses from the pattern. */
250 (void)pcre2_pattern_info(
251 re, /* the compiled pattern */
252 PCRE2_INFO_NAMECOUNT, /* get the number of named substrings */
253 &namecount); /* where to put the answer */
255 if (namecount == 0) printf("No named substrings\n"); else
258 printf("Named substrings\n");
260 /* Before we can access the substrings, we must extract the table for
261 translating names to numbers, and the size of each entry in the table. */
263 (void)pcre2_pattern_info(
264 re, /* the compiled pattern */
265 PCRE2_INFO_NAMETABLE, /* address of the table */
266 &name_table); /* where to put the answer */
268 (void)pcre2_pattern_info(
269 re, /* the compiled pattern */
270 PCRE2_INFO_NAMEENTRYSIZE, /* size of each entry in the table */
271 &name_entry_size); /* where to put the answer */
273 /* Now we can scan the table and, for each entry, print the number, the name,
274 and the substring itself. In the 8-bit library the number is held in two
275 bytes, most significant first. */
278 for (i = 0; i < namecount; i++)
280 int n = (tabptr[0] << 8) | tabptr[1];
281 printf("(%d) %*s: %.*s\n", n, name_entry_size - 3, tabptr + 2,
282 (int)(ovector[2*n+1] - ovector[2*n]), subject + ovector[2*n]);
283 tabptr += name_entry_size;
288 /*************************************************************************
289 * If the "-g" option was given on the command line, we want to continue *
290 * to search for additional matches in the subject string, in a similar *
291 * way to the /g option in Perl. This turns out to be trickier than you *
292 * might think because of the possibility of matching an empty string. *
293 * What happens is as follows: *
295 * If the previous match was NOT for an empty string, we can just start *
296 * the next match at the end of the previous one. *
298 * If the previous match WAS for an empty string, we can't do that, as it *
299 * would lead to an infinite loop. Instead, a call of pcre2_match() is *
300 * made with the PCRE2_NOTEMPTY_ATSTART and PCRE2_ANCHORED flags set. The *
301 * first of these tells PCRE2 that an empty string at the start of the *
302 * subject is not a valid match; other possibilities must be tried. The *
303 * second flag restricts PCRE2 to one match attempt at the initial string *
304 * position. If this match succeeds, an alternative to the empty string *
305 * match has been found, and we can print it and proceed round the loop, *
306 * advancing by the length of whatever was found. If this match does not *
307 * succeed, we still stay in the loop, advancing by just one character. *
308 * In UTF-8 mode, which can be set by (*UTF) in the pattern, this may be *
309 * more than one byte. *
311 * However, there is a complication concerned with newlines. When the *
312 * newline convention is such that CRLF is a valid newline, we must *
313 * advance by two characters rather than one. The newline convention can *
314 * be set in the regex by (*CR), etc.; if not, we must find the default. *
315 *************************************************************************/
317 if (!find_all) /* Check for -g */
319 pcre2_match_data_free(match_data); /* Release the memory that was used */
320 pcre2_code_free(re); /* for the match data and the pattern. */
321 return 0; /* Exit the program. */
324 /* Before running the loop, check for UTF-8 and whether CRLF is a valid newline
325 sequence. First, find the options with which the regex was compiled and extract
328 (void)pcre2_pattern_info(re, PCRE2_INFO_ALLOPTIONS, &option_bits);
329 utf8 = (option_bits & PCRE2_UTF) != 0;
331 /* Now find the newline convention and see whether CRLF is a valid newline
334 (void)pcre2_pattern_info(re, PCRE2_INFO_NEWLINE, &newline);
335 crlf_is_newline = newline == PCRE2_NEWLINE_ANY ||
336 newline == PCRE2_NEWLINE_CRLF ||
337 newline == PCRE2_NEWLINE_ANYCRLF;
339 /* Loop for second and subsequent matches */
343 uint32_t options = 0; /* Normally no options */
344 PCRE2_SIZE start_offset = ovector[1]; /* Start at end of previous match */
346 /* If the previous match was for an empty string, we are finished if we are
347 at the end of the subject. Otherwise, arrange to run another match at the
348 same point to see if a non-empty match can be found. */
350 if (ovector[0] == ovector[1])
352 if (ovector[0] == subject_length) break;
353 options = PCRE2_NOTEMPTY_ATSTART | PCRE2_ANCHORED;
356 /* If the previous match was not an empty string, there is one tricky case to
357 consider. If a pattern contains \K within a lookbehind assertion at the
358 start, the end of the matched string can be at the offset where the match
359 started. Without special action, this leads to a loop that keeps on matching
360 the same substring. We must detect this case and arrange to move the start on
361 by one character. The pcre2_get_startchar() function returns the starting
362 offset that was passed to pcre2_match(). */
366 PCRE2_SIZE startchar = pcre2_get_startchar(match_data);
367 if (start_offset <= startchar)
369 if (startchar >= subject_length) break; /* Reached end of subject. */
370 start_offset = startchar + 1; /* Advance by one character. */
371 if (utf8) /* If UTF-8, it may be more */
372 { /* than one code unit. */
373 for (; start_offset < subject_length; start_offset++)
374 if ((subject[start_offset] & 0xc0) != 0x80) break;
379 /* Run the next matching operation */
382 re, /* the compiled pattern */
383 subject, /* the subject string */
384 subject_length, /* the length of the subject */
385 start_offset, /* starting offset in the subject */
386 options, /* options */
387 match_data, /* block for storing the result */
388 NULL); /* use default match context */
390 /* This time, a result of NOMATCH isn't an error. If the value in "options"
391 is zero, it just means we have found all possible matches, so the loop ends.
392 Otherwise, it means we have failed to find a non-empty-string match at a
393 point where there was a previous empty-string match. In this case, we do what
394 Perl does: advance the matching position by one character, and continue. We
395 do this by setting the "end of previous match" offset, because that is picked
396 up at the top of the loop as the point at which to start again.
398 There are two complications: (a) When CRLF is a valid newline sequence, and
399 the current position is just before it, advance by an extra byte. (b)
400 Otherwise we must ensure that we skip an entire UTF character if we are in
403 if (rc == PCRE2_ERROR_NOMATCH)
405 if (options == 0) break; /* All matches found */
406 ovector[1] = start_offset + 1; /* Advance one code unit */
407 if (crlf_is_newline && /* If CRLF is a newline & */
408 start_offset < subject_length - 1 && /* we are at CRLF, */
409 subject[start_offset] == '\r' &&
410 subject[start_offset + 1] == '\n')
411 ovector[1] += 1; /* Advance by one more. */
412 else if (utf8) /* Otherwise, ensure we */
413 { /* advance a whole UTF-8 */
414 while (ovector[1] < subject_length) /* character. */
416 if ((subject[ovector[1]] & 0xc0) != 0x80) break;
420 continue; /* Go round the loop again */
423 /* Other matching errors are not recoverable. */
427 printf("Matching error %d\n", rc);
428 pcre2_match_data_free(match_data);
435 printf("\nMatch succeeded again at offset %d\n", (int)ovector[0]);
437 /* The match succeeded, but the output vector wasn't big enough. This
438 should not happen. */
441 printf("ovector was not big enough for all the captured substrings\n");
443 /* We must guard against patterns such as /(?=.\K)/ that use \K in an
444 assertion to set the start of a match later than its end. In this
445 demonstration program, we just detect this case and give up. */
447 if (ovector[0] > ovector[1])
449 printf("\\K was used in an assertion to set the match start after its end.\n"
450 "From end to start the match was: %.*s\n", (int)(ovector[0] - ovector[1]),
451 (char *)(subject + ovector[1]));
452 printf("Run abandoned\n");
453 pcre2_match_data_free(match_data);
458 /* As before, show substrings stored in the output vector by number, and then
459 also any named substrings. */
461 for (i = 0; i < rc; i++)
463 PCRE2_SPTR substring_start = subject + ovector[2*i];
464 size_t substring_length = ovector[2*i+1] - ovector[2*i];
465 printf("%2d: %.*s\n", i, (int)substring_length, (char *)substring_start);
468 if (namecount == 0) printf("No named substrings\n"); else
470 PCRE2_SPTR tabptr = name_table;
471 printf("Named substrings\n");
472 for (i = 0; i < namecount; i++)
474 int n = (tabptr[0] << 8) | tabptr[1];
475 printf("(%d) %*s: %.*s\n", n, name_entry_size - 3, tabptr + 2,
476 (int)(ovector[2*n+1] - ovector[2*n]), subject + ovector[2*n]);
477 tabptr += name_entry_size;
480 } /* End of loop to find second and subsequent matches */
483 pcre2_match_data_free(match_data);
488 /* End of pcre2demo.c */