home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 18 REXX / 18-REXX.zip / rxregexp.zip / regsub.c < prev    next >
C/C++ Source or Header  |  2002-09-14  |  2KB  |  83 lines

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