我想使用C中的regex.h库从表达式中提取子字符串.这是代码
#include#include #include int main(void) { regex_t preg; char *string = "Random_ddName:cateof:Name_Random"; char *pattern = ".*Name:\\(.*\\):Name.*"; int rc; size_t nmatch = 1; regmatch_t pmatch[1]; if (0 != (rc = regcomp(&preg, pattern, 0))) { printf("regcomp() failed, returning nonzero (%d)\n", rc); exit(EXIT_FAILURE); } if (0 != (rc = regexec(&preg, string, nmatch, pmatch, 0))) { printf("Failed to match '%s' with '%s',returning %d.\n", string, pattern, rc); } else { printf("With the whole expression, " "a matched substring \"%.*s\" is found at position %d to %d.\n", pmatch[0].rm_eo - pmatch[0].rm_so, &string[pmatch[0].rm_so], pmatch[0].rm_so, pmatch[0].rm_eo - 1); } regfree(&preg); return 0; }
我想提取字符串"cateof",但我想确保字符串Name:和:Name之间.cateof是随机的,它会动态变化,这是我需要的唯一部分.我怎样才能立刻得到它?是否可以使用反向引用来存储我需要的值?
您必须指定nmatch = 2
,以便pmatch[0]
包含所需的整个匹配和子匹配pmatch[1]
.
需要的代码更改:
size_t nmatch = 2; regmatch_t pmatch[2];
和
... pmatch[1].rm_eo - pmatch[1].rm_so, &string[pmatch[1].rm_so], pmatch[1].rm_so, pmatch[1].rm_eo - 1); ...