0Pricing
C++ Academy · Lesson

regex Basics

Match patterns in text.

What Is <regex>?

The <regex> header lets you match text against regular expressions patterns that describe sets of strings. You build a pattern, then test or search text with it.

  • std::regex holds a compiled pattern.
  • Matching functions report whether text fits.
#include <iostream>
#include <regex>

int main() {
    std::regex pattern("hello");
    std::cout << std::boolalpha << std::regex_match("hello", pattern) << '\n';
    return 0;
}

regex_match vs regex_search

regex_match requires the entire string to match. regex_search succeeds if the pattern appears anywhere in the string.

#include <iostream>
#include <regex>

int main() {
    std::regex p("cat");
    std::string s = "the cat sat";
    std::cout << std::boolalpha;
    std::cout << "match: " << std::regex_match(s, p) << '\n';
    std::cout << "search: " << std::regex_search(s, p) << '\n';
    return 0;
}

All lessons in this course

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