Reputation: 309
In regex engines that I'm familiar with, it's possible to return every instance of a matching substring. E.g. the following Perl code gives the output shown:
my $data = "one two three four";
my @result = ($data =~ /(\w+)/g);
say "@result";
output:
one two three four
So all four matches are returned, when the "g" modifier is used. If I try to do the same thing using std::regex_search, only the first match is returned. I.e.:
std::string srchStr = "one two three four";
std::regex r("(\\w+)");
std::smatch m;
if (regex_search(srchStr, m, r)) {
std::cout << "m.size()=" << m.size() << std::endl;
for (const std::string &s : m) {
std::cout << s << std::endl;
}
}
output:
m.size()=2
one
one
Is there something like the g operator in perl that will cause it to return all the matches? Thanks
Upvotes: -1
Views: 404
Reputation: 29955
You use std::sregex_iterator:
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string const s{"one two three four"};
std::regex const r{"(\\w+)"};
for (std::sregex_iterator it{s.begin(), s.end(), r}, end{}; it != end;
++it) {
std::cout << it->str() << '\n';
}
}
Upvotes: 0