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 re_set_syntax(RE_SYNTAX_POSIX_EXTENDED);
45 msg = re_compile_pattern(p, strlen(p), &r->buf);
48 die("Error parsing pattern `%s': %s", p, msg);
59 rx_match(regex *r, byte *s)
64 if (re_match(&r->buf, s, len, 0, &r->regs) < 0)
66 if (r->regs.start[0] || r->regs.end[0] != len) /* XXX: Why regex doesn't enforce implicit "^...$" ? */
72 rx_subst(regex *r, byte *by, byte *src, byte *dest, uns destlen)
74 byte *end = dest + destlen - 1;
76 if (!rx_match(r, src))
84 if (*by >= '0' && *by <= '9') /* \0 gets replaced by entire pattern */
87 if (j < r->regs.num_regs)
89 byte *s = src + r->regs.start[j];
90 uns i = r->regs.end[j] - r->regs.start[j];
91 if (r->regs.start[j] > r->len_cache || r->regs.end[j] > r->len_cache)
112 void main(int argc, char **argv)
115 byte buf1[256], buf2[256];
117 r = rx_compile(argv[1]);
118 while (fgets(buf1, sizeof(buf1), stdin))
120 char *p = strchr(buf1, '\n');
125 if (rx_match(r, buf1))
132 int i = rx_subst(r, argv[2], buf1, buf2, sizeof(buf2));