#include <sys/types.h>
#include <regex.h>
#include <stdio.h>
#include <string.h>


void match_all(regex_t *p, char *sz) {
    regmatch_t whole_match;
    int match = 0;
    size_t offset = 0;
    size_t length = strlen(sz);
    char result[BUFSIZ];
    int len;

    while (regexec(p, sz + offset, 1, &whole_match, 0) == 0) {
        match = 1;
        len = whole_match.rm_eo - whole_match.rm_so;
        memcpy(result, sz + whole_match.rm_so, len);
        result[len] = 0;
        printf("Match: %s\n", result);

        offset += whole_match.rm_eo + 1; // increase the starting offset
        if (offset > length) {
            break;
        }
    }
    if (! match) {
        printf("\"%s\" does not contain a match\n", sz);
    }
}


int main(int argc, char* argv[]) {
    int r;
    regex_t p;
    r = regcomp(&p, "[[:alnum:]]*k[[:alnum:]]*", 0);
    if (r != 0) {
        printf("regcomp failed\n");
    }
    match_all(&p, "mikko mikko");
    regfree(&p);
    return 0;
}