1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <regex.h>
int main (void)
{
int err;
int i=0;
regex_t preg;
const char *str_request = "20a21a22";
const char *str_regex = "([0-9]{2})a([0-9]{2})a([0-9]{2})";
/* (1) */
err = regcomp (&preg, str_regex, REG_EXTENDED);
if (err == 0)
{
int match;
size_t nmatch = 0;
regmatch_t *pmatch = NULL;
nmatch = preg.re_nsub;
pmatch = calloc (sizeof (*pmatch),nmatch);
if (pmatch)
{
/* (2) */
match = regexec (&preg, str_request, nmatch, pmatch, REG_NOTBOL);
/* (3) */
printf ("nmatch=%d \n",nmatch);
regfree (&preg);
/* (4) */
if (match == 0)
{
for (i=0;i<nmatch;i++) {
char *site = NULL;
int start = pmatch[i].rm_so;
int end = pmatch[i].rm_eo;
size_t size = end - start;
site = calloc (sizeof (*site),(size + 1));
if (site)
{
strncpy (site, &str_request[start], size);
printf ("Chaine %d : %s\n", i,site);
}
free(site);
}
}
/* (5) */
else if (match == REG_NOMATCH)
{
printf ("No match\n", str_request);
}
/* (6) */
else
{
char *text;
size_t size;
/* (7) */
size = regerror (err, &preg, NULL, 0);
text = malloc (sizeof (*text) * size);
if (text)
{
/* (8) */
regerror (err, &preg, text, size);
fprintf (stderr, "%s\n", text);
free (text);
}
else
{
fprintf (stderr, "Memoire insuffisante\n");
exit (EXIT_FAILURE);
}
}
}
else
{
fprintf (stderr, "Memoire insuffisante\n");
exit (EXIT_FAILURE);
}
}
puts ("\nPress any key\n");
/* Dev-cpp */
getchar ();
return (EXIT_SUCCESS);
} |
Partager