我有一个类似于051916.000的输入字符串。我想把05、19、16和000分开。我试图用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并不熟悉,所以我不知道我哪里出了问题。Regex被验证,并正确匹配。
发布于 2016-04-23 06:35:15
这里有一些小错误:
char* pattern = "/([0-9]{2})([0-9]{2})([0-9]{2})\\.(.*)";你有一个领先的斜线。这里的Regexes是在没有周围斜线的情况下组成的,移除它。
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);https://stackoverflow.com/questions/36807186
复制相似问题