您可以使用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