我有这段代码:
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 数字。如何进入匹配部分的变量?假设我有一个名为char *
的{{1}}变量,如何将 5 放入该变量?
我知道这是一个非常棒的问题,但我对正则表达不太了解。提前谢谢。
答案 0 :(得分:0)
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的大小。 rm_so
的{{1}}和rm_se
字段将指出字符串的匹配部分:
pmatch[0]
它不是NUL终止,如果你想要一个合适的C字符串,你将不得不复制它,例如:
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;
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