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 << ' ' << *it << endl;
}
};
};
const auto sri = [](auto r) {
return [&]() {
for (sregex_iterator it(s.begin(), s.end(), r), e; it != e; ++it) {
cout << ' ';
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
|
附上沙雕示意图一张