fork(1) download
  1. #include <stdio.h>
  2. #include <regex.h>
  3. #include <string.h>
  4.  
  5. int main() {
  6.  
  7. regex_t preg;
  8. char str[] = "dave";
  9. char regex[] = "\\(.\\)ave";
  10.  
  11. // flag REG_EXTENDED with unescaped parens in the r.e. doesn't fix anything
  12. int ret, cflags = REG_ICASE;
  13.  
  14. // the elements of unused pmatches used to be set to -1 by regexec, but no longer. a clue perhaps.
  15.  
  16. regmatch_t pmatch[2] = {{-1,-1},{-1,-1}};
  17.  
  18. ret = regcomp(&preg, regex, cflags);
  19. if (ret) {
  20. puts("regcomp fail");
  21. return ret;
  22. }
  23. else
  24. // preg.re_nsub contains the correct number of groups that regcomp recognized in the r.e. Tests succeeded for 0, 1, 2, and 3 groups.
  25. printf("regcomp ok; re_nsub=%zu\n", preg.re_nsub);
  26.  
  27. ret = regexec(&preg, str, 2, pmatch, 0); // 1 changed to 2 as there is Group 0 (whole match) and Group 1 (for the first capturing group)
  28.  
  29. if(ret)
  30. puts("no match");
  31. else {
  32. printf("match offsets are %d %d\n", pmatch[0].rm_so, pmatch[0].rm_eo);
  33. printf("match[0]=%*s<\n", pmatch[0].rm_eo, &str[pmatch[0].rm_so]);
  34.  
  35. printf("submatch offsets are %d %d\n", pmatch[1].rm_so, pmatch[1].rm_eo);
  36. if(pmatch[1].rm_so != -1) {
  37. printf("match[1]=%.*s<\n", pmatch[1].rm_eo, &str[pmatch[1].rm_so]);
  38. }
  39. }
  40. return 0;
  41. }
  42. /*
  43. regcomp ok; re_nsub=1
  44. match offsets are 0 4
  45. match[0]=dave<
  46. submatch offsets are 0 1
  47. match[1]=d<
  48. */
Success #stdin #stdout 0.01s 5456KB
stdin
Standard input is empty
stdout
regcomp ok; re_nsub=1
match offsets are 0 4
match[0]=dave<
submatch offsets are 0 1
match[1]=d<