Attachment 'pcredemo.c'

Download

   1 #ifndef PCRE2_CODE_UNIT_WIDTH
   2 #define PCRE2_CODE_UNIT_WIDTH 8
   3 #endif
   4 
   5 #include <stdio.h>
   6 #include <string.h>
   7 #include <pcre2.h>
   8 
   9 int main(int argc, char **argv)
  10 {
  11     pcre2_code *re;
  12     PCRE2_SPTR pattern;     /* PCRE2_SPTR is a pointer to unsigned code units of */
  13     PCRE2_SPTR subject;     /* the appropriate width (in this case, 8 bits). */
  14 
  15     int errnum;
  16     int i, rc;
  17 
  18     PCRE2_SIZE erroffs;
  19     PCRE2_SIZE *ovector;
  20     PCRE2_SIZE subject_length;
  21 
  22     pcre2_match_data *match_data;
  23 
  24     if (argc != 3) {
  25         printf("Exactly two arguments required: a regex and a subject string\n");
  26         return 1;
  27     }
  28 
  29     pattern = (PCRE2_SPTR)argv[1];
  30     subject = (PCRE2_SPTR)argv[2];
  31     subject_length = (PCRE2_SIZE)strlen((char *)subject);
  32 
  33     re = pcre2_compile(pattern, PCRE2_ZERO_TERMINATED, PCRE2_UCP, &errnum, &erroffs, NULL);
  34 
  35     if (re == NULL) {
  36         PCRE2_UCHAR buffer[256];
  37         pcre2_get_error_message(errnum, buffer, sizeof(buffer));
  38         printf("PCRE2 compilation failed at offset %d: %s\n", (int)erroffs,
  39                buffer);
  40         return 1;
  41     }
  42 
  43     match_data = pcre2_match_data_create_from_pattern(re, NULL);
  44 
  45     rc = pcre2_match(re, subject, subject_length, 0, 0, match_data, NULL);
  46 
  47     if (rc < 0) {
  48         switch(rc) {
  49         case PCRE2_ERROR_NOMATCH:
  50             printf("No match\n");
  51             break;
  52         default:
  53             printf("Matching error %d\n", rc);
  54             break;
  55         }
  56         pcre2_match_data_free(match_data);   /* Release memory used for the match */
  57         pcre2_code_free(re);                 /*   data and the compiled pattern. */
  58         return 1;
  59     }
  60 
  61     ovector = pcre2_get_ovector_pointer(match_data);
  62 
  63     for (i = 0; i < rc; i++)
  64         printf("%2ld: %.*s\n", ovector[2*i], 
  65 			     (int)(ovector[2*i+1] - ovector[2*i]),
  66 			     subject + ovector[2*i]);
  67 
  68     pcre2_match_data_free(match_data);  /* Release the memory that was used */
  69     pcre2_code_free(re);                /* for the match data and the pattern. */
  70 
  71     return 0;
  72 }

Attached Files

To refer to attachments on a page, use attachment:filename, as shown below in the list of files. Do NOT use the URL of the [get] link, since this is subject to change and can break easily.

You are not allowed to attach a file to this page.