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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With