#include <iostream>
#include <pcre.h>
#define OVECCOUNT 30
int main (int argc, char * const argv[]) {
pcre *re;
const char *error;
int erroroffset;
int ovector[OVECCOUNT];
int rc;
char regex[] = "^From: ([^@]+)@([^\r]+)";
char data[] = "From: regular.expressions@example.com\r\n";
re = pcre_compile(regex, 0, &error, &erroroffset, NULL);
if (!re) {
fprintf(stderr, "PCRE compilation failed at expression offset %d: %s\n", erroroffset, error);
return 1;
}
rc = pcre_exec(re, NULL, data, strlen(data), 0, 0, ovector, OVECCOUNT);
if (rc < 0) {
switch (rc) {
case PCRE_ERROR_NOMATCH:
printf("No match found in text\n");
break;
default:
printf("Match error %d\n", rc);
break;
}
return 1;
}
if (rc < 3)
{
printf("Match did not catch all the groups\n");
return 1;
}
char *name_start = data + ovector[2];
int name_length = ovector[3] - ovector[2];
char *domain_start = data + ovector[4];
int domain_length = ovector[5] - ovector[4];
printf("Mail from: %.*s domain: %.*s\n", name_length, name_start, domain_length, domain_start);
return 0;
}