#include <stdio.h>
#include <sys/types.h>
#include <string.h>
#include <regex.h>
/**
* 要提取出字符串中的时间,消息类型,发送者 接收者 消息内容
*/
int main(int argc, char** argv) {
char *str = "20120302T12:12:12: [message] (test): [SAVE] chat 12234124@test to 234325@test: content";
char * pattern = "([0-9]{4}[0-9]{2}[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}): \\[message\\].+\\[\.+\] ([a-zA-Z]+) ([0-9a-z]+)@.+ to ([0-9a-z]+)@.+: (.+)";
regex_t reg;
regmatch_t pm[10];
int z,cflags = 0;;
z = regcomp(®, pattern, cflags);
//先编译正则表达式,正确返回0
if (z != 0) {
regerror(z, ®, ebuf, sizeof(ebuf));
fprintf(stderr, "%s: pattern '%s' \n", ebuf, pattern);
return 1;
}
z = regexec(®, lbuf, nmatch, pm, 0);
if (z == REG_NOMATCH)
continue;
else if (z != 0) {
regerror(z, ®, ebuf, sizeof(ebuf));
fprintf(stderr, "%s: regcom('%s')\n", ebuf, lbuf);
return 2;
}
/* 输出处理结果 */
for (x = 0; x < nmatch && pm[x].rm_so != -1; ++x) {
if (!x)
printf("%04d: %s\n", lno, lbuf);
printf(" $%d='%s'\n", x, substr(lbuf, pm[x].rm_so, pm[x].rm_eo));
}
/* 释放正则表达式 */
regfree(®);
return 0;
}
linux c 正则表达式
最新推荐文章于 2021-05-14 18:15:17 发布