使用regexec进行分组

加拉

我有一个类似的输入字符串051916.000我想隔离051916000我正在尝试以regexec这种方式在C语言中使用。

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的新手,所以我不确定我哪里出错了。正则表达式已验证,并且正确匹配。

欧姆

这里有一些小错误:

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);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章