Examples

Example 29 and Example 30 are adapted from an open source example written by Philip Hazel and copyright by the University of Cambridge, England.

Example 1-29. Simple match

#include <stdio.h>
#include <string.h>
#include <pcre.h>

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

int main(int argc, char **argv)
{
pcre *regex;
const char *error;
int erroffset;
int capturevector[CAPTUREVECTORSIZE];
int rc;

char *pattern = "spider[- ]?man";
char *text ="SPIDERMAN menaces city!";

/* Compile Regex */
regex = pcre_compile(
  pattern,
  PCRE_CASELESS,  /* OR'd mode modifiers */
  &error,         /* error message */
  &erroffset,     /* position in regex where error occurred */
  NULL);          /* use default locale */

/* Handle Errors */
if (regex =  = NULL)
  {
  printf("Compilation failed at offset %d: %s\n", erroffset,
         error);
  return 1;
  }

/* Try Match */
rc = pcre_exec(
  regex,    /* compiled regular expression */
  NULL,     /* optional results from pcre_study */
  text,     /* input string */
  (int)strlen(text), /* length of input string */
  0,        /* starting position in input string */
  0,        /* OR'd options */
  capturevector, /* holds results of capture groups */
  CAPTUREVECTORSIZE);

/* Handle Errors */
if (rc < 0)
  {
  switch(rc)
    {
    case PCRE_ERROR_NOMATCH: printf("No match\n"); break;
    default: printf("Matching error %d\n", rc); break;
    }
  return 1;
  }
return 0;
}

Example 1-30. Match and capture group

#include <stdio.h> #include <string.h> #include <pcre.h> #define CAPTUREVECTORSIZE 30 /* should be a multiple of 3 */ int main(int ...

Get Regular Expression Pocket Reference, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.