C++11 REGEX MATCH ALL 获取全部匹配
C++11 REGEX MATCH ALL 获取全部匹配
C++11 Regex
处理规模较小,较为复杂的字符串逻辑时可能会用到。
经过了很多比较,我认为 regex_token_iterator 是相对简单的。
有两个选择 sregex_token_iterator 和 sregex_iterator
概念区分
- regex_token_iterator
- regex_iterator
- sregex_token_iterator
- sregex_token_iterator
- cregex_token_iterator
- cregex_iterator
看了下面这个一般就明白了
1
2
3
4
5
6
7
8
|
/** @brief Token iterator for C-style NULL-terminated strings. */
typedef regex_token_iterator<const char*> cregex_token_iterator;
/** @brief Token iterator for standard strings. */
typedef regex_token_iterator<string::const_iterator> sregex_token_iterator;
typedef regex_iterator<const char*> cregex_iterator;
typedef regex_iterator<string::const_iterator> sregex_iterator;
|
regex_token_iterator 是一个模板类
sregex_token_iterator 和 cregex_token_iterator 分别是对应的标准C++字符串和C字符串版本regex_iterator 同理
关于 regex_token_iterator 和 regex_iterator 的区别
网上的博客说的有些让人摸不着头脑,我简单说一下我的看法。
regex_token_iterator 相当于 将 regex_iterator 中的第 i 列(或数组集合)单独抽取的版本。(捕获组)
当第四个参数为-1时,表明该迭代器不会匹配所有捕捉组内的内容。
代码示例
下面的代码使用了regex, C++ Raw string literal, currying, range-for . 均需要至少 C++11
!!此代码有诸多不严谨之处(悬挂引用等),仅供演示
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
#include <iostream>
#include <regex>
using namespace std;
const string s = "uvw 123 122wdf7442";
const regex r(R"(\d+)"), // integer
block(R"(.*)"), // block
mixed(R"((?:\d)([a-z]))"), // char after a digit
multi(R"((\d)(\d)(\d))"); // three sequential digit
const auto srti = [](auto r) {
return [&]() {
for (sregex_token_iterator it(s.begin(), s.end(), r), e; it != e;
++it) {
cout << '\t' << *it << endl;
}
};
};
const auto sri = [](auto r) {
return [&]() {
for (sregex_iterator it(s.begin(), s.end(), r), e; it != e; ++it) {
cout << '\t';
for (auto z : *it) {
cout << z << ' ';
}
cout << endl;
}
};
};
const auto se = [](auto msg, auto e) {
cout << msg << endl;
e();
};
const auto test = [](auto e) {
return [&]() {
se("> int", e(r));
se("> block", e(block));
se("> mixed", e(mixed));
se("> nulti", e(multi));
};
};
int main() {
se("------SREGEX TOKEN ITERATOR-------", test(srti));
se("---------SREGEX ITERATOR----------", test(sri));
return 0;
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
------SREGEX TOKEN ITERATOR-------
> int
123
122
7442
> block
uvw 123 122wdf7442
> mixed
2w
> nulti
123
122
744
---------SREGEX ITERATOR----------
> int
123
122
7442
> block
uvw 123 122wdf7442
> mixed
2w w
> nulti
123 1 2 3
122 1 2 2
744 7 4 4
|
附上沙雕示意图一张
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?