2 * Sherlock Library -- Regular Expressions
4 * (c) 1997 Martin Mares <mj@ucw.cz>
5 * (c) 2001 Robert Spalek <robert@ucw.cz>
7 * This software may be freely distributed and used according to the terms
8 * of the GNU Lesser General Public License.
12 #include "lib/chartype.h"
19 #define INITIAL_MEM 1024 /* Initial space allocated for each pattern */
20 #define CHAR_SET_SIZE 256 /* How many characters in the character set. */
23 struct re_pattern_buffer buf;
24 struct re_registers regs; /* Must not change between re_match() calls */
29 rx_compile(byte *p, int icase)
31 regex *r = xmalloc_zero(sizeof(regex));
34 r->buf.buffer = xmalloc(INITIAL_MEM);
35 r->buf.allocated = INITIAL_MEM;
39 r->buf.translate = xmalloc (CHAR_SET_SIZE);
40 /* Map uppercase characters to corresponding lowercase ones. */
41 for (i = 0; i < CHAR_SET_SIZE; i++)
42 r->buf.translate[i] = Cupcase(i);
45 r->buf.translate = NULL;
46 re_set_syntax(RE_SYNTAX_POSIX_EXTENDED);
47 msg = re_compile_pattern(p, strlen(p), &r->buf);
50 die("Error parsing pattern `%s': %s", p, msg);
58 xfree(r->buf.translate);
63 rx_match(regex *r, byte *s)
68 if (re_match(&r->buf, s, len, 0, &r->regs) < 0)
70 if (r->regs.start[0] || r->regs.end[0] != len) /* XXX: Why regex doesn't enforce implicit "^...$" ? */
76 rx_subst(regex *r, byte *by, byte *src, byte *dest, uns destlen)
78 byte *end = dest + destlen - 1;
80 if (!rx_match(r, src))
88 if (*by >= '0' && *by <= '9') /* \0 gets replaced by entire pattern */
91 if (j < r->regs.num_regs)
93 byte *s = src + r->regs.start[j];
94 uns i = r->regs.end[j] - r->regs.start[j];
95 if (r->regs.start[j] > r->len_cache || r->regs.end[j] > r->len_cache)
116 void main(int argc, char **argv)
119 byte buf1[256], buf2[256];
121 r = rx_compile(argv[1]);
122 while (fgets(buf1, sizeof(buf1), stdin))
124 char *p = strchr(buf1, '\n');
129 if (rx_match(r, buf1))
136 int i = rx_subst(r, argv[2], buf1, buf2, sizeof(buf2));