首页 > 解决方案 > 如何在参考上进行 regex_replace

问题描述

我有这个方法:

std::string pluralize(std::string const& word) const {
        std::regex_replace(word, m_pattern, m_replacement);
        return word;
    }

但它没有按预期工作。字符串不会被给定的规则替换。是否可以regex_replace在引用上做而不是返回这个变量的引用?

标签: c++reference

解决方案


regex_replace原地不变,但返回新的string

std::string pluralize(std::string const& word) const {
    return std::regex_replace(word, m_pattern, m_replacement);;
}

如果要编辑原件string

void pluralize(std::string &word) const {
    word = std::regex_replace(word, m_pattern, m_replacement);
}

如果你想要修改和返回:

std::string pluralize(std::string &word) const {
    return word = std::regex_replace(word, m_pattern, m_replacement);
}

推荐阅读