Reputation: 1768
I'd like to remove certain lines (let's assume 'aaa' and 'bbb') from a multiline string with the standard C++ regex library. With ECMAScript replace syntax, I would use the next pattern: /^(aaa|bbb)$/gm
. I tried to pass something like ^(aaa|bbb)$
as regex argument to std::regex_replace
, but it's not working, as ^
and $
seem to not get matched as the beginning and the end of line, though I didn't pass match_not_eol
or match_not_bol
as match flags. So how the C++ pattern should look like for this case?
Upvotes: 2
Views: 1814
Reputation: 627103
The regex_replace
reference does not list any flag to redefine the ^
and $
meanings. Thus, when you need to search and replace lines, use the capturing group (^|\r?\n)
before and a lookahead (?=\r?\n|$)
after the main pattern (and replace with backreference $1
). Surely, the patterns can be adjusted to allow or not empty lines after the replacement.
See IDEONE demo:
std::string s("ccc\r\naaa\r\ngggg");
std::regex ee(R"((^|\r?\n)(?:aaa|bbb)(?=\r?\n|$))");
std::string newtext = std::regex_replace( s, ee, "$1" );
std::cout << newtext << std::endl;
Output:
ccc
gggg
Upvotes: 1