1

So, I'm working on a preprocessor for C, my post on another site went semi viral (cprogramming.com)

What I want is a function, using PCRE2, that replaces a string with another string.

  • I also want a function that replaces a string with the result of a callback (a null-terminated) string for each match of a string

Ruby has

str.gsub /foo/ do |i|

end

I have code that does the first one, see (https://cboard.cprogramming.com/c-programming/181161-c-regular-expressions.html)

#define PCRE2_CODE_UNIT_WIDTH 8
#include <pcre2.h>

char* gsub (const char* str, const char* reg, const char* rep) {
    size_t outlen;
    static const char* error_str = "\"DONT KNOW HOW TO ALLOCATE MEM FOR REGEX\"";
    char* out = malloc(outlen =strlen(str) *      strlen(rep))  ;
    if (out == NULL) {
        error:
    fputs(error_str,   stderr);
return NULL;
    }
    
    int error;
    PCRE2_SIZE erroffset;
//                                       printf(\"       %l                             \", 
    const PCRE2_SPTR pattern = (PCRE2_SPTR)reg;
    const PCRE2_SPTR subject = (PCRE2_SPTR)str;
    const PCRE2_SPTR replacement = (PCRE2_SPTR)rep;

    pcre2_code *re = pcre2_compile(pattern, PCRE2_ZERO_TERMINATED, 0, &error, &erroffset, 0);
    if (re == 0) return NULL;
//        return 1;

    pcre2_jit_compile(re, PCRE2_JIT_COMPLETE);

    int rc = pcre2_substitute(re, subject, PCRE2_ZERO_TERMINATED, 0, PCRE2_SUBSTITUTE_GLOBAL | PCRE2_SUBSTITUTE_EXTENDED, 0, 0, replacement, PCRE2_ZERO_TERMINATED, out, &outlen);
    if (rc >= 0);
//        printf(%s\\n, output);

    pcre2_code_free(re);
    size_t new_len = strlen(out);
    char* new_out = realloc(out,new_len + 1);
    if (new_out == NULL) goto error;

    return   new_out;
   }
  • Could someone help me to make the second function ?

  • Is there any way to have PCRE automatically account for memory allocation sizes?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278

0 Answers0