Namespaces
Variants

std::regex_traits<CharT>:: isctype

From cppreference.net
Regular expressions library
Classes
(C++11)
Algorithms
Iterators
Exceptions
Traits
Constants
(C++11)
Regex Grammar
bool isctype ( CharT c, char_class_type f ) const ;

确定字符 c 是否属于由 f 标识的字符类别,其中 f 是由 lookup_classname() 返回的值,或是多个此类值的按位或组合。

标准库中 std::regex_traits 特化版本提供的此函数实现如下:

1) 首先将 f 转换为类型为 std::ctype_base::mask 的值 m
对于 std::ctype 分类表中列出的每个类别(位于 lookup_classname() 页面),若 f 中对应分类的位被设置,则 m 中对应的位也将被设置。
2) 随后尝试通过调用 std:: use_facet < std:: ctype < CharT >> ( getloc ( ) ) . is ( m, c ) 来对当前注入的区域设置中的字符进行分类。
  • 若该调用返回 true ,则 isctype() 亦将返回 true
  • 否则,若 c 等于 '_' ,且 f 包含对字符类 [:w:] 调用 lookup_classname() 的结果,则返回 true ,否则返回 false

目录

参数

c - 待分类的字符
f - 通过一次或多次调用 lookup_classname() 获得的位掩码

返回值

c f 分类时返回 true ,否则返回 false

示例

#include <iostream>
#include <regex>
#include <string>
int main()
{
    std::regex_traits<char> t;
    std::string str_alnum = "alnum";
    auto a = t.lookup_classname(str_alnum.begin(), str_alnum.end());
    std::string str_w = "w"; // [:w:] 是 [:alnum:] 加上 '_'
    auto w = t.lookup_classname(str_w.begin(), str_w.end());
    std::cout << std::boolalpha
              << t.isctype('A', w) << ' ' << t.isctype('A', a) << '\n'
              << t.isctype('_', w) << ' ' << t.isctype('_', a) << '\n'
              << t.isctype(' ', w) << ' ' << t.isctype(' ', a) << '\n';
}

输出:

true true
true false
false false

演示了自定义正则表达式特性对 lookup_classname() / isctype() 的实现:

#include <cwctype>
#include <iostream>
#include <locale>
#include <regex>
// 此自定义正则表达式特性使用 wctype/iswctype 实现 lookup_classname/isctype
struct wctype_traits : std::regex_traits<wchar_t>
{
    using char_class_type = std::wctype_t;
    template<class It>
    char_class_type lookup_classname(It first, It last, bool = false) const
    {
        return std::wctype(std::string(first, last).c_str());
    }
    bool isctype(wchar_t c, char_class_type f) const
    {
        return std::iswctype(c, f);
    }
};
int main()
{
    std::locale::global(std::locale("ja_JP.utf8"));
    std::wcout.sync_with_stdio(false);
    std::wcout.imbue(std::locale());
    std::wsmatch m;
    std::wstring in = L"風の谷のナウシカ";
    // 匹配所有字符(它们被分类为字母数字)
    std::regex_search(in, m, std::wregex(L"([[:alnum:]]+)"));
    std::wcout << "alnums: " << m[1] << '\n'; // 输出 "風の谷のナウシカ"
    // 仅匹配片假名
    std::regex_search(in, m,
                      std::basic_regex<wchar_t, wctype_traits>(L"([[:jkata:]]+)"));
    std::wcout << "katakana: " << m[1] << '\n'; // 输出 "ナウシカ"
}

输出:

alnums: 風の谷のナウシカ
katakana: ナウシカ

缺陷报告

以下行为变更缺陷报告被追溯应用于先前发布的C++标准。

DR 适用范围 发布时的行为 正确行为
LWG 2018 C++11 m 的值未作规定 lookup_classname() 的最小支持要求保持一致

参见

通过名称获取字符类
(公开成员函数)
[virtual]
对字符或字符序列进行分类
( std::ctype<CharT> 的虚受保护成员函数)
根据指定的 LC_CTYPE 类别对宽字符进行分类
(函数)