且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 std::regex_replace 将字符串替换为小写?

更新时间:2023-02-20 08:11:16

既然没有像 \L 这样的魔法,我们不得不妥协——使用 regex_search 并手动将上限转换为下限.

Since there is no the magic like \L, we have to take a compromise - use regex_search and manually covert the uppers to lowers.

template<typename ChrT>
void RegexReplaceToLower(std::basic_string<ChrT>& s, const std::basic_regex<ChrT>& reg)
{
    using string = std::basic_string<ChrT>;
    using const_string_it = string::const_iterator;
    std::match_results<const_string_it> m;
    std::basic_stringstream<ChrT> ss;

    for (const_string_it searchBegin=s.begin(); std::regex_search(searchBegin, s.cend(), m, reg);)
    {
        for (int i = 0; i < m.length(); i++)
        {
            s[m.position() + i] += ('a' - 'A');
        }
        searchBegin += m.position() + m.length();
    }
}

void _replaceToLowerTest()
{
    string sOut = "I will NOT leave the U.S.";
    RegexReplaceToLower(sOut, regex("[A-Z]{2,}"));

    cout << sOut << endl;

}