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

时间:2010-06-26 01:17:45

标签: 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)

然后mcMatch只包含第一个“abc”结果。我怎样才能获得所有可能的匹配?

1 个答案:

答案 0 :(得分: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;
}

该程序的输出是:

abc
abd