c++ - Regex to replace all occurrences between two matches -
i using std::regex
, need search , replace.
the string have is:
begin foo spaces , maybe new line( text replace foo foo bar foo, keep rest ) more text not replace foo here
only stuff between begin .... (
, )
should touched.
i manage replace first foo using search , replace:
(begin[\s\s]*?\([\s\s]*?)foo([\s\s]*?\)[\s\s]*) $1abc$2
however, how replace 3 foo in 1 pass? tried lookarounds, failed because of quantifiers.
the end result should this:
begin foo spaces , maybe new line( text replace abc abc bar abc, keep rest ) more text not replace foo here
question update:
i looking pure regex solution. is, question should solved changing search
, replace
strings in the online c++ demo.
i have come code (based on benjamin lindley's answer):
#include <iostream> #include <regex> #include <string> int main() { std::string input_text = "my text\nbegin foo 14 spaces , maybe \nnew line(\nsome text replace foo foo bar foo, keep rest\n)\nsome more text not replace foo here"; std::regex re(r"((begin[^(]*)(\([^)]*\)))"); std::regex rxreplace(r"(\bfoo\b)"); std::string output_text; auto callback = [&](std::string const& m){ std::smatch smtch; if (regex_search(m, smtch, re)) { output_text += smtch[1].str(); output_text += std::regex_replace(smtch[2].str().c_str(), rxreplace, "abc"); } else { output_text += m; } }; std::sregex_token_iterator begin(input_text.begin(), input_text.end(), re, {-1,0}), end; std::for_each(begin,end,callback); std::cout << output_text; return 0; }
see ideone demo
i using 1 regex find matches of begin...(....)
, pass them callback function group 2 processed further (a \bfoo\b
regex used replace foo
s abc
s).
i suggest using (begin[^(]*)(\([^)]*\))
regex:
(begin[^(]*)
- group 1 matching character sequencebegin
followed 0 or more characters other(
(\([^)]*\))
- group 2 matching literal(
followed 0 or more characters other)
(with[^)]*
) , literal)
.
Comments
Post a Comment