Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex, replace all occurrences of subgroup

Tags:

c++

regex

replace

I want to replace "all" occurrences of "a" within the parenthesis with "b".

I have:

std::string s = "a(aaa)a";
std::regex e("(\\(.*?)(a)(.*\\))");
s = std::regex_replace(s, e, "$1b$3");

std::cout << s << std::endl;

It outputs:

a(baa)a

But I want:

a(bbb)a
like image 615
Adelost Avatar asked Dec 03 '14 21:12

Adelost


1 Answers

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

like image 139
Behrouz.M Avatar answered Sep 19 '22 19:09

Behrouz.M