命名空间
变体
操作

std::regex_traits<CharT>::value

来自 cppreference.cn
< cpp‎ | regex‎ | regex traits
 
 
 
正则表达式库
(C++11)
算法
迭代器
异常
特性
常量
(C++11)
正则表达式语法
 
 
int value( CharT ch, int radix ) const;
(since C++11)

确定在当前使用的区域设置中,数字基数 radix 中由数字 ch 表示的值。当 std::regex 处理量词(如 {1} 或 {2,5})、反向引用(如 \1)以及十六进制和 Unicode 字符转义时,会调用此函数。

[编辑] 参数

ch - 可能表示数字的字符
radix - 8、10 或 16

[编辑] 返回值

如果 ch 确实表示当前使用的区域设置中对于数字基数 radix 有效的数字,则返回数值;否则,如果出错,则返回 -1。

[编辑] 示例

#include <iostream>
#include <locale>
#include <map>
#include <regex>
 
// This custom regex traits allows japanese numerals
struct jnum_traits : std::regex_traits<wchar_t>
{   
    static std::map<wchar_t, int> data;
    int value(wchar_t ch, int radix) const
    {
        wchar_t up = std::toupper(ch, getloc());
        return data.count(up) ? data[up] : regex_traits::value(ch, radix);
    }
};
std::map<wchar_t, int> jnum_traits::data = {{L'〇',0}, {L'一',1}, {L'二',2},
                                            {L'三',3}, {L'四',4}, {L'五',5},
                                            {L'六',6}, {L'七',7}, {L'八',8},
                                            {L'九',9}, {L'A',10}, {L'B',11},
                                            {L'C',12}, {L'D',13}, {L'E',14},
                                            {L'F',15}};
 
int main()
{   
    std::locale::global(std::locale("ja_JP.utf8"));
    std::wcout.sync_with_stdio(false);
    std::wcout.imbue(std::locale());
 
    std::wstring in = L"風";
 
    if (std::regex_match(in, std::wregex(L"\\u98a8")))
        std::wcout << "\\u98a8 matched " << in << '\n';
 
    if (std::regex_match(in, std::basic_regex<wchar_t, jnum_traits>(L"\\u九八a八")))
        std::wcout << L"\\u九八a八 with custom traits matched " << in << '\n';
}

输出

\u98a8 matched 風
\u九八a八 with custom traits matched 風