You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++如何使用std::regex_replace按规则替换不同换行符组合

问题原因

C++标准库的std::regex_replace仅支持传入符合正则替换语法的字符串作为替换参数,不支持直接传入自定义lambda回调处理匹配结果,因此你的原有代码无法正常运行。


可行实现方案

方案1:正则迭代器遍历实现(匹配你原有的正则逻辑)

通过std::sregex_iterator遍历所有匹配的换行符组合,手动拼接替换后的字符串:

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

int main() {
    std::string input = "\rThis is just an example\n Learning CPP \r\n Stuck at a point \r\n\n\r C++11 onwards \r\r\r\n\n";
    const std::regex search_exp(R"([\r\n]+)");
    std::string output;
    auto last_pos = input.cbegin();
    // 遍历所有匹配到的换行符组合
    for (std::sregex_iterator it(input.cbegin(), input.cend(), search_exp), end_it; it != end_it; ++it) {
        // 先拼接当前匹配位置之前的普通文本
        output.append(last_pos, it->prefix().second);
        std::string match_str = it->str();
        std::string replace_str;
        // 按规则执行替换
        if (match_str.size() == 1) {
            replace_str = (match_str == "\r") ? "\n" : match_str;
        } else if (match_str.size() == 2 && match_str[0] != match_str[1]) {
            replace_str = "\n";
        } else {
            replace_str = "\n\n";
        }
        output += replace_str;
        last_pos = it->suffix().first;
    }
    // 拼接最后一段未匹配的普通文本
    output.append(last_pos, input.cend());

    // 验证输出(转义显示换行符便于核对)
    std::cout << "替换后结果:\n";
    for (char c : output) {
        if (c == '\r') std::cout << "\\r";
        else if (c == '\n') std::cout << "\\n";
        else std::cout << c;
    }
    return 0;
}

方案2:原生扫描实现(性能更高,无正则依赖)

如果需要处理大体积文本,直接扫描字符串处理的性能远高于正则方案:

#include <iostream>
#include <string>

std::string replace_newline(std::string input) {
    std::string output;
    output.reserve(input.size()); // 预分配空间减少内存拷贝
    int len = input.size();
    int idx = 0;
    while (idx < len) {
        // 普通字符直接追加
        if (input[idx] != '\r' && input[idx] != '\n') {
            output += input[idx];
            idx++;
            continue;
        }
        // 统计连续换行符长度
        int start = idx;
        while (idx < len && (input[idx] == '\r' || input[idx] == '\n')) {
            idx++;
        }
        int newline_len = idx - start;
        // 按规则替换
        if (newline_len == 1 || (newline_len == 2 && input[start] != input[start+1])) {
            output += '\n';
        } else {
            output += "\n\n";
        }
    }
    return output;
}

内容的提问来源于stack exchange,提问作者atulya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 04:24:03