René Nyffenegger's collection of things on the web
René Nyffenegger on Oracle - Most wanted - Feedback -
 

PCRE test 1

This is a simple sample program to demonstrate the use of pcre_compile() and pcre_exec (which are functions of PCRE).
test_1.c
#include <stdio.h>
#include <string.h>
#include <pcre.h>

#define OVECCOUNT 30    /* should be a multiple of 3 */

int main() {
  const char *error;
        int   erroffset;
        pcre *re;
        int   rc;
        int   i;
        char  str[] = "regular expressions=very cool";  /* String to match */
        int   ovector[OVECCOUNT];

  re = pcre_compile (
         "([^=]*)=(.*)",       /* the pattern */
         0,                    /* default options */
         &error,               /* for error message */
         &erroffset,           /* for error offset */
         0);                   /* use default character tables */

  if (!re) {
    printf("pcre_compile failed (offset: %d), %s\n", erroffset, error);
    return -1;
  }

  rc = pcre_exec (
    re,                   /* the compiled pattern */
    0,                    /* no extra data - pattern was not studied */
    str,                  /* the string to match */
    strlen(str),          /* the length of the string */
    0,                    /* start at offset 0 in the subject */
    0,                    /* default options */
    ovector,              /* output vector for substring information */
    OVECCOUNT);           /* number of elements in the output vector */

  if (rc < 0) {
    switch (rc) {
      case PCRE_ERROR_NOMATCH:
        printf("String didn't match");
        break;

      default:
        printf("Error while matching: %d\n", rc);
        break;
    }
    free(re);
    return -1;
  }

  for (i = 0; i < rc; i++) {
    printf("%2d: %.*s\n", i, ovector[2*i+1] - ovector[2*i], str + ovector[2*i]);
  }
}
If this program is run, the following will be printed:
 0: regular expressions=very cool
 1: regular expressions
 2: very cool

Compiling

I was able to compile this sample with MinGW on Windows like so:
gcc -I. pcre.c chartables.c get.c test_1.c pcreposix.c  study.c