c++ - 如何使用 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++ 中编写小写函数标记?
解决方案
由于没有类似 的魔法\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;
}
推荐阅读
- r - SEM:将 Mplus 语法转换为 lavaan 以进行模型规范
- linux - 当使用物理和逻辑内核的 diff no 时,在哪里可以找到英特尔处理器(比如 skylake)的 ipc(或 cpi)值?
- angular - 如何在关联的 spec.ts 文件中反映 Angular component.ts 更改
- vba - col变量名称中col的含义是什么?
- c# - 将一个值映射到多个值的最佳方法
- python - 使用 python selenium 单击 ng-click 按钮并上传文件
- android - 我想在textview中从右手边写到左手边
- python - 如何初始化列表对象的 Numpy 数组
- c++ - 如何使用 lz4 压缩有效载荷数据包 UDP?
- node.js - Node v12.7 如何实现原生brotli、gzip、deflate压缩缓冲区