这是关于pcre的多个子组,主题是:
const char* subject = "http://mail.google.com:443";
我想找到protocol& domain& port,我的正则表达式是这样,但 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;
}
答案 0 :(得分:0)
这一行:
#define VECTORSIZE 6
将其更改为30或其他东西(整数便宜),它会起作用。 pcre_exec每个子组需要3个元素,整个匹配需要3个元素。因此,在您的示例中,它至少需要12个。