C Regex - 获取匹配的字符串

标签 c regex

我有这个代码:

regex_t regex;
    int reti;

    reti = regcomp(&regex, "[0-9]", REG_EXTENDED);

    reti = regexec(&regex, "sdsda5dada", 0, NULL, 0);
    if( !reti ){
        return 1;
    }
    else if( reti == REG_NOMATCH ){
        return 0;
    }

    regfree(&regex);

它匹配字符串 sdsda5dada 中包含的数字 5。如何进入匹配部分的变量?假设我有一个名为 matchd_strchar * 变量,我如何将 5 放入该变量?

我知道这是一个非常菜鸟的问题,但我对正则表达式知之甚少。提前致谢。

最佳答案

man regexec 指出:

The 0th member of the pmatch array is filled in to indicate what substring
of string was matched by the entire RE. Remaining members report what
substring was matched by parenthesized subexpressions within the RE.

因此,您必须将 pmatch 参数指向至少一个元素的 regmatch_t 数组,并将 nmatch 设置为 pmatch 的大小。 pmatch[0]rm_sorm_se 字段将指出字符串的匹配部分:

 const char *string = "sdsda5dada";
 const char *digit_start = string + pmatch[0].rm_so;
 const char *digit_end = string + pmatch[0].rm_se;
 int digit_len = digit_end - digit_start;

它不是 NUL 终止的,如果你想要一个正确的 C 字符串,你将不得不复制它,例如:

 char digit_copy[10];

 if (digit_len >= sizeof(digit_copy))
     digit_len = sizoef(digit_copy) - 1;
 memcpy(digit_copy, digit_start, digit_len);
 digit_copy[digit_len] = '\0';

nmatch 是第三个参数,patch 是第四个参数。这是概要:

 int
 regexec(const regex_t *restrict preg, const char *restrict string, size_t nmatch, regmatch_t pmatch[restrict],
     int eflags);

关于C Regex - 获取匹配的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21941461/

相关文章:

c - 程序不读取 printf 并在 main 之前启动?

c - 在 C 中将指针分配给变量和将指针分配给数组

c - C 中多维数组中指针的使用

java - 如何使用正则表达式匹配和排除 "!x"?

regex - 将正则表达式与项目加载器一起使用

regex - Hive RegexSerDe多行日志匹配

c++ - 如何使进程忽略某些信号(如 SIGHUP、SIGABRT、SIGABORT、SIGINT 等)

javascript - 正则表达式:无法进行负向预测

android - 从<img>标签android中提取图片src

c++ - 增量变量 "never used"?