2 * Sherlock Library -- Regular Expressions
4 * (c) 1997 Martin Mares <mj@ucw.cz>
14 #define INITIAL_MEM 1024 /* Initial space allocated for each pattern */
17 struct re_pattern_buffer buf;
18 struct re_registers regs; /* Must not change between re_match() calls */
25 regex *r = xmalloc(sizeof(regex));
28 bzero(r, sizeof(struct regex));
29 r->buf.buffer = xmalloc(INITIAL_MEM);
30 r->buf.allocated = INITIAL_MEM;
31 msg = re_compile_pattern(p, strlen(p), &r->buf);
34 die("Error parsing pattern `%s': %s", p, msg);
45 rx_match(regex *r, byte *s)
50 if (re_match(&r->buf, s, len, 0, &r->regs) < 0)
52 if (r->regs.start[0] || r->regs.end[0] != len) /* XXX: Why regex doesn't enforce implicit "^...$" ? */
58 rx_subst(regex *r, byte *by, byte *src, byte *dest, uns destlen)
60 byte *end = dest + destlen - 1;
62 if (!rx_match(r, src))
70 if (*by >= '0' && *by <= '9') /* \0 gets replaced by entire pattern */
73 if (j < r->regs.num_regs)
75 byte *s = src + r->regs.start[j];
76 uns i = r->regs.end[j] - r->regs.start[j];
77 if (r->regs.start[j] > r->len_cache || r->regs.end[j] > r->len_cache)
98 void main(int argc, char **argv)
101 byte buf1[256], buf2[256];
103 r = rx_compile(argv[1]);
104 while (fgets(buf1, sizeof(buf1), stdin))
106 char *p = strchr(buf1, '\n');
111 if (rx_match(r, buf1))
118 int i = rx_subst(r, argv[2], buf1, buf2, sizeof(buf2));