pcre match all groups in C

2020-03-30 07:14发布

问题:

I want to match a group recursively using PCRE C library.

e.g.

pattern = "(\d,)"
subject = "5,6,3,2,"
OVECCOUNT = 30

pcrePtr = pcre_compile(pattern, 0, &error, &erroffset, NULL);
rc = pcre_exec(pcrePtr, NULL, subject, (int)strlen(subject), 
0, 0, ovector, OVECCOUNT);

rc is -1..

How to match all groups so that matches are "5,", "6,", "3,", "2,"

For analogy, PHP's preg_match_all parses entire string until the end of subject...

回答1:

Try this :

pcre *myregexp;
const char *error;
int erroroffset;
int offsetcount;
int offsets[(0+1)*3]; // (max_capturing_groups+1)*3
myregexp = pcre_compile("\\d,", 0, &error, &erroroffset, NULL);
if (myregexp != NULL) {
    offsetcount = pcre_exec(myregexp, NULL, subject, strlen(subject), 0, 0, offsets, (0+1)*3);
    while (offsetcount > 0) {
        // match offset = offsets[0];
        // match length = offsets[1] - offsets[0];
        if (pcre_get_substring(subject, &offsets, offsetcount, 0, &result) >= 0) {
            // Do something with match we just stored into result
        }
        offsetcount = pcre_exec(myregexp, NULL, subject, strlen(subject), 0, offsets[1], offsets, (0+1)*3);
    } 
} else {
    // Syntax error in the regular expression at erroroffset
}

I believe the comments are self explanatory?



回答2:

Any way I used strtok since "," was repeating after each group..

Solution using pcre is welcomed....



标签: c regex pcre