这是关于 pcre 多个子组,主题是:
const char* subject = "http://mail.google.com:443";
我想找到协议&域&端口,我的正则表达式是这样的,但是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;
}