regex_replace flag to ignore multiline?

Marcus 41 Reputation points
2022-09-07T20:03:09.997+00:00

DEMO

#include <iostream>  
#include <regex>  
  
int main()  
{  
    std::string text = R"(blue  
red  
green  
)";  
    std::regex re("^red+\n");  
    std::string str = std::regex_replace(text, re, "");  
    std::cout << str;  
  return 0;  
}  

The compile of the demo above the regex doesn't replace red I think by default it doesn't do a multiline search/replace? while on visual studio the exactly same code red is replaced.

How could I make Visual Studio behave the same? I mean, doesn't replace things on multiline if doesn't ask to.

While searching about I found this in MSDN docs: Regex Flags.

I wonder if I need to specify any special flag? I read the flags in the link but I still couldn't figure out which to use.

Developer technologies | C++
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. YujianYao-MSFT 4,296 Reputation points Microsoft External Staff
    2022-09-08T02:23:47.233+00:00

    Hi @Marcus ,

    If you want visual studio to get the same result as the demo, you need to use match_continuous, which specifies that the expression must match a sub-sequence that begins at first.

    Sample Code:

    std::regex re("^red+\n");  
    std::string str = std::regex_replace(text, re, "",std::regex_constants::match_continuous);  
    

    Result:

    238866-pict1.png

    Best regards,

    Elya


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.