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
| void my_ereg ( const char *regex, const char *str, char ***result )
{
int regcomp_options = 0;
int regexec_options = 0;
regex_t motif;
int error = 0;
size_t message_size = 0;
char *message = NULL;
size_t substr_count = 0;
size_t substr_size = 0;
regmatch_t *substr_match = NULL;
int i = 0;
/* nothing to do if regular expression is empty */
if ((regex == NULL) || (str == NULL))
return;
/* Motif compilation */
regcomp_options |= REG_EXTENDED;
error = regcomp(&motif, regex, regcomp_options);
/* Catch error */
if (error != 0) {
message_size = regerror(error, &motif, NULL, 0);
message = (char *)malloc(message_size * sizeof(char));
regerror(error, &motif, message, message_size);
regfree(&motif);
error_printf(NON_FATAL, NULL, message);
free(message), message = NULL;
exit(EXIT_FAILURE);
}
/* Prepare sub-expressions */
substr_count = motif.re_nsub + 1;
substr_match = calloc(substr_count, sizeof(regmatch_t));
/* Execute regular expression */
error = regexec(&motif, str, substr_count, substr_match,
regexec_options);
if (error != 0) {
regfree(&motif);
free(substr_match), substr_match = NULL;
if (error == REG_NOMATCH)
return;
else
error_printf(FATAL, "regexec", NULL);
}
/* Allocating memory for results pointers */
*result = (char **)malloc((substr_count + 1) * sizeof(void *));
/* Parsing results */
for (i = 0;i < substr_count;i++) {
substr_size = substr_match[i].rm_eo
- substr_match[i].rm_so;
*((*result) + i) = (char *)calloc( substr_size + 1,
(substr_size + 1) * sizeof(void *));
*((*result) + i) = strncpy(*((*result) + i),
str + substr_match[i].rm_so,
substr_size);
}
/* Last result is NULL */
*((*result) + i) = NULL;
free(substr_match), substr_match = NULL;
regfree(&motif);
return;
} /* my_ereg() */ |
Partager