首页 > 解决方案 > 如何使用 std::regex_replace 将字符串替换为小写?

问题描述

我发现这个正则表达式替换正则表达式用小写字母替换大写

Find: (\w) Replace With: \L$1 

我的代码

string s = "ABC";
cout << std::regex_replace(s, std::regex("(\\w)"), "\\L$1") << endl;

在 Visual Studio 2017 中运行。

输出:

\LA\LB\LC

如何在 C++ 中编写小写函数标记?

标签: c++regexstd

解决方案


由于没有类似 的魔法\L,我们不得不妥协——使用 regex_search 并手动将上部转换为下部。

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;

}

推荐阅读