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

问题描述 投票:0回答:2

我找到这个正则表达式用于替换正则表达式用小写字母替换大写字母

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++ regex std
2个回答
1
投票

由于没有像

\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;

}

0
投票

正如 @halfelf 在他们的评论中提到的,你可以使用 boost。但您不需要使用回调。只需将

std::
替换为
boost::
即可使用您在问题中给出的语法。

即,做

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

给予

abc
© www.soinside.com 2019 - 2024. All rights reserved.