c - 使用 regexec 进行分组

标签 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 中使用过正则表达式。我是 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);

关于c - 使用 regexec 进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36807186/

相关文章:

bash - 正则表达式、捕获组和美元符号

regex - 与正则表达式的反匹配

c - 使用 gethostbyname 的 DNS

c++ - Arduino中断频率

c - 使用 atof 函数有什么问题?

正则表达式 - 将文本从一个街道号码匹配到下一个街道号码的模式

python - python中的多次重复错误

c - 'sizeof (function name)' 返回什么?

java - java中的SPARQL查询REGEX边界返回空

regex - 如何将一组值与组 1 相匹配