使用char和wchar_t的C ++正则表达式? [英] C++ regex with char and wchar_t?

查看:752
本文介绍了使用char和wchar_t的C ++正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个const char和一个const 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;
    }


推荐答案

code> regex 是 basic_regex< char> 的typedef,很像 string basic_string< char> 的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 ++正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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