这是关于pcre多个子组的,主题是:

const char* subject = "http://mail.google.com:443";

我想找到protocol&domain&port和我的regex,但是pcre_exec返回0
const char* regex_str = "([^/]+)//([^:]+):(\\d+)";

但是当这样修改时,pcre_exec返回2:
const char* regex_str = "[^/]+//([^:]+):\\d+";

怎么了?
#include <stdio.h>
#include <string.h>
#include <pcre.h>
#define VECTORSIZE 6
int main()
{
    const char* subject = "http://mail.google.com:443";
    const char* regex_str = "([^/]+)//([^:]+):(\\d+)";
    const char* error = NULL;
    int erroffset = 0;
    int ovector[VECTORSIZE];
    char match[50];
    int matchlen = 0;

    pcre* regex = pcre_compile(regex_str, PCRE_CASELESS, &error, &erroffset, NULL);
    if(regex == NULL)
    {
        printf("error=%s,offset=%d\n", error, erroffset);
        return -1;
    }

    int matches = pcre_exec(regex, NULL, subject, strlen(subject), 0, 0, ovector, VECTORSIZE);
    printf("matches=%d\n", matches);
    if(matches == -1)
    {
        printf("no matches\n");
        return -1;
    }
    for(int i=0; i<matches; i++)
    {
        memset(match, 0, sizeof(match));
        matchlen = ovector[2*i + 1] - ovector[2*i];
        printf("start=%d, lenth=%d\n", ovector[2*i], matchlen);
        memcpy(match, subject + ovector[2*i], matchlen);
        printf("match=%s\n", match);
    }
    pcre_free(regex);

    return 0;
}

最佳答案

这一行:

#define VECTORSIZE 6

把它改成30或是更便宜,它就会起作用。pcre_exec需要每个子组3个元素,整个匹配需要3个以上元素。所以在你的例子中至少需要12个。

10-07 13:47