delibk 2016-04-27 03:18 采纳率: 50%
浏览 1569

C语言 PCRE正则表达式 函数解释

求指教:_PCRE库函数中,pcre_exec()的返回值是什么意思? *ovector数组的元素又是代表什么意_?
#include
#include
#include
#include
void main()
{
pcre *code;
char *src="Tel: 18701252677 18829696789 17867890987 E-mail:gsxu@sonicom.com.cn";
char *pattern="(([+86]|[86])?[0-9]{11})";
int i=0;
int ovector[15]={0};
int rc,exec_offset=0;
const char *sub;
const char *errptr;
const char **listptr;
int erroffet;
char temp[512]={0};

code=pcre_compile(pattern,0,&errptr,&erroffet,NULL);
//code=pcre_compile(pattern,PCRE_DOTALL,&errptr,&erroffet,NULL);
rc=pcre_exec(code,NULL,src,strlen(src),0,PCRE_BSR_ANYCRLF,ovector,15);

printf("match:%d\n",rc);
printf("start:%d end:%d\n",ovector[2],ovector[3]);
if(rc>0)
{
    for(i=0;i++;i<rc)
    {
        pcre_get_substring(src,ovector,rc,0,&sub);/////////////???????????????????????????????????
        printf("%s\n",sub);
        //exec_offset=ovector[i];
        //i++;
        pcre_free_substring(sub);
    }
}
pcre_get_substring_list(src,ovector,rc,&listptr);
printf("%s\n",*listptr);
pcre_free_substring_list(listptr);

free(code);

}

为什么数组ovector的元素{5,16,5,16,-1,.......}???????????????

  • 写回答

1条回答 默认 最新

  • 你知我知皆知 2024-08-05 11:54
    关注

    以下回答参考 皆我百晓生券券喵儿 等免费微信小程序相关内容作答,并由本人整理回复。

    pcre_exec()函数中,ovector是一个指向字符串的指针数组。这个数组包含了一组子串,这些子串是通过pcre_exec()函数匹配到的。

    每个子串都用一个整数表示其起始位置(索引)。例如,在你的例子中,子串"Tel:"和"E-mail:"的位置分别是ovector[2]ovector[4],因为它们分别对应于模式中的第2个和第4个捕获组。

    数组ovector的长度由pcre_exec()函数根据输入字符串的长度来确定。如果你的输入字符串非常长,那么ovector的长度可能会很大,因为它可能包含了所有的捕获组。

    至于const char *sub;这部分,它用来存储匹配到的部分文本。当你调用pcre_get_substring()时,你会传入当前的ovector索引作为参数,并且会从src字符串中获取相应的子串。然后,你将这个子串打印出来。注意,由于ovector是动态分配的,所以每次使用pcre_get_substring()都会重新分配内存以容纳新的子串。

    最后,pcre_free_substring()用于释放已经不再使用的子串资源,而pcre_free_substring_list()用于释放所有已分配的子串列表资源。

    总的来说,pcre_exec()函数的核心作用是在给定的模式下执行正则表达式的匹配操作,并将结果存储在一个数组中供后续处理。

    评论

报告相同问题?