Home > Article > Backend Development > Why does `std::match_results::size` return 1 instead of 3 for multiple matches in a regex search?
std::match_results::size
In C , std::match_results::size is a function that returns the number of matched groups plus the overall match in a regex search. It's important to note that it does not return the total number of matches found.
In the example you provided:
<code class="cpp">#include <iostream> #include <string> #include <regex> int main() { std::string haystack("abcdefabcghiabc"); std::regex needle("abc"); std::smatch matches; std::regex_search(haystack, matches, needle); std::cout << matches.size() << std::endl; }</code>
You expected matches.size() to return 3, but instead, you get 1. This is because regex_search returns only one match, and size() returns the number of capture groups plus the whole match value. In this case, there is no capture group, so the size is 1 (the whole match itself).
To get multiple matches, you can use std::regex_iterator, which is demonstrated in the following alternative code:
<code class="cpp">std::regex rgx1("abc"); int i = 0; smatch smtch; while (regex_search(str, smtch, rgx1)) { std::cout << i << ": " << smtch[0] << std::endl; i += 1; str = smtch.suffix().str(); }</code>
This code destroys the input string, so here is another alternative using std::sregex_iterator:
<code class="cpp">std::regex r("ab(c)"); std::string s = "abcdefabcghiabc"; for(std::sregex_iterator i = std::sregex_iterator(s.begin(), s.end(), r); i != std::sregex_iterator(); ++i) { std::smatch m = *i; std::cout << "Match value: " << m.str() << " at Position " << m.position() << '\n'; std::cout << " Capture: " << m[1].str() << " at Position " << m.position(1) << '\n'; }</code>
This iterator-based approach maintains the original string while allowing you to iterate through the matches.
The above is the detailed content of Why does `std::match_results::size` return 1 instead of 3 for multiple matches in a regex search?. For more information, please follow other related articles on the PHP Chinese website!