命名空间
变体
操作

std::regex_traits<CharT>::isctype

来自 cppreference.cn
< cpp‎ | regex‎ | regex_traits
 
 
 
正则表达式库
(C++11)
算法
迭代器
异常
特性
常量
(C++11)
正则表达式语法
 
 
bool isctype( CharT c, char_class_type f ) const;

判断字符 c 是否属于由 f 标识的字符类别,其中 flookup_classname() 返回的值,或者是多个此类值的位或结果。

标准库中 std::regex_traits 特化版本提供的此函数执行以下操作:

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

目录

[编辑] 参数

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

[编辑] 返回值

如果 cf 分类,则返回 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:] is [:alnum:] plus '_'
    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>
 
// This custom regex traits uses wctype/iswctype to implement 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"風の谷のナウシカ";
    // matches all characters (they are classified as alnum)
    std::regex_search(in, m, std::wregex(L"([[:alnum:]]+)"));
    std::wcout << "alnums: " << m[1] << '\n'; // prints "風の谷のナウシカ"
    // matches only the katakana
    std::regex_search(in, m,
                      std::basic_regex<wchar_t, wctype_traits>(L"([[:jkata:]]+)"));
    std::wcout << "katakana: " << m[1] << '\n'; // prints "ナウシカ"
}

输出

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

[编辑] 缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

缺陷报告 应用于 发布时的行为 正确的行为
LWG 2018 C++11 m 的值未指定 匹配 lookup_classname() 的最小支持

[编辑] 参阅

按名称获取字符类别
(public 成员函数) [编辑]
[virtual]
分类一个字符或一个字符序列
(std::ctype<CharT> 的虚保护成员函数) [编辑]
根据指定的 LC_CTYPE 类别对宽字符进行分类
(函数) [编辑]