【问题标题】:pcre match all groups in Cpcre 匹配 C 中的所有组
【发布时间】:2011-12-08 18:59:09
【问题描述】:

我想使用 PCRE C 库递归匹配一个组。

例如

pattern = "(\d,)"
subject = "5,6,3,2,"
OVECCOUNT = 30

pcrePtr = pcre_compile(pattern, 0, &error, &erroffset, NULL);
rc = pcre_exec(pcrePtr, NULL, subject, (int)strlen(subject), 
0, 0, ovector, OVECCOUNT);

rc 是 -1..

如何匹配所有组,以便匹配为“5”、“6”、“3”、“2”

打个比方,PHP 的preg_match_all 会解析整个字符串,直到主题结束...

【问题讨论】:

  • 围绕pcre_exec() 循环,每次迭代后适当调整起始位置。
  • 有没有办法一口气搞定?
  • 如果没有编写函数来为你做循环。

标签: c regex pcre


【解决方案1】:

我使用 strtok 的任何方式,因为“,”在每组之后重复..

欢迎使用 pcre 的解决方案....

【讨论】:

    【解决方案2】:

    试试这个:

    pcre *myregexp;
    const char *error;
    int erroroffset;
    int offsetcount;
    int offsets[(0+1)*3]; // (max_capturing_groups+1)*3
    myregexp = pcre_compile("\\d,", 0, &error, &erroroffset, NULL);
    if (myregexp != NULL) {
        offsetcount = pcre_exec(myregexp, NULL, subject, strlen(subject), 0, 0, offsets, (0+1)*3);
        while (offsetcount > 0) {
            // match offset = offsets[0];
            // match length = offsets[1] - offsets[0];
            if (pcre_get_substring(subject, &offsets, offsetcount, 0, &result) >= 0) {
                // Do something with match we just stored into result
            }
            offsetcount = pcre_exec(myregexp, NULL, subject, strlen(subject), 0, offsets[1], offsets, (0+1)*3);
        } 
    } else {
        // Syntax error in the regular expression at erroroffset
    }
    

    我相信 cmets 是不言自明的?

    【讨论】:

    • @Rahul 您使用的是哪个版本的 PCRE?
    • @FailedDev 你的代码我试过了,我在你的代码的while循环中找到了函数pcre_exec(),它的offsets[1]参数不是他的正确顺序。于是我改了:offsetcount = pcre_exec(myregexp, NULL, subject, strlen(subject), offsets[1],0, offsets, (0+1)*3); 然后就很好用了。
    • @hession 也许不同版本的pcre lib。很高兴它的措辞:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-20
    相关资源
    最近更新 更多