expreg.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * File: expreg.c
  3. * Author: Arthur Brandao
  4. *
  5. * Created on 21 décembre 2018
  6. */
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <string.h>
  10. #include "expreg.h"
  11. /* --- Fonctions publiques --- */
  12. boolean ini_expreg(expreg* er, char* str, char* regex) {
  13. //Setup regex
  14. if (regcomp(&er->regex, regex, REG_EXTENDED) != 0) {
  15. return false;
  16. }
  17. //Copie la chaine
  18. int length = strlen(str);
  19. er->str = malloc(sizeof (char) * (length + 1));
  20. memset(er->str, 0, length + 1);
  21. strncpy(er->str, str, length);
  22. //Setup structure
  23. er->pos = 0;
  24. er->nmatch = er->regex.re_nsub;
  25. er->pmatch = malloc(sizeof (regmatch_t) * er->nmatch);
  26. return true;
  27. }
  28. char* get_match_expreg(expreg* er, int* deb, int* fin) {
  29. if (regexec(&er->regex, er->str + er->pos, er->nmatch, er->pmatch, 0) != 0) {
  30. if(deb != NULL){
  31. *deb = -1;
  32. }
  33. if(fin != NULL){
  34. *fin = -1;
  35. }
  36. return NULL;
  37. }
  38. //Recup info regex
  39. int start = er->pmatch[0].rm_so;
  40. int end = er->pmatch[0].rm_eo;
  41. int length = end - start;
  42. //Indique les positions
  43. if(deb != NULL){
  44. *deb = er->pos + start;
  45. }
  46. if(fin != NULL){
  47. *fin = er->pos + end;
  48. }
  49. //Recup la chaine
  50. char* str;
  51. str = malloc(sizeof(char) * (length + 1));
  52. memset(str, 0, length + 1);
  53. strncpy(str, &er->str[er->pos + start], length);
  54. //On avance dans la chaine
  55. er->pos += end;
  56. return str;
  57. }
  58. void clean_expreg(expreg* er) {
  59. regfree(&er->regex);
  60. free(er->str);
  61. free(er->pmatch);
  62. }