Boost C++正则表达式 - 如何获得多个匹配

Ron*_*Ron 15 c++ regex boost

如果我有一个简单的正则表达式模式,如"ab".我有一个像"abc abd"这样的多个匹配的字符串.如果我做以下......

boost::match_flag_type flags = boost::match_default;
boost::cmatch mcMatch;
boost::regex_search("abc abd", mcMatch, "ab.", flags)
Run Code Online (Sandbox Code Playgroud)

然后mcMatch只包含第一个"abc"结果.我怎样才能得到所有可能的比赛?

Jac*_*cob 28

你可以boost::sregex_token_iterator在这个简短的例子中使用类似的东西:

#include <boost/regex.hpp>
#include <iostream>
#include <string>

int main() {
    std::string text("abc abd");
    boost::regex regex("ab.");

    boost::sregex_token_iterator iter(text.begin(), text.end(), regex, 0);
    boost::sregex_token_iterator end;

    for( ; iter != end; ++iter ) {
        std::cout<<*iter<<'\n';
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

该程序的输出是:

abc
abd
Run Code Online (Sandbox Code Playgroud)