examples

Toy examples in single C files.
git clone git://henryandlizzy.uk/examples
Log | Files | Refs

regex.c (1481B)


      1 #include <regex.h>
      2 #include <assert.h>
      3 #include <stdio.h>
      4 #include <string.h>
      5 
      6 #define ARRAY_SIZE(a)   (sizeof(a) / sizeof(*a))
      7 #define min(a,b) \
      8    ({ __typeof__ (a) _a = (a); \
      9        __typeof__ (b) _b = (b); \
     10      _a < _b ? _a : _b; })
     11 
     12 char const* const tests[] =
     13 {
     14     "hello world",
     15     "10=5",
     16     "big=small"
     17 };
     18 
     19 
     20 
     21 int main()
     22 {
     23     //char const re[] = R"~(^(?:(\d+)|([^=]+))=(?:(\d+)|([^=]+))$)~";
     24     char const re[] = "^((\\d+)|([^=]+))=((\\d+)|([^=]+))$";
     25     regex_t preg;
     26  
     27     int err = regcomp(&preg, re, REG_EXTENDED);
     28     if (err)
     29     {
     30         char buf[256];
     31         regerror(err, &preg, buf, sizeof(buf));
     32         puts(buf);
     33         return 1;
     34     }
     35 
     36 
     37 
     38     for (unsigned i = 0; i < ARRAY_SIZE(tests); ++i)
     39     {
     40         char const* const str = tests[i];
     41         regmatch_t pmatch[7];
     42         printf("'%s':\n", str);
     43         int res = regexec(&preg, str, ARRAY_SIZE(pmatch), pmatch, 0);
     44         if (res == REG_NOMATCH)
     45         {
     46             puts("NO MATCH");
     47             continue;
     48         }
     49         assert(!res);
     50         for (unsigned j = 0; j < ARRAY_SIZE(pmatch); ++j)
     51         {
     52             char buf[128];
     53             if (pmatch[j].rm_so == -1)
     54                 continue;
     55 
     56             size_t len = pmatch[j].rm_eo - pmatch[j].rm_so;
     57             len = min(len, ARRAY_SIZE(buf) - 1);
     58             *strncpy(buf, str, len) = '\0';
     59             printf("  %d -> %d: '%s'\n", pmatch[j].rm_so, pmatch[j].rm_eo, buf);
     60         }
     61     }
     62 
     63     regfree(&preg);
     64 
     65     return 0;
     66 }