c++regexc++17regexp-replace

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?


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