如何使用 std::regex_replace 将字符串替换为小写? [英] How do I use std::regex_replace to replace string into lowercase?

查看:61
本文介绍了如何使用 std::regex_replace 将字符串替换为小写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

我的代码

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

在 Visual Studio 2017 中运行.

runs in Visual Studio 2017.

输出:

\LA\LB\LC

C++中小写的函数标记怎么写?

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

推荐答案

既然没有像 \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;

}

这篇关于如何使用 std::regex_replace 将字符串替换为小写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆