Reputation: 67
i want to extract all dash separated digits ( like this 232-65 ) from string in c++ using boost regex i use this pattern
\\d*-\\d*
but only first match is detected. what should i do to extract all matched pattern.
example input :
"2 1 5-25 37 42 43 53 69-119 123-514"
out put is only 5-25 but must be 5-25 69-119 123-514
my sample code is
cmatch res;
boost::regex port("\\d*-\\d*");
regex_search(s,res, port);
for (unsigned int i = 0; i < res.size(); ++i) {
cout << res[i] << endl;
}
Upvotes: 1
Views: 1726
Reputation: 111870
This is for C++11, but you should be able to replace the std::
with boost::
to make it work with Boost
std::string s = std::string("2 1 5-25 37 42 43 53 69-119 123-514");
std::regex port("\\d*-\\d*");
std::sregex_token_iterator iter(s.begin(), s.end(), port);
std::sregex_token_iterator end;
for(; iter != end; ++iter)
{
std::cout << iter->str() << std::endl;
}
Taken from Boost C++ regex - how to get multiple matches
If you want to use const char*
it should be:
const char *s = "2 1 5-25 37 42 43 53 69-119 123-514";
std::regex port("\\d*-\\d*");
std::cregex_token_iterator iter(s, s + strlen(s), port);
std::cregex_token_iterator end;
for(; iter != end; ++iter)
{
std::cout << iter->str() << std::endl;
}
Upvotes: 2
Reputation: 106116
You want to embed parenthesised "subexpressions" in your regular expression, which will be extracted in the matching process. Go read the boost page, searching for subexpression matches....
Upvotes: 0