Se connecter avec
S'enregistrer | Connectez-vous

extraire plusieurs sous chaine d'un string en C

Dernière réponse : dans Programmation
Lassé par la pub ? Créez un compte

suffit d'appeler la fonction avec une chaine différente:
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <regex.h>
  5.  
  6. int main (void)
  7. {
  8. int err;
  9. regex_t preg;
  10. const char *str="chaine sous chaine sous chaine toto";
  11. const char *str_regex="(sous +chaine)";
  12.  
  13.  
  14. err = regcomp (&preg, str_regex, REG_EXTENDED);
  15. if (err == 0)
  16. {
  17. int match;
  18. size_t nmatch = 0;
  19. regmatch_t *pmatch = NULL;
  20. char *buffer;
  21.  
  22. nmatch = preg.re_nsub;
  23. printf ("taille: %d\n", nmatch);
  24. pmatch = malloc (sizeof (*pmatch) * nmatch);
  25. if (!pmatch)
  26. {
  27. fprintf (stderr, "Memoire insuffisante\n");
  28. exit (1);
  29. }
  30. buffer = (char *) str;
  31. match = regexec (&preg, buffer, nmatch, pmatch, 0);
  32. while (match == 0)
  33. {
  34. char *str_found = NULL;
  35. size_t size ;
  36. int start, end;
  37. start = pmatch[0].rm_so;
  38. end = pmatch[0].rm_eo;
  39. size = end - start;
  40.  
  41. str_found = malloc (sizeof (*str_found) * (size + 1));
  42. if (str_found)
  43. {
  44. strncpy (str_found, &buffer[start], size);
  45. str_found[size] = '\0';
  46. printf ("%s\n", str_found);
  47. free (str_found);
  48. }
  49. match = regexec (&preg, (buffer += end), nmatch, pmatch, 0);
  50. }
  51. regfree (&preg);
  52. free (pmatch);
  53. }
  54. return 0;
  55. }
Lassé par la pub ? Créez un compte
Tom's guide dans le monde