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