在Perl中,我可以这样做:
$text = '1747239';
@matches = ($text =~ m/(\d)/g);
# @matches now contains ('1', '7', '4', '7', '2', '3', '9')
Run Code Online (Sandbox Code Playgroud)
使用C++正则表达式匹配,复制此行为的最佳方法是什么,以便获得包含所有匹配项的匹配集?
我现在有这个: -
compiledRegex = std::regex(regex, std::tr1::regex_constants::extended);
regex_search(text, results, compiledRegex);
int count = results.size();
// Alloc pointer array based on count * sizeof(mystruct).
for ( std::cmatch::iterator match = results.begin();
match != results.end();
++match )
{
// Do something with match;
}
Run Code Online (Sandbox Code Playgroud)
然而,这只会给我第一场比赛,就像没有/ g的Perl一样好,但是我喜欢/ g效果.
那么,有没有一个好方法,或者我必须一遍又一遍地运行正则表达式?
你应该regex_search多次打电话.其返回值指定是否有更多匹配项.每次调用它都会得到一个新的匹配.结果返回的迭代器遍历正则表达式中定义的组子匹配.第一个条目始终是整个匹配,这就是为什么在你的情况下count == 1
std::string::const_iterator text_iter = text.cbegin();
compiledRegex = std::regex(regex, std::tr1::regex_constants::extended);
while (regex_search(text_iter, text.end(), results, compiledRegex))
{
int count = results.size();
// Alloc pointer array based on count * sizeof(mystruct).
for ( std::cmatch::iterator group = results.begin();
group != results.end();
++group )
{
// If you uses grouping in your search here you can access each group
}
std::cout << std::string(results[0].first, results[0].second) << endl;
text_iter = results[0].second;
}
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你