我有这个代码:
regex_t regex;
int reti;
reti = regcomp(®ex, "[0-9]", REG_EXTENDED);
reti = regexec(®ex, "sdsda5dada", 0, NULL, 0);
if( !reti ){
return 1;
}
else if( reti == REG_NOMATCH ){
return 0;
}
regfree(®ex);
它匹配字符串 sdsda5dada
中包含的数字 5。如何进入匹配部分的变量?假设我有一个名为 matchd_str
的 char *
变量,我如何将 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_so
和 rm_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/