Regular Expressions with <regex> in C++
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.
match vs search
regex_match demands the whole string fit the pattern; regex_search succeeds on any matching substring β pick by intent.
Groups capture pieces
Parenthesized groups land in std::smatch slots (m[1], m[2]) β structured extraction without manual slicing.
Replace and split
regex_replace rewrites matches ($1 back-references); sregex_token_iterator with -1 splits on delimiters.
Catch bad patterns
Invalid patterns throw std::regex_error at construction β build user-supplied patterns inside try/catch.
#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;}Recommended resourcesAffiliate links Β· may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself β building beats watching.