How can I access all matches of a re-capture group, and not just the last?

My code is:

#include <boost/regex.hpp>
boost::cmatch matches;
boost::regex_match("alpha beta", matches, boost::regex("([a-z])+"));
cout << "found: " << matches.size() << endl;

And he shows found: 2what it means that only one event is found ... How to instruct him to find THREE Entries? Thank!

+5
source share
3 answers

This is what I have found so far:

text = "alpha beta";
string::const_iterator begin = text.begin();
string::const_iterator end = text.end();
boost::match_results<string::const_iterator> what;
while (regex_search(begin, end, what, boost::regex("([a-z]+)"))) {
    cout << string(what[1].first, what[2].second-1);
    begin = what[0].second;
}

And it works as expected. Maybe someone knows a better solution?

+2
source

You should not call match.size () before checking that something has been matched, i.e. your code should look something like this:

#include <boost/regex.hpp>
boost::cmatch matches;
if (boost::regex_match("alpha beta", matches, boost::regex("([a-z])+")))
    cout << "found: " << matches.size() << endl;
else
    cout << "nothing found" << endl;

" ", regex_match . , , regex_search, . :

#include <boost/regex.hpp>
boost::cmatch matches;
if (boost::regex_search("alpha beta", matches, boost::regex("([a-z])+")))
    cout << "found: " << matches.size() << endl;
else
    cout << "nothing found" << endl;

"2", .. [0] "" [1] "a" ( - )

, ([a-z] +) regex_search, .

, 2 , - , , , , - ...

+2

, , - .

std::string arg = "alpha beta";
boost::sregex_iterator it{arg.begin(), arg.end(), boost::regex("([a-z])+")};
boost::sregex_iterator end;
for (; it != end; ++it) {
  std::cout << *it << std::endl;
}

alpha
beta
0

All Articles