C匹配和打印中的正则表达式

我有这样的文件行:

{123} {12.3.2015 moday} {THIS IS A TEST} 

是否有可能获得括号{}和插入数组之间的每个值?

此外,我想知道是否有其他解决方案来解决这个问题…

得到这样的:

 array( 123, '12.3.2015 moday', 'THIS IS A TEST' ) 

我的尝试:

  int r; regex_t reg; regmatch_t match[2]; char *line = "{123} {12.3.2015 moday} {THIS IS A TEST}"; regcomp(&reg, "[{](.*?)*[}]", REG_ICASE | REG_EXTENDED); r = regexec(&reg, line, 2, match, 0); if (r == 0) { printf("Match!\n"); printf("0: [%.*s]\n", match[0].rm_eo - match[0].rm_so, line + match[0].rm_so); printf("1: %.*s\n", match[1].rm_eo - match[1].rm_so, line + match[1].rm_so); } else { printf("NO match!\n"); } 

这将导致:

 123} {12.3.2015 moday} {THIS IS A TEST 

有谁知道如何改善这个?

为了帮助您,您可以使用真正有用的regex101网站。

然后我建议你使用这个正则表达式:

 /(?<=\{).*?(?=\})/g 

或者这些中的任何一个:

 /\{\K.*?(?=\})/g /\{\K[^\}]+/g /\{(.*?)\}/g 

也可以在这里找到第一个:

https://regex101.com/r/bB6sE8/1

在C中你可以从这开始,这是一个例子:

 #include  #include  #include  int main () { char * source = "{123} {12.3.2015 moday} {THIS IS A TEST}"; char * regexString = "{([^}]*)}"; size_t maxGroups = 10; regex_t regexCompiled; regmatch_t groupArray[10]; unsigned int m; char * cursor; if (regcomp(&regexCompiled, regexString, REG_EXTENDED)) { printf("Could not compile regular expression.\n"); return 1; }; cursor = source; while (!regexec(&regexCompiled, cursor, 10, groupArray, 0)) { unsigned int offset = 0; if (groupArray[1].rm_so == -1) break; // No more groups offset = groupArray[1].rm_eo; char cursorCopy[strlen(cursor) + 1]; strcpy(cursorCopy, cursor); cursorCopy[groupArray[1].rm_eo] = 0; printf("%s\n", cursorCopy + groupArray[1].rm_so); cursor += offset; } regfree(&regexCompiled); return 0; }