Home | History | Annotate | Download | only in src
      1 /*************************************************
      2 *           PCRE2 DEMONSTRATION PROGRAM          *
      3 *************************************************/
      4 
      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.
     10 
     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.
     16 
     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:
     19 
     20 cc -Wall pcre2demo.c -lpcre2-8 -o pcre2demo
     21 
     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:
     25 
     26 cc -Wall pcre2demo.c `pkg-config --cflags --libs libpcre2-8` -o pcre2demo
     27 
     28 If you do not have pkg-config, you may have to use something like this:
     29 
     30 cc -Wall pcre2demo.c -I/usr/local/include -L/usr/local/lib \
     31   -R/usr/local/lib -lpcre2-8 -o pcre2demo
     32 
     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.
     36 
     37 Building under Windows:
     38 
     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. */
     42 
     43 /* #define PCRE2_STATIC */
     44 
     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
     52 to 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 
     69 int main(int argc, char **argv)
     70 {
     71 pcre2_code *re;
     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;
     75 
     76 int crlf_is_newline;
     77 int errornumber;
     78 int find_all;
     79 int i;
     80 int rc;
     81 int utf8;
     82 
     83 uint32_t option_bits;
     84 uint32_t namecount;
     85 uint32_t name_entry_size;
     86 uint32_t newline;
     87 
     88 PCRE2_SIZE erroroffset;
     89 PCRE2_SIZE *ovector;
     90 
     91 size_t subject_length;
     92 pcre2_match_data *match_data;
     93 
     94 
     95 
     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 **************************************************************************/
    102 
    103 find_all = 0;
    104 for (i = 1; i < argc; i++)
    105   {
    106   if (strcmp(argv[i], "-g") == 0) find_all = 1;
    107   else if (argv[i][0] == '-')
    108     {
    109     printf("Unrecognised option %s\n", argv[i]);
    110     return 1;
    111     }
    112   else break;
    113   }
    114 
    115 /* After the options, we require exactly two arguments, which are the pattern,
    116 and the subject string. */
    117 
    118 if (argc - i != 2)
    119   {
    120   printf("Exactly two arguments required: a regex and a subject string\n");
    121   return 1;
    122   }
    123 
    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. */
    126 
    127 pattern = (PCRE2_SPTR)argv[i];
    128 subject = (PCRE2_SPTR)argv[i+1];
    129 subject_length = strlen((char *)subject);
    130 
    131 
    132 /*************************************************************************
    133 * Now we are going to compile the regular expression pattern, and handle *
    134 * any errors that are detected.                                          *
    135 *************************************************************************/
    136 
    137 re = pcre2_compile(
    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 */
    144 
    145 /* Compilation failed: print the error message and exit. */
    146 
    147 if (re == NULL)
    148   {
    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,
    152     buffer);
    153   return 1;
    154   }
    155 
    156 
    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 *************************************************************************/
    163 
    164 /* Using this function ensures that the block is exactly the right size for
    165 the number of capturing parentheses in the pattern. */
    166 
    167 match_data = pcre2_match_data_create_from_pattern(re, NULL);
    168 
    169 rc = pcre2_match(
    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 */
    177 
    178 /* Matching failed: handle error cases */
    179 
    180 if (rc < 0)
    181   {
    182   switch(rc)
    183     {
    184     case PCRE2_ERROR_NOMATCH: printf("No match\n"); break;
    185     /*
    186     Handle other special cases if you like
    187     */
    188     default: printf("Matching error %d\n", rc); break;
    189     }
    190   pcre2_match_data_free(match_data);   /* Release memory used for the match */
    191   pcre2_code_free(re);                 /* data and the compiled pattern. */
    192   return 1;
    193   }
    194 
    195 /* Match succeded. Get a pointer to the output vector, where string offsets are
    196 stored. */
    197 
    198 ovector = pcre2_get_ovector_pointer(match_data);
    199 printf("Match succeeded at offset %d\n", (int)ovector[0]);
    200 
    201 
    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 *
    205 * captured.                                                              *
    206 *************************************************************************/
    207 
    208 /* The output vector wasn't big enough. This should not happen, because we used
    209 pcre2_match_data_create_from_pattern() above. */
    210 
    211 if (rc == 0)
    212   printf("ovector was not big enough for all the captured substrings\n");
    213 
    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. */
    217 
    218 if (ovector[0] > ovector[1])
    219   {
    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);
    225   pcre2_code_free(re);
    226   return 1;
    227   }
    228 
    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. */
    231 
    232 for (i = 0; i < rc; i++)
    233   {
    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);
    237   }
    238 
    239 
    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 **************************************************************************/
    246 
    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. */
    249 
    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 */
    254 
    255 if (namecount == 0) printf("No named substrings\n"); else
    256   {
    257   PCRE2_SPTR tabptr;
    258   printf("Named substrings\n");
    259 
    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. */
    262 
    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 */
    267 
    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 */
    272 
    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. */
    276 
    277   tabptr = name_table;
    278   for (i = 0; i < namecount; i++)
    279     {
    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;
    284     }
    285   }
    286 
    287 
    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:                                            *
    294 *                                                                        *
    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.                         *
    297 *                                                                        *
    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.                                                    *
    310 *                                                                        *
    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 *************************************************************************/
    316 
    317 if (!find_all)     /* Check for -g */
    318   {
    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. */
    322   }
    323 
    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
    326 the UTF state. */
    327 
    328 (void)pcre2_pattern_info(re, PCRE2_INFO_ALLOPTIONS, &option_bits);
    329 utf8 = (option_bits & PCRE2_UTF) != 0;
    330 
    331 /* Now find the newline convention and see whether CRLF is a valid newline
    332 sequence. */
    333 
    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;
    338 
    339 /* Loop for second and subsequent matches */
    340 
    341 for (;;)
    342   {
    343   uint32_t options = 0;                   /* Normally no options */
    344   PCRE2_SIZE start_offset = ovector[1];   /* Start at end of previous match */
    345 
    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. */
    349 
    350   if (ovector[0] == ovector[1])
    351     {
    352     if (ovector[0] == subject_length) break;
    353     options = PCRE2_NOTEMPTY_ATSTART | PCRE2_ANCHORED;
    354     }
    355 
    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(). */
    363 
    364   else
    365     {
    366     PCRE2_SIZE startchar = pcre2_get_startchar(match_data);
    367     if (start_offset <= startchar)
    368       {
    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;
    375         }
    376       }
    377     }
    378 
    379   /* Run the next matching operation */
    380 
    381   rc = pcre2_match(
    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 */
    389 
    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.
    397 
    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
    401   UTF mode. */
    402 
    403   if (rc == PCRE2_ERROR_NOMATCH)
    404     {
    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. */
    415         {
    416         if ((subject[ovector[1]] & 0xc0) != 0x80) break;
    417         ovector[1] += 1;
    418         }
    419       }
    420     continue;    /* Go round the loop again */
    421     }
    422 
    423   /* Other matching errors are not recoverable. */
    424 
    425   if (rc < 0)
    426     {
    427     printf("Matching error %d\n", rc);
    428     pcre2_match_data_free(match_data);
    429     pcre2_code_free(re);
    430     return 1;
    431     }
    432 
    433   /* Match succeded */
    434 
    435   printf("\nMatch succeeded again at offset %d\n", (int)ovector[0]);
    436 
    437   /* The match succeeded, but the output vector wasn't big enough. This
    438   should not happen. */
    439 
    440   if (rc == 0)
    441     printf("ovector was not big enough for all the captured substrings\n");
    442 
    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. */
    446 
    447   if (ovector[0] > ovector[1])
    448     {
    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);
    454     pcre2_code_free(re);
    455     return 1;
    456     }
    457 
    458   /* As before, show substrings stored in the output vector by number, and then
    459   also any named substrings. */
    460 
    461   for (i = 0; i < rc; i++)
    462     {
    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);
    466     }
    467 
    468   if (namecount == 0) printf("No named substrings\n"); else
    469     {
    470     PCRE2_SPTR tabptr = name_table;
    471     printf("Named substrings\n");
    472     for (i = 0; i < namecount; i++)
    473       {
    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;
    478       }
    479     }
    480   }      /* End of loop to find second and subsequent matches */
    481 
    482 printf("\n");
    483 pcre2_match_data_free(match_data);
    484 pcre2_code_free(re);
    485 return 0;
    486 }
    487 
    488 /* End of pcre2demo.c */
    489