免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 9066 | 回复: 4
打印 上一主题 下一主题

[函数] 问个C的正则匹配函数regexec() [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-03-02 13:13 |只看该作者 |倒序浏览
如果待查找串中有多个词符合模式串,那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(&reg, pattern, cflags);

        if(z != 0)
        {   
                regerror(z, &reg, ebuf, sizeof(ebuf));
                fprintf(stderr, "%s: pattern '%s'\n", ebuf, pattern);
                return 1;
        }   

        z = regexec(&reg, str, nmatch, pm, 0);

        if(z == REG_NOMATCH)
                return 1;
        else if(z != 0)
        {
                regerror(z, &reg, 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(&reg);

        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。可实际上只输出了一个,为什么呢?

论坛徽章:
0
2 [报告]
发表于 2008-03-03 09:20 |只看该作者
貌似regexec()匹配出第一个就返回了,  要自己写循环匹配

论坛徽章:
0
3 [报告]
发表于 2008-03-03 10:07 |只看该作者
本站搜索regexec()

论坛徽章:
0
4 [报告]
发表于 2008-03-03 11:11 |只看该作者
你的理解有问题,它不会匹配多次,而是匹配一次,但是里面有多组


char *str = "a bbb c";
        char *pattern = "a \\(b*\\) \\(.*\\)";

你再试试上面的

这是regex的代码中的说明
If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
   store offsets for the substring each group matched in REGS.  See the
   documentation for exactly how many groups we fill.

你再看看man,不过我也觉得手册有点迷惑人

论坛徽章:
0
5 [报告]
发表于 2008-03-03 18:26 |只看该作者
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP