Capturing Groups
Extract matched parts.
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;
}All lessons in this course
- regex Basics
- Capturing Groups
- Search and Replace
- Performance Notes