17

If I have a simple regex pattern like "ab." and I have a string that has multiple matches like "abc abd". If I do the following...

boost::match_flag_type flags = boost::match_default;
boost::cmatch mcMatch;
boost::regex_search("abc abd", mcMatch, "ab.", flags)

Then mcMatch contains just the first "abc" result. How can I get all possible matches?

1 Answer 1

30

You can use the boost::sregex_token_iterator like in this short example:

#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;
}

The output from this program is:

abc
abd
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the quick reply. Question, what does *iter return, it doesn't appear to be a boost::cmatch in my quick test? I just gave a very simple example. In my regex I may have groups, so I need access to the group information for each match (as is available from cmatch)?
You could try out the regex_iterator instead, it returns a match_result when dereferenced, and should give you what you're looking for?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.