Learn C++
#include "advanced/regex.hpp"

Regular Expressions with <regex> in C++

//concept

The <regex> library matches patterns against text with an ECMAScript grammar by default: std::regex_match checks whole strings, regex_search finds substrings, regex_replace rewrites, and sregex_token_iterator splits. Capture groups ((\d+)-(\d+)) extract structured pieces like dates and codes in a few lines.

Honest caveats: <regex> is famously slower than dedicated engines and its error messages are cryptic β€” syntax errors throw regex_error, so validate patterns in try/catch. For hot paths, hand-rolled parsing or RE2-style libraries win; for config validation and one-off extraction, <regex> is plenty.

//how it works
1

match vs search

regex_match demands the whole string fit the pattern; regex_search succeeds on any matching substring β€” pick by intent.

2

Groups capture pieces

Parenthesized groups land in std::smatch slots (m[1], m[2]) β€” structured extraction without manual slicing.

3

Replace and split

regex_replace rewrites matches ($1 back-references); sregex_token_iterator with -1 splits on delimiters.

4

Catch bad patterns

Invalid patterns throw std::regex_error at construction β€” build user-supplied patterns inside try/catch.

//example
#include <iostream>
#include <string>
#include <regex>
Β 
int main() {
std::string s = "order 42 ready";
std::regex num("[0-9]+");
std::smatch m;
if (std::regex_search(s, m, num)) {
std::cout << "found " << m[0] << std::endl;
}
return 0;
}
Output
found 42
1The pattern [0-9]+ describes one or more digits β€” compiled once into the regex object.
2regex_search scans the sentence and matches the 42 substring; m[0] holds the whole match.
3found 42 prints β€” extraction without a single manual index.
//use cases
Validating emails, phone numbers, and IDs at input boundaries
Extracting dates, codes, and numbers from logs and text
Search-and-replace across strings with capture-group references
Knowing when to graduate to hand parsers for hot paths

Recommended resourcesAffiliate links Β· may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice β€” pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from β€” great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself β€” building beats watching.