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

查看:23
本文介绍了带有 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;
    }

推荐答案

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

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