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?

5
  • 1
    Do you want to call the callback function once and use that for all replacements, or call it once per match?
    – Shawn
    Aug 8, 2022 at 20:31
  • Oo, good question. Why not both? So three functions in total, I am interested in. Thank you. Aug 8, 2022 at 21:47
  • The call it once case is easy: just reuse your existing code.
    – Shawn
    Aug 8, 2022 at 22:08
  • For the once per match, a loop using pcre2_substitute() without the global flag and passing match info. Memory management will be a pain though.
    – Shawn
    Aug 8, 2022 at 22:10
  • Code snippet please? Aug 8, 2022 at 23:11

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.