I am not sure if I completely understand what is returned by std::match_results::size. According to cppreference it "Returns the number of submatches".
I am probably misinterpreting this description. In my opinion that function is returning results for first occurrence, not for complete string. matches[0] is a complete match, matches[1] is submatch and matches[2] is rest of the string.
#include <iostream>
#include <string>
#include <regex>
int main ()
{
std::string s ("this subject has a submarine as a subsequence called subaru");
std::smatch matches;
std::regex pattern ("\\b(sub)([^ ]*)"); // matches words beginning by "sub"
std::cout << "Target sequence: " << s << std::endl;
std::cout << "Regular expression: /\\b(sub)([^ ]*)/" << std::endl;
std::cout << "The following matches and submatches were found:" << std::endl;
std::regex_search (s, matches, pattern);
std::cout << "size: " << matches.size() << "\n";
std::cout << "Results: \n";
while (std::regex_search (s, matches, pattern)) {
std::cout << matches[0] << " " << matches[1] << " " << matches[2] << "\n"; // match, submatch, rest
s = matches.suffix().str();
}
return 0;
}
based on: https://en.cppreference.com/w/cpp/regex/regex_search
http://www.cplusplus.com/reference/regex/regex_search/?kw=regex_search
demo: http://coliru.stacked-crooked.com/a/056462e884896604
Description suggests that in case of mentioned string call to size() should return number 4. (since there are four "subs" in sentence) In practice size() returns matches and submatches, but only to first occurrence. Is this function wrongly documented or I misunderstood how it works?
Aucun commentaire:
Enregistrer un commentaire