std::sub_match - cppreference.com
来自cppreference.com
template<class BidirIt> class sub_match; |
(C++11 起) | |
正则表达式引擎用类模板 std::sub_match 表示有标记子表达式所匹配的字符序列。
匹配是目标范围中匹配正则表达式的 [begin, end) 对,不过拥有附加的观察器函数以增进代码清晰度。
只有默认构造函数是可公开访问的。在处理正则表达式算法期间,std::sub_match 的实例作为 std::match_results 容器的一部分正常构造并移居。
成员函数返回定义的默认值,除非 matched 成员是 true。
std::sub_match 继承自 std::pair<BidirIt, BidirIt>,尽管它不能当做 std::pair 对象,因为成员函数,如赋值,不会有预计效果。
类型要求
特化
为常见字符类型提供数个特化:
在标头 | |
| 类型 | 定义 |
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>
|
数据成员
| 成员 | 描述 |
| 此匹配是否成功 (公开成员对象) |
继承自 std::pair
| 匹配序列的开始 (公开成员对象) | |
| 匹配序列的结尾后一位置 (公开成员对象) |
成员函数
| 构造匹配对象 (公开成员函数) [编辑] | |
观察器 | |
| 若存在则返回匹配的长度 (公开成员函数) [编辑] | |
| 转换为底层字符串类型 (公开成员函数) [编辑] | |
| 若存在则比较匹配的子序列 (公开成员函数) [编辑] | |
修改器 | |
| 交换内容 (公开成员函数) [编辑] | |
非成员函数
示例
#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: '.'