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
|
附上沙雕示意圖一張