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_zero(sizeof(regex));
28 r->buf.buffer = xmalloc(INITIAL_MEM);
29 r->buf.allocated = INITIAL_MEM;
30 msg = re_compile_pattern(p, strlen(p), &r->buf);
33 die("Error parsing pattern `%s': %s", p, msg);
44 rx_match(regex *r, byte *s)
49 if (re_match(&r->buf, s, len, 0, &r->regs) < 0)
51 if (r->regs.start[0] || r->regs.end[0] != len) /* XXX: Why regex doesn't enforce implicit "^...$" ? */
57 rx_subst(regex *r, byte *by, byte *src, byte *dest, uns destlen)
59 byte *end = dest + destlen - 1;
61 if (!rx_match(r, src))
69 if (*by >= '0' && *by <= '9') /* \0 gets replaced by entire pattern */
72 if (j < r->regs.num_regs)
74 byte *s = src + r->regs.start[j];
75 uns i = r->regs.end[j] - r->regs.start[j];
76 if (r->regs.start[j] > r->len_cache || r->regs.end[j] > r->len_cache)
97 void main(int argc, char **argv)
100 byte buf1[256], buf2[256];
102 r = rx_compile(argv[1]);
103 while (fgets(buf1, sizeof(buf1), stdin))
105 char *p = strchr(buf1, '\n');
110 if (rx_match(r, buf1))
117 int i = rx_subst(r, argv[2], buf1, buf2, sizeof(buf2));