How do I use std::regex_replace to replace string into lowercase?

风格不统一 提交于 2020-01-06 01:17:18

问题


I find this regex for replacement Regex replace uppercase with lowercase letters

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

My code

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

runs in Visual Studio 2017.

output:

\LA\LB\LC

How do I write the lowercase function mark in C++?


回答1:


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;

}


来源:https://stackoverflow.com/questions/53112726/how-do-i-use-stdregex-replace-to-replace-string-into-lowercase

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!