使用regexec进行分组

时间:2016-04-23 05:53:29

标签: c regex pcre posix-api

我有一个像051916.000这样的输入字符串。我想将051916000分开。 我试图在C语言中以这种方式使用regexec

regex_t r;
regmatch_t pmatch[4];
char* pattern = "/([0-9]{2})([0-9]{2})([0-9]{2})\\.(.*)";
int status = regcomp(&r, "", REG_EXTENDED|REG_NEWLINE);
status = regexec(&r, t, 4, pmatch, 0);
regfree(&r);

但这似乎不起作用。下面是GDB输出

(gdb) p pmatch 
$1 = {{rm_so = 0, rm_eo = 0}, {rm_so = -1, rm_eo = -1}, {rm_so = -1, rm_eo = -1}, {rm_so = -1, rm_eo = -1}}

我在Python中使用过Regex。我是C的Regex的新手。所以我不确定我哪里出错了。正则表达式已经过验证,并且匹配正确。

1 个答案:

答案 0 :(得分:4)

这里有一些小错误:

char* pattern = "/([0-9]{2})([0-9]{2})([0-9]{2})\\.(.*)";

你有一个领先的斜线。这里的正则表达式没有周围的斜线;删除它。

status = regcomp(&r, "", REG_EXTENDED|REG_NEWLINE);

在这里,您将空字符串作为模式传递。当然,你想传递'模式'。

regmatch_t pmatch[4];

如果要捕获所有四个括号内的子表达式,则应传递一个大小为5的数组:pmatch[0]是整个表达式。

修复这些问题后,您的代码就可以运行:

const char *t = "051916.000";
regex_t r;
regmatch_t pmatch[5];
char* pattern = "([0-9]{2})([0-9]{2})([0-9]{2})\\.(.*)";
int status, i;

status = regcomp(&r, pattern, REG_EXTENDED|REG_NEWLINE);
if (status == 0) status = regexec(&r, t, 5, pmatch, 0);

if (status == 0) {
    for (i = 0; i < 5; i++) {
        int len = pmatch[i].rm_eo - pmatch[i].rm_so;
        const char *str = t + pmatch[i].rm_so;

        printf("'%.*s'\n", len, str);
    }
}

regfree(&r);