命名空间
变体
操作

std::sub_match

来自 cppreference.cn
< cpp‎ | regex
定义于头文件 <regex>
template< class BidirIt >
class sub_match;
(自 C++11 起)

类模板 std::sub_match 被正则表达式引擎用于表示由标记的子表达式匹配的字符序列。 匹配是正则表达式匹配的目标范围内的 [beginend) 对,但带有额外的观察器函数以增强代码清晰度。

只有默认构造函数是公开可访问的。 std::sub_match 的实例通常在处理正则表达式算法之一期间,作为 std::match_results 容器的一部分构造和填充。

除非 matched 成员为 true,否则成员函数返回已定义的默认值。

std::sub_match 继承自 std::pair<BidirIt, BidirIt>,尽管它不能被视为 std::pair 对象,因为诸如赋值之类的成员函数将无法按预期工作。

内容

[编辑] 类型要求

-
BidirIt 必须满足 LegacyBidirectionalIterator 的要求。

[编辑] 特化

为常见的字符序列类型提供了几种特化

定义于头文件 <regex>
类型 定义
std::csub_match std::sub_match<const char*>
std::wcsub_match std::sub_match<const wchar_t*>
std::ssub_match std::sub_match<std::string::const_iterator>
std::wssub_match std::sub_match<std::wstring::const_iterator>

[编辑] 嵌套类型

类型 定义
iterator BidirIt
value_type std::iterator_traits<BidirIt>::value_type
difference_type std::iterator_traits<BidirIt>::difference_type
string_type std::basic_string<value_type>

[编辑] 数据成员

成员 描述
bool matched
此匹配是否成功
(公共成员对象)

继承自 std::pair

BidirIt first
匹配序列的开始
(公共成员对象)
BidirIt second
匹配序列的末尾之后
(公共成员对象)

[编辑] 成员函数

构造匹配对象
(公共成员函数) [编辑]
观察器
返回匹配的长度 (如果有)
(公共成员函数) [编辑]
转换为底层字符串类型
(公共成员函数) [编辑]
比较匹配的子序列 (如果有)
(公共成员函数) [编辑]
修改器
交换内容
(公共成员函数) [编辑]

[编辑] 非成员函数

(C++20 前移除)(C++20 前移除)(C++20 前移除)(C++20 前移除)(C++20 前移除)(C++20)
sub_match 与另一个 sub_match、字符串或字符进行比较
(函数模板) [编辑]
输出匹配的字符子序列
(函数模板) [编辑]

[编辑] 示例

#include <cassert>
#include <iostream>
#include <regex>
#include <string>
 
int main()
{
    std::string sentence{"Friday the thirteenth."};
    const std::regex re{"([A-z]+) ([a-z]+) ([a-z]+)"};
    std::smatch words;
    std::regex_search(sentence, words, re);
    std::cout << std::boolalpha;
    for (const auto& m : words)
    {
        assert(m.matched);
        std::cout << "m: [" << m << "], m.length(): " << m.length() << ", "
                     "*m.first: '" << *m.first << "', "
                     "*m.second: '" << *m.second << "'\n";
    }
}

输出

m: [Friday the thirteenth], m.length(): 21, *m.first: 'F', *m.second: '.'
m: [Friday], m.length(): 6, *m.first: 'F', *m.second: ' '
m: [the], m.length(): 3, *m.first: 't', *m.second: ' '
m: [thirteenth], m.length(): 10, *m.first: 't', *m.second: '.'

[编辑] 参见

迭代给定字符串中所有正则表达式匹配项内的指定子表达式或未匹配的子字符串
(类模板) [编辑]