Home > Backend Development > C++ > How Many Items Does std::match_results::size() Return in C ?

How Many Items Does std::match_results::size() Return in C ?

Patricia Arquette
Release: 2024-11-08 13:40:02
Original
586 people have browsed it

How Many Items Does std::match_results::size() Return in C  ?

What Does std::match_results::size() Return?

In C 11, the std::match_results::size() function returns the number of capture groups within a match result object plus one (the whole match value).

Consider the following code:

<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>
Copy after login

This code finds the first occurrence of the substring "abc" in the string "abcdefabcghiabc" and stores the match result in the matches object. Surprisingly, calling matches.size() returns 1 instead of 3 (the expected number of matches).

This behavior is explained by the fact that regex_search() only returns one match and size() includes both the full match and any capture groups. In this case, there are no capture groups, so size() returns 1 (full match only).

Finding Multiple Matches

To find and count multiple matches, use std::sregex_iterator or std::wsregex_iterator (for wide character strings). Here's an example using std::sregex_iterator:

<code class="cpp">#include <iostream>
#include <string>
#include <regex>
using namespace std;

int main() {
    std::regex r("abc");
    std::string s = "abcdefabcghiabc";
    int count = 0;
    for (std::sregex_iterator i = std::sregex_iterator(s.begin(), s.end(), r);
        i != std::sregex_iterator();
        ++i) {
        count++;
    }
    cout << "Number of matches: " << count << endl;
}</code>
Copy after login

This code iterates over all matches of "abc" in the string and counts them.

Capture Groups

If your regular expression contains capture groups (parenthesized subexpressions), the size of the match result will include the capture groups as well. For example, if you have a regular expression that matches "abc(def)" and the input string contains "abcdef," the size of the match result will be 2 (full match and capture group "def").

The above is the detailed content of How Many Items Does std::match_results::size() Return in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template