home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / regexps.zip / regsub.c < prev    next >
C/C++ Source or Header  |  1996-09-05  |  1KB  |  61 lines

  1. /*
  2.  * regsub
  3.  */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <string.h>
  7. #include <ctype.h>
  8. #include <regexp.h>
  9. #include "regmagic.h"
  10.  
  11. /*
  12.  - regsub - perform substitutions after a regexp match
  13.  */
  14. void
  15. regsub(rp, source, dest)
  16. const regexp *rp;
  17. const char *source;
  18. char *dest;
  19. {
  20.     register regexp * const prog = (regexp *)rp;
  21.     register char *src = (char *)source;
  22.     register char *dst = dest;
  23.     register char c;
  24.     register int no;
  25.     register size_t len;
  26.  
  27.     if (prog == NULL || source == NULL || dest == NULL) {
  28.         regerror("NULL parameter to regsub");
  29.         return;
  30.     }
  31.     if ((unsigned char)*(prog->program) != MAGIC) {
  32.         regerror("damaged regexp");
  33.         return;
  34.     }
  35.  
  36.     while ((c = *src++) != '\0') {
  37.         if (c == '&')
  38.             no = 0;
  39.         else if (c == '\\' && isdigit(*src))
  40.             no = *src++ - '0';
  41.         else
  42.             no = -1;
  43.  
  44.         if (no < 0) {    /* Ordinary character. */
  45.             if (c == '\\' && (*src == '\\' || *src == '&'))
  46.                 c = *src++;
  47.             *dst++ = c;
  48.         } else if (prog->startp[no] != NULL && prog->endp[no] != NULL &&
  49.                     prog->endp[no] > prog->startp[no]) {
  50.             len = prog->endp[no] - prog->startp[no];
  51.             (void) strncpy(dst, prog->startp[no], len);
  52.             dst += len;
  53.             if (*(dst-1) == '\0') {    /* strncpy hit NUL. */
  54.                 regerror("damaged match string");
  55.                 return;
  56.             }
  57.         }
  58.     }
  59.     *dst++ = '\0';
  60. }
  61.