regsub.c revision 1.1 1 1.1 cgd /*
2 1.1 cgd * regsub
3 1.1 cgd *
4 1.1 cgd * Copyright (c) 1986 by University of Toronto.
5 1.1 cgd * Written by Henry Spencer. Not derived from licensed software.
6 1.1 cgd *
7 1.1 cgd * Permission is granted to anyone to use this software for any
8 1.1 cgd * purpose on any computer system, and to redistribute it freely,
9 1.1 cgd * subject to the following restrictions:
10 1.1 cgd *
11 1.1 cgd * 1. The author is not responsible for the consequences of use of
12 1.1 cgd * this software, no matter how awful, even if they arise
13 1.1 cgd * from defects in it.
14 1.1 cgd *
15 1.1 cgd * 2. The origin of this software must not be misrepresented, either
16 1.1 cgd * by explicit claim or by omission.
17 1.1 cgd *
18 1.1 cgd * 3. Altered versions must be plainly marked as such, and must not
19 1.1 cgd * be misrepresented as being the original software.
20 1.1 cgd */
21 1.1 cgd #include <regexp.h>
22 1.1 cgd #include <stdio.h>
23 1.1 cgd #include <string.h>
24 1.1 cgd #include "regmagic.h"
25 1.1 cgd
26 1.1 cgd #ifndef CHARBITS
27 1.1 cgd #define UCHARAT(p) ((int)*(unsigned char *)(p))
28 1.1 cgd #else
29 1.1 cgd #define UCHARAT(p) ((int)*(p)&CHARBITS)
30 1.1 cgd #endif
31 1.1 cgd
32 1.1 cgd /*
33 1.1 cgd - regsub - perform substitutions after a regexp match
34 1.1 cgd */
35 1.1 cgd void
36 1.1 cgd regsub(prog, source, dest)
37 1.1 cgd const regexp *prog;
38 1.1 cgd const char *source;
39 1.1 cgd char *dest;
40 1.1 cgd {
41 1.1 cgd register char *src;
42 1.1 cgd register char *dst;
43 1.1 cgd register char c;
44 1.1 cgd register int no;
45 1.1 cgd register int len;
46 1.1 cgd extern char *strncpy();
47 1.1 cgd
48 1.1 cgd if (prog == NULL || source == NULL || dest == NULL) {
49 1.1 cgd regerror("NULL parm to regsub");
50 1.1 cgd return;
51 1.1 cgd }
52 1.1 cgd if (UCHARAT(prog->program) != MAGIC) {
53 1.1 cgd regerror("damaged regexp fed to regsub");
54 1.1 cgd return;
55 1.1 cgd }
56 1.1 cgd
57 1.1 cgd src = (char *)source;
58 1.1 cgd dst = dest;
59 1.1 cgd while ((c = *src++) != '\0') {
60 1.1 cgd if (c == '&')
61 1.1 cgd no = 0;
62 1.1 cgd else if (c == '\\' && '0' <= *src && *src <= '9')
63 1.1 cgd no = *src++ - '0';
64 1.1 cgd else
65 1.1 cgd no = -1;
66 1.1 cgd if (no < 0) { /* Ordinary character. */
67 1.1 cgd if (c == '\\' && (*src == '\\' || *src == '&'))
68 1.1 cgd c = *src++;
69 1.1 cgd *dst++ = c;
70 1.1 cgd } else if (prog->startp[no] != NULL && prog->endp[no] != NULL) {
71 1.1 cgd len = prog->endp[no] - prog->startp[no];
72 1.1 cgd (void) strncpy(dst, prog->startp[no], len);
73 1.1 cgd dst += len;
74 1.1 cgd if (len != 0 && *(dst-1) == '\0') { /* strncpy hit NUL. */
75 1.1 cgd regerror("damaged match string");
76 1.1 cgd return;
77 1.1 cgd }
78 1.1 cgd }
79 1.1 cgd }
80 1.1 cgd *dst++ = '\0';
81 1.1 cgd }
82