fork download
  1. #include <stdio.h>
  2. #include <regex.h>
  3.  
  4. int
  5. regex_match (char *pattern, const char *string,
  6. size_t sub_size, char **sub)
  7. {
  8. const int msg_size = 200;
  9. char msg[msg_size];
  10. msg[0] = '\0';
  11. //
  12. regmatch_t match[sub_size];
  13. size_t n;
  14. size_t m;
  15. size_t d;
  16. int status;
  17. regex_t re;
  18. status = regcomp (&re, pattern, REG_EXTENDED);
  19. if (status != 0)
  20. {
  21. regerror (status, &re, msg, msg_size);
  22. fprintf (stderr, "%s\n", msg);
  23. return (status);
  24. }
  25. status = regexec (&re, string, sub_size, match, 0);
  26. if (status != 0)
  27. {
  28. regerror (status, &re, msg, msg_size);
  29. fprintf (stderr, "%s\n", msg);
  30. }
  31. else
  32. {
  33. for (n=0; n < sub_size; n++)
  34. {
  35. for (d = 0, m = match[n].rm_so;
  36. m >= 0 && m < match[n].rm_eo;
  37. m++, d++)
  38. {
  39. sub[n][d] = string[m];
  40. }
  41. sub[n][d] = '\0';
  42. }
  43. }
  44. regfree (&re);
  45. return (status);
  46. }
  47.  
  48. int
  49. main (void)
  50. {
  51. int result;
  52. char *string = "Ciao amore mio";
  53. char *re = "*Ciao (amo)re";
  54. char sub0[200];
  55. sub0[0] = '\0';
  56. char sub1[200];
  57. sub1[0] = '\0';
  58. char *sub[] = {sub0, sub1};
  59.  
  60. result = regex_match (re, string, 2, sub);
  61.  
  62. if (result == 0)
  63. {
  64. printf ("Il modello \"%s\" trova corrispondenza ",
  65. re);
  66. printf ("nella stringa \"%s\", precisamente ",
  67. string);
  68. printf ("nella porzione \"%s\", mentre la ",
  69. sub[0]);
  70. printf ("sottostringa estratta รจ \"%s\".\n",
  71. sub[1]);
  72. }
  73. else
  74. {
  75. printf ("Il modello \"%s\" ", re);
  76. printf ("NON trova corrispondenza ");
  77. printf ("nella stringa \"%s\"\n", string);
  78. }
  79. return 0;
  80. }
Success #stdin #stdout 0.02s 1852KB
stdin
Standard input is empty
stdout
Il modello "*Ciao (amo)re" NON trova corrispondenza nella stringa "Ciao amore mio"