2 * Sherlock Library -- Regular Expressions
4 * (c) 1997 Martin Mares <mj@ucw.cz>
5 * (c) 2001 Robert Spalek <robert@ucw.cz>
9 #include "lib/chartype.h"
17 #define INITIAL_MEM 1024 /* Initial space allocated for each pattern */
18 #define CHAR_SET_SIZE 256 /* How many characters in the character set. */
21 struct re_pattern_buffer buf;
22 struct re_registers regs; /* Must not change between re_match() calls */
27 rx_compile(byte *p, int icase)
29 regex *r = xmalloc_zero(sizeof(regex));
32 r->buf.buffer = xmalloc(INITIAL_MEM);
33 r->buf.allocated = INITIAL_MEM;
37 r->buf.translate = xmalloc (CHAR_SET_SIZE);
38 /* Map uppercase characters to corresponding lowercase ones. */
39 for (i = 0; i < CHAR_SET_SIZE; i++)
40 r->buf.translate[i] = Cupper(i) ? tolower (i) : i;
43 r->buf.translate = NULL;
44 msg = re_compile_pattern(p, strlen(p), &r->buf);
47 die("Error parsing pattern `%s': %s", p, msg);
58 rx_match(regex *r, byte *s)
63 if (re_match(&r->buf, s, len, 0, &r->regs) < 0)
65 if (r->regs.start[0] || r->regs.end[0] != len) /* XXX: Why regex doesn't enforce implicit "^...$" ? */
71 rx_subst(regex *r, byte *by, byte *src, byte *dest, uns destlen)
73 byte *end = dest + destlen - 1;
75 if (!rx_match(r, src))
83 if (*by >= '0' && *by <= '9') /* \0 gets replaced by entire pattern */
86 if (j < r->regs.num_regs)
88 byte *s = src + r->regs.start[j];
89 uns i = r->regs.end[j] - r->regs.start[j];
90 if (r->regs.start[j] > r->len_cache || r->regs.end[j] > r->len_cache)
111 void main(int argc, char **argv)
114 byte buf1[256], buf2[256];
116 r = rx_compile(argv[1]);
117 while (fgets(buf1, sizeof(buf1), stdin))
119 char *p = strchr(buf1, '\n');
124 if (rx_match(r, buf1))
131 int i = rx_subst(r, argv[2], buf1, buf2, sizeof(buf2));