为什么我的PCRE只匹配第一个结果

时间:2012-11-12 15:03:39

标签: pcre

我想匹配输入字符串中的所有'abc'。但输入“first abc,second abc,third abc”时得到以下结果。我也输出了ovector:

src: first abc, second abc, third abc
Matches 1
ovector: 6|9|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|

我的代码:

#include <stdio.h>
#include <string.h>
#include "pcre.h"

static const char my_pattern[] = "abc";
static pcre* my_pcre = NULL;
static pcre_extra* my_pcre_extra = NULL;

void my_match(const char* src)
{
    printf("src: %s\n", src);
    int ovector[30]={0};
    int ret = pcre_exec(my_pcre, NULL, src, strlen(src), 0, 0, ovector, 30);
    if (ret == PCRE_ERROR_NOMATCH){
        printf("None match.\n");
    }
    else{
        printf("Matches %d\n",ret);
    }
    printf("ovector: ");
    for(int i=0;i<sizeof(ovector)/sizeof(int);i++){
        printf("%d|",ovector[i]);
    }
    printf("\n");
    return;
}

int main()
{
    const char* err;
    int erroffset;
    my_pcre = pcre_compile(my_pattern, PCRE_CASELESS, &err, &erroffset, NULL);
    my_pcre_extra = pcre_study(my_pcre, 0, &err);
    my_match("first abc, second abc, third abc");
    return 0;
}

如何获得所有'abc',谢谢。

1 个答案:

答案 0 :(得分:1)

pcre_exec一次只能找到一个匹配项。 ovector用于子字符串匹配。 int ovector[30]={0};将为您提供最多10个匹配(最后三分之一(20-29)未使用),第一对数字用于整个模式,下一对用于第一个捕获括号,依此类推。例如。如果您将模式更改为:

`static const char my_pattern[] = "(a(b)c)";`

然后在你的输出中你应该看到

Matches 3
ovector: 6|9|6|9|7|8|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|

该函数返回匹配的捕获数,在本例中为三个,一个用于整个模式,两个子模式捕获。整个模式匹配在6-9,第一个括号也匹配6-9,第二个括号匹配7-8。要获得更多的完整匹配(全局),您必须使用循环,每次都传入上一个匹配(ovector[1])的偏移量。

请参阅http://www.pcre.org/pcre.txt并搜索 pcre_exec()如何返回捕获的子字符串

相关问题