linux c pcre 正则匹配多个目标
程序员文章站
2022-06-04 13:17:19
...
#include <pcre.h>
#define OVECCOUNT 30
void main() {
char *in = "20171208121020Z 20171208121020Z\n20171208121020Z";
char *pattern = "(19|20)([\\d]{2})([0-1][0-9])([0-3][0-9])([0-2][0-9])([0-6][0-9])([0-6][0-9])(\\.?[0-9]{0,3})(Z?)";
pcre *re;
const char *err, *p;
int erroffset;
int ovector[OVECCOUNT], i, rc, srcLen, ret;
char *src, *src1;
re = pcre_compile(pattern, 0, &err, &erroffset, NULL);
if (NULL == re) {
printf("pcre compile error:%s", err);
return;
}
//try multiple target match
src = src1 = in;
srcLen = strlen(src);
while (1) {
printf("<%s>\n", src);
rc = pcre_exec(re, NULL, src, srcLen, 0, 0, ovector, OVECCOUNT);
if (rc < 0) {
printf("pcre exec error");
break;
}
for (i = 0; i < rc; i++) {
int ret = pcre_get_substring(src, ovector, rc, i, &p);
printf("%d, %s\n", ret, p);
pcre_free_substring(p);
}
ret = pcre_get_substring(src, ovector, rc, 0, &p);
pcre_free_substring(p);
if (ret > 0) {
src1 += ret + ovector[0];
srcLen = srcLen - (src1 - src);
src = src1;
if (srcLen <= 0) {
break;
}
}
}
pcre_free(re);
}