Grouping when using regexec

I have an input line, for example 051916.000. I would like to highlight 05, 19, 16and 000. I am trying to use regexecthis way in C.

regex_t r;
regmatch_t pmatch[4];
char* pattern = "/([0-9]{2})([0-9]{2})([0-9]{2})\\.(.*)";
int status = regcomp(&r, "", REG_EXTENDED|REG_NEWLINE);
status = regexec(&r, t, 4, pmatch, 0);
regfree(&r);

But this does not seem to work. Below is the output of GDB

(gdb) p pmatch 
$1 = {{rm_so = 0, rm_eo = 0}, {rm_so = -1, rm_eo = -1}, {rm_so = -1, rm_eo = -1}, {rm_so = -1, rm_eo = -1}}

I used Regex in Python. I am new to Regex in C. Therefore, I am not sure where I am going wrong. Regex is checked and it matches correctly.

+4
source share
1 answer

There are some minor bugs here:

char* pattern = "/([0-9]{2})([0-9]{2})([0-9]{2})\\.(.*)";

You have a leading slash. The modes here are composed without surrounding slashes; delete it.

status = regcomp(&r, "", REG_EXTENDED|REG_NEWLINE);

Here you pass the empty string as a template. You, of course, want to go through'pattern`.

regmatch_t pmatch[4];

, 5: pmatch[0] - .

, :

const char *t = "051916.000";
regex_t r;
regmatch_t pmatch[5];
char* pattern = "([0-9]{2})([0-9]{2})([0-9]{2})\\.(.*)";
int status, i;

status = regcomp(&r, pattern, REG_EXTENDED|REG_NEWLINE);
if (status == 0) status = regexec(&r, t, 5, pmatch, 0);

if (status == 0) {
    for (i = 0; i < 5; i++) {
        int len = pmatch[i].rm_eo - pmatch[i].rm_so;
        const char *str = t + pmatch[i].rm_so;

        printf("'%.*s'\n", len, str);
    }
}

regfree(&r);
+4

All Articles