您需要傳入一組regmatch_t
s表示正則表達式可以填充匹配的索引。用一個命令行參數(要測試的字符串)嘗試下面的程序。
一旦你有了匹配的指數,它應該是相當容易的拉出你的東西。 (注:matches[0]
將是整個表達式的匹配,所以子表達式開始於matches[1]
。)
#include <stdlib.h>
#include <stdio.h>
#include <regex.h>
int main(int argc, char* argv[])
{
const char* pattern = "{{()*(([[:alnum:]]+\\.)*)?[[:alnum:]]+()*}}";
regex_t rex;
int rc;
if ((rc = regcomp(&rex, pattern, REG_EXTENDED))) {
fprintf(stderr, "error %d compiling regex\n", rc);
/* retrieve error here with regerror */
return -1;
}
regmatch_t* matches = malloc(sizeof(regex_t) * (rex.re_nsub + 1));
if ((rc = regexec(&rex, argv[1], rex.re_nsub + 1, matches, 0))){
printf("no match\n");
/* error or no match */
} else {
for(int i = 0; i < rex.re_nsub; ++i) {
printf("match %d from index %d to %d: ", i, matches[i].rm_so,
matches[i].rm_eo);
for(int j = matches[i].rm_so; j < matches[i].rm_eo; ++j) {
printf("%c", argv[1][j]);
}
printf("\n");
}
}
free(matches);
regfree(&rex);
return 0;
}