- 论坛徽章:
- 0
|
如果待查找串中有多个词符合模式串,那regexec()应该是匹配出多个结果才对吧?为什么我的代码只匹配出第一个就不干活了呢?
求达人指点~
代码如下:
static char *substr(const char *str, unsigned start, unsigned end)
{
unsigned n =end - start;
static char stbuf[256];
strncpy(stbuf, str+start, n);
stbuf[n]=0;
return stbuf;
}
int cns_reg(const char *str, const char *pattern)
{
int z; //status
int cflags = 0; //compile flags
regex_t reg; //compiled regular expression
char ebuf[129]; //error buffer
regmatch_t pm[10]; //pattern matches 0-9
const size_t nmatch = 10; //The size of array pm[]
z = regcomp(®, pattern, cflags);
if(z != 0)
{
regerror(z, ®, ebuf, sizeof(ebuf));
fprintf(stderr, "%s: pattern '%s'\n", ebuf, pattern);
return 1;
}
z = regexec(®, str, nmatch, pm, 0);
if(z == REG_NOMATCH)
return 1;
else if(z != 0)
{
regerror(z, ®, ebuf, sizeof(ebuf));
fprintf(stderr, "%s: regcomp('%s')\n", ebuf, str);
return 2;
}
int x=0;
for (x=0; (x<nmatch && pm[x].rm_so != -1); x++)
{
printf("%s\n", substr(str, pm[x].rm_so, pm[x].rm_eo));
}
regfree(®);
return 0;
}
int main(int argc, char **argv)
{
char *str = "ball ball ball";
char *pattern = "ball";
printf("str:%s\npattern:%s\n", str, pattern);
cns_reg(str, pattern);
return 0;
}
按我的理解应该输出三个ball。可实际上只输出了一个,为什么呢? |
|