1/*************************************************
2* PCRE2 DEMONSTRATION PROGRAM *
3*************************************************/
4
5/* This is a demonstration program to illustrate a straightforward way of
6using the PCRE2 regular expression library from a C program. See the
7pcre2sample documentation for a short discussion ("man pcre2sample" if you have
8the PCRE2 man pages installed). PCRE2 is a revised API for the library, and is
9incompatible with the original PCRE API.
10
11There are actually three libraries, each supporting a different code unit
12width. This demonstration program uses the 8‐bit library. The default is to
13process 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
15characters may occupy multiple code units.
16
17In Unix‐like environments, if PCRE2 is installed in your standard system
18libraries, you should be able to compile this program using this command:
19
20cc ‐Wall pcre2demo.c ‐lpcre2‐8 ‐o pcre2demo
21
22If PCRE2 is not installed in a standard place, it is likely to be installed
23with support for the pkg‐config mechanism. If you have pkg‐config, you can
24compile this program using this command:
25
26cc ‐Wall pcre2demo.c ‘pkg‐config ‐‐cflags ‐‐libs libpcre2‐8‘ ‐o pcre2demo
27
28If you do not have pkg‐config, you may have to use something like this:
29
30cc ‐Wall pcre2demo.c ‐I/usr/local/include ‐L/usr/local/lib \
31 ‐R/usr/local/lib ‐lpcre2‐8 ‐o pcre2demo
32
33Replace "/usr/local/include" and "/usr/local/lib" with wherever the include and
34library files for PCRE2 are installed on your system. Only some operating
35systems (Solaris is one) use the ‐R option.
36
37Building under Windows:
38
39If you want to statically link this program against a non‐dll .a file, you must
40define PCRE2_STATIC before including pcre2.h, so in this environment, uncomment
41the following line. */
42
43/* #define PCRE2_STATIC */
44
45/* The PCRE2_CODE_UNIT_WIDTH macro must be defined before including pcre2.h.
46For a program that uses only one code unit width, setting it to 8, 16, or 32
47makes it possible to use generic function names such as pcre2_compile(). Note
48that just changing 8 to 16 (for example) is not sufficient to convert this
49program to process 16‐bit characters. Even in a fully 16‐bit environment, where
50string‐handling functions such as strcmp() and printf() work with 16‐bit
51characters, the code for handling the table of named substrings will still need
52to be modified. */
53
54#define PCRE2_CODE_UNIT_WIDTH 8
55
56#include <stdio.h>
57#include <string.h>
58#include <pcre2.h>
59
60
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**************************************************************************/
68
69int main(int argc, char **argv)
70{
71pcre2_code *re;
72PCRE2_SPTR pattern; /* PCRE2_SPTR is a pointer to unsigned code units of */
73PCRE2_SPTR subject; /* the appropriate width (in this case, 8 bits). */
74PCRE2_SPTR name_table;
75
76int crlf_is_newline;
77int errornumber;
78int find_all;
79int i;
80int rc;
81int utf8;
82
83uint32_t option_bits;
84uint32_t namecount;
85uint32_t name_entry_size;
86uint32_t newline;
87
88PCRE2_SIZE erroroffset;
89PCRE2_SIZE *ovector;
90PCRE2_SIZE subject_length;
91
92pcre2_match_data *match_data;
93
94
95/**************************************************************************
96* First, sort out the command line. There is only one possible option at *
97* the moment, "‐g" to request repeated matching to find all occurrences, *
98* like Perl’s /g option. We set the variable find_all to a non‐zero value *
99* if the ‐g option is present. *
100**************************************************************************/
101
102find_all = 0;
103for (i = 1; i < argc; i++)
104 {
105 if (strcmp(argv[i], "‐g") == 0) find_all = 1;
106 else if (argv[i][0] == ’‐’)
107 {
108 printf("Unrecognised option %s\n", argv[i]);
109 return 1;
110 }
111 else break;
112 }
113
114/* After the options, we require exactly two arguments, which are the pattern,
115and the subject string. */
116
117if (argc ‐ i != 2)
118 {
119 printf("Exactly two arguments required: a regex and a subject string\n");
120 return 1;
121 }
122
123/* Pattern and subject are char arguments, so they can be straightforwardly
124cast to PCRE2_SPTR because we are working in 8‐bit code units. The subject
125length is cast to PCRE2_SIZE for completeness, though PCRE2_SIZE is in fact
126defined to be size_t. */
127
128pattern = (PCRE2_SPTR)argv[i];
129subject = (PCRE2_SPTR)argv[i+1];
130subject_length = (PCRE2_SIZE)strlen((char *)subject);
131
132
133/*************************************************************************
134* Now we are going to compile the regular expression pattern, and handle *
135* any errors that are detected. *
136*************************************************************************/
137
138re = pcre2_compile(
139 pattern, /* the pattern */
140 PCRE2_ZERO_TERMINATED, /* indicates pattern is zero‐terminated */
141 0, /* default options */
142 &errornumber, /* for error number */
143 &erroroffset, /* for error offset */
144 NULL); /* use default compile context */
145
146/* Compilation failed: print the error message and exit. */
147
148if (re == NULL)
149 {
150 PCRE2_UCHAR buffer[256];
151 pcre2_get_error_message(errornumber, buffer, sizeof(buffer));
152 printf("PCRE2 compilation failed at offset %d: %s\n", (int)erroroffset,
153 buffer);
154 return 1;
155 }
156
157
158/*************************************************************************
159* If the compilation succeeded, we call PCRE2 again, in order to do a *
160* pattern match against the subject string. This does just ONE match. If *
161* further matching is needed, it will be done below. Before running the *
162* match we must set up a match_data block for holding the result. Using *
163* pcre2_match_data_create_from_pattern() ensures that the block is *
164* exactly the right size for the number of capturing parentheses in the *
165* pattern. If you need to know the actual size of a match_data block as *
166* a number of bytes, you can find it like this: *
167* *
168* PCRE2_SIZE match_data_size = pcre2_get_match_data_size(match_data); *
169*************************************************************************/
170
171match_data = pcre2_match_data_create_from_pattern(re, NULL);
172
173/* Now run the match. */
174
175rc = pcre2_match(
176 re, /* the compiled pattern */
177 subject, /* the subject string */
178 subject_length, /* the length of the subject */
179 0, /* start at offset 0 in the subject */
180 0, /* default options */
181 match_data, /* block for storing the result */
182 NULL); /* use default match context */
183
184/* Matching failed: handle error cases */
185
186if (rc < 0)
187 {
188 switch(rc)
189 {
190 case PCRE2_ERROR_NOMATCH: printf("No match\n"); break;
191 /*
192 Handle other special cases if you like
193 */
194 default: printf("Matching error %d\n", rc); break;
195 }
196 pcre2_match_data_free(match_data); /* Release memory used for the match */
197 pcre2_code_free(re); /* data and the compiled pattern. */
198 return 1;
199 }
200
201/* Match succeded. Get a pointer to the output vector, where string offsets are
202stored. */
203
204ovector = pcre2_get_ovector_pointer(match_data);
205printf("Match succeeded at offset %d\n", (int)ovector[0]);
206
207
208/*************************************************************************
209* We have found the first match within the subject string. If the output *
210* vector wasn’t big enough, say so. Then output any substrings that were *
211* captured. *
212*************************************************************************/
213
214/* The output vector wasn’t big enough. This should not happen, because we used
215pcre2_match_data_create_from_pattern() above. */
216
217if (rc == 0)
218 printf("ovector was not big enough for all the captured substrings\n");
219
220/* We must guard against patterns such as /(?=.\K)/ that use \K in an assertion
221to set the start of a match later than its end. In this demonstration program,
222we just detect this case and give up. */
223
224if (ovector[0] > ovector[1])
225 {
226 printf("\\K was used in an assertion to set the match start after its end.\n"
227 "From end to start the match was: %.*s\n", (int)(ovector[0] ‐ ovector[1]),
228 (char *)(subject + ovector[1]));
229 printf("Run abandoned\n");
230 pcre2_match_data_free(match_data);
231 pcre2_code_free(re);
232 return 1;
233 }
234
235/* Show substrings stored in the output vector by number. Obviously, in a real
236application you might want to do things other than print them. */
237
238for (i = 0; i < rc; i++)
239 {
240 PCRE2_SPTR substring_start = subject + ovector[2*i];
241 PCRE2_SIZE substring_length = ovector[2*i+1] ‐ ovector[2*i];
242 printf("%2d: %.*s\n", i, (int)substring_length, (char *)substring_start);
243 }
244
245
246/**************************************************************************
247* That concludes the basic part of this demonstration program. We have *
248* compiled a pattern, and performed a single match. The code that follows *
249* shows first how to access named substrings, and then how to code for *
250* repeated matches on the same subject. *
251**************************************************************************/
252
253/* See if there are any named substrings, and if so, show them by name. First
254we have to extract the count of named parentheses from the pattern. */
255
256(void)pcre2_pattern_info(
257 re, /* the compiled pattern */
258 PCRE2_INFO_NAMECOUNT, /* get the number of named substrings */
259 &namecount); /* where to put the answer */
260
261if (namecount == 0) printf("No named substrings\n"); else
262 {
263 PCRE2_SPTR tabptr;
264 printf("Named substrings\n");
265
266 /* Before we can access the substrings, we must extract the table for
267 translating names to numbers, and the size of each entry in the table. */
268
269 (void)pcre2_pattern_info(
270 re, /* the compiled pattern */
271 PCRE2_INFO_NAMETABLE, /* address of the table */
272 &name_table); /* where to put the answer */
273
274 (void)pcre2_pattern_info(
275 re, /* the compiled pattern */
276 PCRE2_INFO_NAMEENTRYSIZE, /* size of each entry in the table */
277 &name_entry_size); /* where to put the answer */
278
279 /* Now we can scan the table and, for each entry, print the number, the name,
280 and the substring itself. In the 8‐bit library the number is held in two
281 bytes, most significant first. */
282
283 tabptr = name_table;
284 for (i = 0; i < namecount; i++)
285 {
286 int n = (tabptr[0] << 8) | tabptr[1];
287 printf("(%d) %*s: %.*s\n", n, name_entry_size ‐ 3, tabptr + 2,
288 (int)(ovector[2*n+1] ‐ ovector[2*n]), subject + ovector[2*n]);
289 tabptr += name_entry_size;
290 }
291 }
292
293
294/*************************************************************************
295* If the "‐g" option was given on the command line, we want to continue *
296* to search for additional matches in the subject string, in a similar *
297* way to the /g option in Perl. This turns out to be trickier than you *
298* might think because of the possibility of matching an empty string. *
299* What happens is as follows: *
300* *
301* If the previous match was NOT for an empty string, we can just start *
302* the next match at the end of the previous one. *
303* *
304* If the previous match WAS for an empty string, we can’t do that, as it *
305* would lead to an infinite loop. Instead, a call of pcre2_match() is *
306* made with the PCRE2_NOTEMPTY_ATSTART and PCRE2_ANCHORED flags set. The *
307* first of these tells PCRE2 that an empty string at the start of the *
308* subject is not a valid match; other possibilities must be tried. The *
309* second flag restricts PCRE2 to one match attempt at the initial string *
310* position. If this match succeeds, an alternative to the empty string *
311* match has been found, and we can print it and proceed round the loop, *
312* advancing by the length of whatever was found. If this match does not *
313* succeed, we still stay in the loop, advancing by just one character. *
314* In UTF‐8 mode, which can be set by (*UTF) in the pattern, this may be *
315* more than one byte. *
316* *
317* However, there is a complication concerned with newlines. When the *
318* newline convention is such that CRLF is a valid newline, we must *
319* advance by two characters rather than one. The newline convention can *
320* be set in the regex by (*CR), etc.; if not, we must find the default. *
321*************************************************************************/
322
323if (!find_all) /* Check for ‐g */
324 {
325 pcre2_match_data_free(match_data); /* Release the memory that was used */
326 pcre2_code_free(re); /* for the match data and the pattern. */
327 return 0; /* Exit the program. */
328 }
329
330/* Before running the loop, check for UTF‐8 and whether CRLF is a valid newline
331sequence. First, find the options with which the regex was compiled and extract
332the UTF state. */
333
334(void)pcre2_pattern_info(re, PCRE2_INFO_ALLOPTIONS, &option_bits);
335utf8 = (option_bits & PCRE2_UTF) != 0;
336
337/* Now find the newline convention and see whether CRLF is a valid newline
338sequence. */
339
340(void)pcre2_pattern_info(re, PCRE2_INFO_NEWLINE, &newline);
341crlf_is_newline = newline == PCRE2_NEWLINE_ANY ||
342 newline == PCRE2_NEWLINE_CRLF ||
343 newline == PCRE2_NEWLINE_ANYCRLF;
344
345/* Loop for second and subsequent matches */
346
347for (;;)
348 {
349 uint32_t options = 0; /* Normally no options */
350 PCRE2_SIZE start_offset = ovector[1]; /* Start at end of previous match */
351
352 /* If the previous match was for an empty string, we are finished if we are
353 at the end of the subject. Otherwise, arrange to run another match at the
354 same point to see if a non‐empty match can be found. */
355
356 if (ovector[0] == ovector[1])
357 {
358 if (ovector[0] == subject_length) break;
359 options = PCRE2_NOTEMPTY_ATSTART | PCRE2_ANCHORED;
360 }
361
362 /* If the previous match was not an empty string, there is one tricky case to
363 consider. If a pattern contains \K within a lookbehind assertion at the
364 start, the end of the matched string can be at the offset where the match
365 started. Without special action, this leads to a loop that keeps on matching
366 the same substring. We must detect this case and arrange to move the start on
367 by one character. The pcre2_get_startchar() function returns the starting
368 offset that was passed to pcre2_match(). */
369
370 else
371 {
372 PCRE2_SIZE startchar = pcre2_get_startchar(match_data);
373 if (start_offset <= startchar)
374 {
375 if (startchar >= subject_length) break; /* Reached end of subject. */
376 start_offset = startchar + 1; /* Advance by one character. */
377 if (utf8) /* If UTF‐8, it may be more */
378 { /* than one code unit. */
379 for (; start_offset < subject_length; start_offset++)
380 if ((subject[start_offset] & 0xc0) != 0x80) break;
381 }
382 }
383 }
384
385 /* Run the next matching operation */
386
387 rc = pcre2_match(
388 re, /* the compiled pattern */
389 subject, /* the subject string */
390 subject_length, /* the length of the subject */
391 start_offset, /* starting offset in the subject */
392 options, /* options */
393 match_data, /* block for storing the result */
394 NULL); /* use default match context */
395
396 /* This time, a result of NOMATCH isn’t an error. If the value in "options"
397 is zero, it just means we have found all possible matches, so the loop ends.
398 Otherwise, it means we have failed to find a non‐empty‐string match at a
399 point where there was a previous empty‐string match. In this case, we do what
400 Perl does: advance the matching position by one character, and continue. We
401 do this by setting the "end of previous match" offset, because that is picked
402 up at the top of the loop as the point at which to start again.
403
404 There are two complications: (a) When CRLF is a valid newline sequence, and
405 the current position is just before it, advance by an extra byte. (b)
406 Otherwise we must ensure that we skip an entire UTF character if we are in
407 UTF mode. */
408
409 if (rc == PCRE2_ERROR_NOMATCH)
410 {
411 if (options == 0) break; /* All matches found */
412 ovector[1] = start_offset + 1; /* Advance one code unit */
413 if (crlf_is_newline && /* If CRLF is a newline & */
414 start_offset < subject_length ‐ 1 && /* we are at CRLF, */
415 subject[start_offset] == ’\r’ &&
416 subject[start_offset + 1] == ’\n’)
417 ovector[1] += 1; /* Advance by one more. */
418 else if (utf8) /* Otherwise, ensure we */
419 { /* advance a whole UTF‐8 */
420 while (ovector[1] < subject_length) /* character. */
421 {
422 if ((subject[ovector[1]] & 0xc0) != 0x80) break;
423 ovector[1] += 1;
424 }
425 }
426 continue; /* Go round the loop again */
427 }
428
429 /* Other matching errors are not recoverable. */
430
431 if (rc < 0)
432 {
433 printf("Matching error %d\n", rc);
434 pcre2_match_data_free(match_data);
435 pcre2_code_free(re);
436 return 1;
437 }
438
439 /* Match succeded */
440
441 printf("\nMatch succeeded again at offset %d\n", (int)ovector[0]);
442
443 /* The match succeeded, but the output vector wasn’t big enough. This
444 should not happen. */
445
446 if (rc == 0)
447 printf("ovector was not big enough for all the captured substrings\n");
448
449 /* We must guard against patterns such as /(?=.\K)/ that use \K in an
450 assertion to set the start of a match later than its end. In this
451 demonstration program, we just detect this case and give up. */
452
453 if (ovector[0] > ovector[1])
454 {
455 printf("\\K was used in an assertion to set the match start after its end.\n"
456 "From end to start the match was: %.*s\n", (int)(ovector[0] ‐ ovector[1]),
457 (char *)(subject + ovector[1]));
458 printf("Run abandoned\n");
459 pcre2_match_data_free(match_data);
460 pcre2_code_free(re);
461 return 1;
462 }
463
464 /* As before, show substrings stored in the output vector by number, and then
465 also any named substrings. */
466
467 for (i = 0; i < rc; i++)
468 {
469 PCRE2_SPTR substring_start = subject + ovector[2*i];
470 size_t substring_length = ovector[2*i+1] ‐ ovector[2*i];
471 printf("%2d: %.*s\n", i, (int)substring_length, (char *)substring_start);
472 }
473
474 if (namecount == 0) printf("No named substrings\n"); else
475 {
476 PCRE2_SPTR tabptr = name_table;
477 printf("Named substrings\n");
478 for (i = 0; i < namecount; i++)
479 {
480 int n = (tabptr[0] << 8) | tabptr[1];
481 printf("(%d) %*s: %.*s\n", n, name_entry_size ‐ 3, tabptr + 2,
482 (int)(ovector[2*n+1] ‐ ovector[2*n]), subject + ovector[2*n]);
483 tabptr += name_entry_size;
484 }
485 }
486 } /* End of loop to find second and subsequent matches */
487
488printf("\n");
489pcre2_match_data_free(match_data);
490pcre2_code_free(re);
491return 0;
492}
493
494/* End of pcre2demo.c */
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528