Boost C++ regex - how to return all matches

2019-02-15 19:25发布

问题:

I have and string "SolutionAN ANANANA SolutionBN" I want to return all string which start with Solution and end with N.

While using regex boost::regex regex("Solu(.*)N"); I am getting output as SolutionAN ANANANA SolutionBN.

While I want to get out as SolutionAN and SolutionBN. I am new to regex in boost any help will be appreciated. Snippet if code I am using

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

int main(int ac,char* av[])
{
    std::string strTotal("SolutionAN ANANANA SolutionBN");
    boost::regex regex("Solu(.*)N");

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

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

回答1:

The problem is that * is greedy. Change to using the non-greedy version (note the ?):

int main(int ac,char* av[])
{
    std::string strTotal("SolutionAN ANANANA SolutionBN");
    boost::regex regex("Solu(.*?)N");

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

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


标签: c++ regex boost