【问题标题】:pcre can not support mutiple subgroupspcre 不能支持多个子组
【发布时间】:2013-07-29 10:17:16
【问题描述】:

这是关于pcre多个子组的,主题是:

const char* subject = "http://mail.google.com:443";

我想找到协议&域&端口,我的正则表达式是这样的,但是 pcre_exec 返回 0

const char* regex_str = "([^/]+)//([^:]+):(\\d+)";

但是当这样修改时,pcre_exec 返回 2:

const char* regex_str = "[^/]+//([^:]+):\\d+";

嗯,怎么了?

#include <stdio.h>
#include <string.h>
#include <pcre.h>
#define VECTORSIZE 6
int main()
{
    const char* subject = "http://mail.google.com:443";
    const char* regex_str = "([^/]+)//([^:]+):(\\d+)";
    const char* error = NULL;
    int erroffset = 0;
    int ovector[VECTORSIZE];
    char match[50];
    int matchlen = 0;

    pcre* regex = pcre_compile(regex_str, PCRE_CASELESS, &error, &erroffset, NULL);
    if(regex == NULL)
    {
        printf("error=%s,offset=%d\n", error, erroffset);
        return -1;
    }

    int matches = pcre_exec(regex, NULL, subject, strlen(subject), 0, 0, ovector, VECTORSIZE);
    printf("matches=%d\n", matches);
    if(matches == -1)
    {
        printf("no matches\n");
        return -1;
    }
    for(int i=0; i<matches; i++)
    {
        memset(match, 0, sizeof(match));
        matchlen = ovector[2*i + 1] - ovector[2*i];
        printf("start=%d, lenth=%d\n", ovector[2*i], matchlen);
        memcpy(match, subject + ovector[2*i], matchlen);
        printf("match=%s\n", match);
    }
    pcre_free(regex);

    return 0;
}

【问题讨论】:

  • "不能支持多个子组" - 您是否尝试过使用非常简单的正则表达式来验证这一点?不要妄下结论。
  • 我的示例很简单
  • 好吧,看看这个: const char* server = "mail.google.com"; const char* regex_str = "(\\w+).(\\w+).";

标签: c++ c pcre


【解决方案1】:

这一行:

#define VECTORSIZE 6

将其更改为 30 或其他值(整数很便宜),它会起作用。 pcre_exec 每个子组需要 3 个元素,整个匹配需要 3 个元素。因此,在您的示例中,它至少需要为 12。

【讨论】:

    猜你喜欢
    • 2011-10-03
    • 1970-01-01
    • 1970-01-01
    • 2014-03-07
    • 2023-03-24
    • 2013-02-24
    • 2012-04-19
    • 1970-01-01
    相关资源
    最近更新 更多