Regex, replace all occurrences of subgroup

Following code is generalized. Supports PCRE, PCRE2 and stl regex libs

bool U::String::replaceExAll(string &s, const string& replace_this_reg_ex, const string& replace_with, bool case_sensitive, bool extended)
{
#ifdef UTIL_USE_PCRE
    pcrecpp::RE_Options options;
    options.set_utf8(true);
    options.set_caseless(!case_sensitive);
    pcrecpp::RE(replace_this_reg_ex, options).GlobalReplace(replace_with, &s);
    return true;
#elif UTIL_USE_PCRE2
    jp8::Regex re(replace_this_reg_ex);
    if(!case_sensitive)
            re.addPcre2Option(PCRE2_CASELESS).compile();

    jp8::RegexReplace& rp = re.initReplace();
    rp.setSubject(s)
                .setReplaceWith(replace_with)
                .setBufferSize(s.length() * 2);

    if(extended)
        rp.addPcre2Option(PCRE2_SUBSTITUTE_EXTENDED);
    rp.addPcre2Option(PCRE2_SUBSTITUTE_GLOBAL);
    // PCRE2_DOTALL PCRE2_MULTILINE PCRE2_UTF does not work

    s = rp.replace();
    return re.getErrorNumber() == 0;
#else
    regex rx = regex(replace_this_reg_ex, case_sensitive ? 0 : regex_constants::icase);;
    std:string temp = std::regex_replace(s, rx, replace_with);
    s = temp;

    return true;
#endif
}

for c++ PCRE2 wrapper use this lib: JPCRE2

Tags:

C++

Regex

Replace