Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

RegEx Replace Empty Lines in C++

I want to delete blank lines in an input string using regex_replace(); however, the regular expression "^\n" isn’t working in my code, even though it works when I test it on RegExr. Here is my code:

    std::string s = "filler text\n\nfiller text";

    std::regex reg("^\n");

    std::cout << s;

    s = std::regex_replace(s, reg, "");

    cout << '\n' << s;

Outputs:

filler text

filler text
filler text

filler text

Should I just resort to replacing any two newlines with just one? Then I’d have to loop until no matches are found, though. Why isn’t this method working when there’s seemingly nothing wrong with it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Rather than dealing with "end of line", I’d just replace multiple consecutive new-lines with a single new-line:

#include <iostream>
#include <string>
#include <regex>

int main(int argc, char **argv) {
    std::string s = "filler text\n\nfiller text";

    std::regex reg("\n+");

    std::cout << "Before:\n";
    std::cout << s << "\nAfter:\n";

    s = std::regex_replace(s, reg, "\n");

    std::cout << '\n' << s << '\n';
}

The result looks like this:

Before:
filler text

filler text
After:

filler text
filler text
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading