How can I easily get regex selections in C?

c, posix, regex, unix

Solution

You need to pass in a set of `regmatch_t`s that the regex can fill with the indices of the matches. Try the below program with a single command line argument (the string to test).

Once you have the indices of the matches, it should be fairly easy to pull out what you're after. (Note: `matches[0]` will be the match of the entire expression, so the subexpressions start at `matches[1]`.)

#include <stdlib.h>
#include <stdio.h>
#include <regex.h>

int main(int argc, char* argv[])
{
    const char* pattern = "{{( )*(([[:alnum:]]+\\.)*)?[[:alnum:]]+( )*}}";
    regex_t rex;
    int rc;

    if ((rc = regcomp(&rex, pattern, REG_EXTENDED))) {
        fprintf(stderr, "error %d compiling regex\n", rc);
        /* retrieve error here with regerror */
        return -1;
    }

    regmatch_t* matches = malloc(sizeof(regex_t) * (rex.re_nsub + 1));

    if ((rc = regexec(&rex, argv[1], rex.re_nsub + 1, matches, 0))){
        printf("no match\n");
        /* error or no match */
    } else {
        for(int i = 0; i < rex.re_nsub; ++i) {
            printf("match %d from index %d to %d: ", i, matches[i].rm_so,
                   matches[i].rm_eo);
            for(int j = matches[i].rm_so; j < matches[i].rm_eo; ++j) {
                printf("%c", argv[1][j]);
            }
            printf("\n");
        }
    }

    free(matches);
    regfree(&rex);

    return 0;
}

Problem

I'm using regex.h (POSIX) for regular expressions. Are there any selection methods for regex matches in C? I can quite easily check for regular expressions but if I need to retrieve the matched value, I have to manually find and store it. ``` {{( )*(([[:alnum:]]+\\.)*)?[[:alnum:]]+( )*}} ``` This regex looks for any variable matches in double curly braces. But I only need the most central item in the string. How can I retrieve the value with regular expressions in C?

Original source