代码之家  ›  专栏  ›  技术社区  ›  Youssef Gamil

RegEx替换C中的空行++

  •  0
  • Youssef Gamil  · 技术社区  · 10 月前

    我想使用以下命令删除输入字符串中的空白行 regex_replace() ; 然而,正则表达式 "^\n" 在我的代码中不起作用,即使在我测试时它起作用 RegExr 。这是我的代码:

        std::string s = "filler text\n\nfiller text";
    
        std::regex reg("^\n");
    
        std::cout << s;
    
        s = std::regex_replace(s, reg, "");
    
        cout << '\n' << s;
    

    输出:

    filler text
    
    filler text
    filler text
    
    filler text
    

    我是否应该只用一个换行符替换任何两个换行符?然后我必须循环,直到找不到匹配项为止。为什么这种方法在看似没有问题的情况下不起作用?

    1 回复  |  直到 10 月前
        1
  •  1
  •   Jerry Coffin    10 月前

    与其处理“行尾”,我只需用一行新行替换多行连续的新行:

    #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';
    }
    

    结果如下:

    Before:
    filler text
    
    filler text
    After:
    
    filler text
    filler text