我有这样的文件行:
{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_ICASE | REG_EXTENDED);
r = regexec(®, 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
任何人都知道如何改进这个?
答案 0 :(得分:2)
为了帮助您,您可以使用真正有用的regex101网站。
然后我建议你使用这个正则表达式:
/(?<=\{).*?(?=\})/g
或其中任何一个:
/\{\K.*?(?=\})/g
/\{\K[^\}]+/g
/\{(.*?)\}/g
这里也可以提供第一个:
https://regex101.com/r/bB6sE8/1
在C中你可以从这开始,这是here的一个例子:
#include <stdio.h>
#include <string.h>
#include <regex.h>
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(®exCompiled, regexString, REG_EXTENDED))
{
printf("Could not compile regular expression.\n");
return 1;
};
cursor = source;
while (!regexec(®exCompiled, 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(®exCompiled);
return 0;
}