C++ regex with char and wchar_t?(带有 char 和 wchar_t 的 C++ 正则表达式?)
问题描述
我有一个 const char 和一个 const wchar_t.我下面的函数适用于 char.编写可以轻松处理 char 和 wchar_t 的函数的最简单/最有效的方法是什么?
I have a const char and a const wchar_t. My function below works with the char. What's the simplest/most efficient way to write a function that can easily handle both char and wchar_t?
const char* asciiChar = "this is an ascii string";
const wchar_t* unicodeChar = L"this is a unicode string";
std::string replaceSubstring(const char* find, const char* asciiChar, const char* replace)
{
std::string const text(str);
std::regex const reg(find);
std::string const newStr = std::regex_replace(text, reg, replace);
return newStr;
}
推荐答案
正因如此,regex 是 basic_regex 的 typedef,很像 string 是 basic_string 的 typedef.知道了这一点,您就可以摆脱单一模板:
For this reason exactly, regex is a typedef of basic_regex<char>, much like string is a typedef of basic_string<char>. Knowing this, you can get away with a single template:
template<typename CharType>
std::basic_string<CharType>
replaceSubstring(const CharType* find, const CharType* str, const CharType* rep)
{
std::basic_string<CharType> text(str);
std::basic_regex<CharType> reg(find);
return std::regex_replace(text, reg, rep);
}
这会正确处理 char 指针和 wchar_t 指针,并返回正确类型的字符串.您可能也想接受 const std::basic_string<CharType>& 参数.
This correctly handles both char pointers and wchar_t pointers, and returns the correct type of string. You may want to accept const std::basic_string<CharType>& parameters instead, too.
这篇关于带有 char 和 wchar_t 的 C++ 正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:带有 char 和 wchar_t 的 C++ 正则表达式?
基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
