在C匹配和定期打印前pressions [英] regular expressions in C match and print
本文介绍了在C匹配和定期打印前pressions的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我从文件中这样的行:
{123} {12.3.2015 moday} {THIS IS A TEST}
是有可能得到括号内的每一个值 {}
,并插入到数组?
此外,我沃尔德想知道是否有这个问题...
Also I wold like to know if there is some other solution for this problem...
要得到这样的:
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
任何人都知道如何改进呢?
Anyone know how to improve this?
推荐答案
要帮助你,你可以使用 regex101 网站,这是非常有用的。
To help you you can use the regex101 website which is really useful.
那我建议你使用这个正则表达式:
Then I suggest you to use this regex:
/(?<=\{).*?(?=\})/g
或任何这些的的:
/\{\K.*?(?=\})/g
/\{\K[^\}]+/g
/\{(.*?)\}/g
也可以在这里的第一个:
Also available here for the first one:
https://regex101.com/r/bB6sE8/1
在C语言中,你可以用这个这是一个例子这里启动:
In C you could start with this which is an example for 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;
}
这篇关于在C匹配和定期打印前pressions的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文