view rcg.c @ 2:4efb50ce4c9c

rcg.c: expect only one match at a time from regexec()
author pang@apollo5.intellisis
date Mon, 05 Apr 2010 21:02:51 -0700
parents 2b95aa9e4e46
children fe4b316b4386
line source
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <regex.h>
5 #define __USE_GNU
6 #include <string.h>
8 const size_t BUFSIZE = 5000;
10 const char *CLR_START = "-CLR_START-";
11 const char *CLR_END = "-CLR_END-";
13 int main(int argc, char **argv)
14 {
15 char *buf = calloc(BUFSIZE, sizeof(char));
17 regex_t *re = calloc(1, sizeof(regex_t));
18 regcomp(re, "Hello", REG_EXTENDED);
20 regmatch_t *rem = calloc(1, sizeof(regmatch_t));
22 size_t CLR_START_len = strlen(CLR_START);
23 size_t CLR_END_len = strlen(CLR_END);
25 char *out = NULL;
26 unsigned int out_pos = 0;
27 unsigned int buf_pos = 0;
29 while (fgets(buf, BUFSIZE, stdin))
30 {
31 int i = 0;
32 int so = -1;
33 int eo = -1;
35 do
36 {
37 regexec(re, &buf[buf_pos], 1, rem, 0);
39 size_t out_len = strlen(&buf[buf_pos]);
40 if (out_len >= (BUFSIZE - buf_pos))
41 out_len = (BUFSIZE - buf_pos) - 1;
43 so = rem[0].rm_so;
44 eo = rem[0].rm_eo;
46 fprintf(stderr, "%d %d \n", so, eo); //d// 20100327 PBA
48 if (so >= 0 && eo >= 0)
49 {
50 int match_len = eo - so;
51 out_len += CLR_START_len + CLR_END_len;
52 out = (char *)realloc(out, out_len*sizeof(char));
53 if (i++ == 0)
54 {
55 strncpy(out, buf, so);
56 out_pos += so;
57 buf_pos += so;
58 }
59 strncpy(&out[out_pos], CLR_START, CLR_START_len);
60 out_pos += CLR_START_len;
61 strncpy(&out[out_pos], &buf[buf_pos], match_len);
62 out_pos += match_len;
63 strncpy(&out[out_pos], CLR_END, CLR_END_len);
64 out_pos += CLR_END_len;
66 buf_pos += match_len;
67 }
68 else
69 strncpy(&out[out_pos], &buf[eo], out_len - out_pos);
70 }
71 while (so >= 0 && eo >= 0);
73 fputs(out, stdout);
74 }
76 return 0;
77 }