您可以使用regex_token_iterator。這裏的基本思想是:
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <regex>
using namespace std;
map<int, string> extract(const std::string & s)
{
map<int, string> m;
static const regex r("\\s*\\[(\\d+)\\]");
sregex_token_iterator tok(s.begin(), s.end(), r, { -1, 1 });
tok++; // Skip past the first end-of-sequence iterator.
for(sregex_token_iterator end; tok != end;)
{
int num = stoi(*tok, nullptr, 10);
if(++tok != end)
{
m.emplace(make_pair(num, *tok++));
}
}
return m;
}
int main()
{
auto m = extract("[05]some words here [13]some more words here [17]and so on");
for(auto & p : m) cout << p.first << ": '" << p.second << "'" << endl;
return 0;
}
這裏,這是搜索和提取模式\s*\[(\d+)\]\s*
,這意味着它將之前的方括號後降大任的空白,並創建一個匹配組至少匹配一個數字。
通過對迭代器使用{-1, 1}
,我們要求的迭代序列提供之前的比賽中的所有文本,然後通過匹配組1
輸出:
5: 'some words here'
13: 'some more words here'
17: 'and so on'
工作的例子是here
*字符數組通過每一個人物去...這將是低效*。爲什麼效率低下?! – CroCo