Advertisement
Adam_mz_

OS2

May 1st, 2022
404
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.15 KB | None | 0 0
  1. #include <stdint.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <regex.h>
  5. #include <libc.h>
  6.  
  7.  
  8. int replaceInText(const char *pattern, char **str, const char *replace)
  9. {
  10.     char *s = *str;
  11.     regex_t reg;
  12.     char *new;
  13.     const char *p;
  14.  
  15.     if (regcomp(&reg, pattern, REG_EXTENDED))
  16.         return -1;
  17.  
  18.     size_t nm = reg.re_nsub;
  19.     regmatch_t pmatch[nm + 1];
  20.  
  21.     while (!regexec(&reg, s, nm + 1, pmatch, REG_NOTBOL))
  22.     {
  23.         new = (char *) malloc(strlen(*str) + strlen(replace));
  24.         strncat(new, *str, s - *str);
  25.         p = replace;
  26.         strncat(new, s, pmatch[0].rm_so);
  27.         strcat(new, p);
  28.         unsigned int off = strlen(new);
  29.         strcat(new, s + pmatch[0].rm_eo);
  30.         *str = (char *) malloc(strlen(new) + 1);
  31.         strcpy(*str, new);
  32.         s = *str + off;
  33.         free(new);
  34.     }
  35.     regfree(&reg);
  36.     *str = (char *) realloc(*str, strlen(*str) + 1);
  37.  
  38.     return 0;
  39. }
  40.  
  41. int main(int argc, char **argv)
  42. {
  43.  
  44.     char *regex = argv[1];
  45.     char *text = argv[2];
  46.     char *replacement = argv[3];
  47.     replaceInText(regex, &text, replacement);
  48.     printf("%s", text);
  49.  
  50.     return 0;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement