C++ Academy · Lesson

Capturing Groups

Extract matched parts.

Lesson 2 of 413 steps

Capturing Groups is a free C++ Academy lesson on CoddyKit. This is lesson 2 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the C++ Academy learning path, and your progress syncs across the web and the CoddyKit app. The C++ Academy course includes 4 lessons in total.

What Is a Capturing Group?

Parentheses in a pattern create a capturing group, remembering the part of the text they matched so you can extract it afterward.

  • (\\d+) captures a run of digits.
  • Results land in a std::smatch.
#include <iostream>
#include <regex>

int main() {
    std::regex p("(\\d+)");
    std::smatch m;
    std::string s = "order 42";
    if (std::regex_search(s, m, p)) {
        std::cout << "Captured: " << m[1] << '\n';
    }
    return 0;
}

The smatch Result

std::smatch stores the match results. Index [0] is the whole match, and [1], [2], ... are the capturing groups in order.

#include <iostream>
#include <regex>

int main() {
    std::regex p("(\\w+)@(\\w+)");
    std::smatch m;
    std::string s = "user@host";
    if (std::regex_search(s, m, p)) {
        std::cout << "Whole: " << m[0] << '\n';
        std::cout << "User: " << m[1] << ", Host: " << m[2] << '\n';
    }
    return 0;
}

Multiple Groups

You can capture several pieces at once, for example splitting a date into year, month, and day.

#include <iostream>
#include <regex>

int main() {
    std::regex p("(\\d{4})-(\\d{2})-(\\d{2})");
    std::smatch m;
    std::string s = "2026-05-30";
    if (std::regex_match(s, m, p)) {
        std::cout << "Y=" << m[1] << " M=" << m[2] << " D=" << m[3] << '\n';
    }
    return 0;
}

str(), position(), length()

Each group offers str() for its text, position() for its offset, and length() for its size within the input.

#include <iostream>
#include <regex>

int main() {
    std::regex p("(\\d+)");
    std::smatch m;
    std::string s = "abc 789 xyz";
    if (std::regex_search(s, m, p)) {
        std::cout << "str: " << m[1].str() << '\n';
        std::cout << "pos: " << m.position(1) << '\n';
        std::cout << "len: " << m.length(1) << '\n';
    }
    return 0;
}

Prefix and Suffix

The match object also exposes prefix() (text before the match) and suffix() (text after it).

#include <iostream>
#include <regex>

int main() {
    std::regex p("\\d+");
    std::smatch m;
    std::string s = "left 55 right";
    if (std::regex_search(s, m, p)) {
        std::cout << "prefix: [" << m.prefix() << "]\n";
        std::cout << "suffix: [" << m.suffix() << "]\n";
    }
    return 0;
}

Non-Capturing Groups

Use (?:...) to group without capturing. This keeps your numbered groups meaningful when you only need grouping for quantifiers or alternation.

#include <iostream>
#include <regex>

int main() {
    std::regex p("(?:Mr|Ms) (\\w+)");
    std::smatch m;
    std::string s = "Ms Smith";
    if (std::regex_search(s, m, p)) {
        std::cout << "Name: " << m[1] << '\n';
    }
    return 0;
}

Checking If a Group Matched

An optional group may not participate in a match. Test matched on the submatch to see whether it captured anything.

#include <iostream>
#include <regex>

int main() {
    std::regex p("file(\\.txt)?");
    std::smatch m;
    std::string s = "file";
    if (std::regex_match(s, m, p)) {
        std::cout << std::boolalpha << "ext matched: " << m[1].matched << '\n';
    }
    return 0;
}

Iterating Over All Matches

std::sregex_iterator walks through every match in a string, giving you each group along the way.

#include <iostream>
#include <regex>

int main() {
    std::regex p("(\\d+)");
    std::string s = "a1 b22 c333";
    auto begin = std::sregex_iterator(s.begin(), s.end(), p);
    auto end = std::sregex_iterator();
    for (auto it = begin; it != end; ++it) {
        std::cout << (*it)[1] << '\n';
    }
    return 0;
}

Counting Matches

Combine the iterator with std::distance to count how many times a pattern occurs.

#include <iostream>
#include <regex>

int main() {
    std::regex p("\\d+");
    std::string s = "1 22 333 4444";
    auto begin = std::sregex_iterator(s.begin(), s.end(), p);
    auto end = std::sregex_iterator();
    std::cout << "Count: " << std::distance(begin, end) << '\n';
    return 0;
}

Extracting Key-Value Pairs

Two groups per match let you parse simple structured text, like key=value tokens.

#include <iostream>
#include <regex>

int main() {
    std::regex p("(\\w+)=(\\w+)");
    std::string s = "a=1 b=2 c=3";
    auto begin = std::sregex_iterator(s.begin(), s.end(), p);
    auto end = std::sregex_iterator();
    for (auto it = begin; it != end; ++it) {
        std::cout << (*it)[1] << " -> " << (*it)[2] << '\n';
    }
    return 0;
}

Storing Captures

Copy a captured submatch into a std::string with str() so the data stays valid after the match object goes away.

#include <iostream>
#include <regex>
#include <string>

int main() {
    std::regex p("v(\\d+)");
    std::smatch m;
    std::string s = "version v7";
    std::string version;
    if (std::regex_search(s, m, p)) {
        version = m[1].str();
    }
    std::cout << "Stored: " << version << '\n';
    return 0;
}

Quick Check

Test your understanding of capture group indexing.

Recap

You learned how to extract data with capturing groups:

  • parentheses capture; (?:...) groups without capturing
  • smatch[0] is the whole match, [1]+ are groups
  • str(), position(), length(), prefix(), suffix()
  • sregex_iterator walks every match

Next, you will transform text using search and replace.

Free to start

Learn C++ with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
51
Lessons
203

Frequently Asked Questions

Is the “Capturing Groups” lesson free?

Yes — any 3 lessons of the C++ Academy learning path, including “Capturing Groups”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The C++ Academy course includes 4 lessons in total.

What will I learn in “Capturing Groups”?

Extract matched parts. You practise C++ Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C++ Academy?

No prior experience is required. C++ Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 2 of 4.

How long does the “Capturing Groups” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C++ Academy lesson?

Yes. Every C++ Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. regex Basics
  2. Capturing Groups
  3. Search and Replace
  4. Performance Notes
← Back to C++ Academy