Ga naar inhoud

Les 129 · Utilities

Regular Expressions

Learn C++ regular expressions with std::regex - regex_match vs regex_search, capture groups, iterating over matches, regex_replace, splitting text, and performance traps.

A regular expression (regex) is a small pattern language for text: "four digits, a dash, two digits", "a word that starts with #", "anything between square brackets". With one line of pattern you can validate input, pull fields out of log lines, find every price in a document or rewrite dates from one format to another. C++11 added regular expressions to the standard library in <regex>.

This lesson covers the three core operations (std::regex_match, std::regex_search, std::regex_replace), capture groups, iterating over all matches, splitting strings, and error handling. It also covers something many tutorials skip: std::regex is slow in every major implementation, so you'll learn how to use it without hurting performance and when to pick an alternative. The examples assume you know std::string and string_view.

A std::regex object holds a compiled pattern. By default it uses the ECMAScript grammar, the same flavor JavaScript uses, so \d is a digit, \w a word character, \s whitespace, + "one or more", * "zero or more", ? "optional", {2,4} "two to four times", [A-Z] a character class, ^ and $ anchors, and (...) a group.

Regex patterns are full of backslashes, and in a normal string literal each one has to be doubled ("\\d+"). Use a raw string literal instead: R"(\d+)". Everything between R"( and )" is taken literally.

The two test functions differ in one important way:

  • std::regex_match(text, re) succeeds only if the pattern matches the entire text. Use it for validation.
  • std::regex_search(text, re) succeeds if the pattern matches anywhere in the text. Use it for finding.

Expect the examples on this page to take several seconds longer to compile than usual: <regex> is one of the heaviest headers in the standard library, because it's a large template library instantiated in your program.

C++ regex_match versus regex_search

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

ABC-12345 fails regex_match because the fifth digit is left over, but regex_search finds ABC-1234 inside it. If you validate with regex_search, wrap the pattern in ^...$, or better, use regex_match, which makes the intent obvious.

The most useful pattern pieces at a glance:

Pattern Matches
. any character except a newline
\d \w \s digit, word character ([A-Za-z0-9_]), whitespace
\D \W \S the opposites
[abc] [^abc] [a-z] one of, none of, a range
* + ? {n,m} repetition: 0+, 1+, 0 or 1, exactly n, n to m
*? +? lazy versions: as few as possible
^ $ \b start, end, word boundary
(...) (?:...) capturing group, non-capturing group
`a b`
(?=...) (?!...) lookahead (lookbehind is not supported)
\1 backreference to group 1

Capture groups and match_results

Parentheses do more than group: each (...) captures the text it matched. Pass a std::smatch (match results for a std::string) to regex_match or regex_search, and it fills in:

  • m[0]: the whole match; m[1], m[2], ...: the groups, numbered by their opening parenthesis from left to right.
  • m[i].str() (or m.str(i)): the captured text as a std::string; m[i].matched is false for an optional group that didn't take part.
  • m.position(i) and m.length(i): where the group is in the text.
  • m.prefix() and m.suffix(): the text before and after the whole match.

There's also std::cmatch for const char* text, and std::wsmatch for wide strings.

C++ Pulling fields out of log lines

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

(?:\.(\d+))? uses a non-capturing group for the "dot and patch number" part, so it can be optional as a unit without adding an extra numbered group.

A std::smatch stores iterators into the string you searched, not copies. If that string is destroyed or modified, the match results dangle. That's why regex_search deliberately won't accept a temporary std::string together with an smatch (that overload is deleted): std::regex_search(get_line(), m, re) doesn't compile. Store the text in a variable first.

std::regex doesn't support named groups like (?<year>\d{4}) in its ECMAScript grammar, and it has no lookbehind. Number your groups and give the results descriptive variable names instead.

Finding every match

regex_search finds the first match. To visit all of them, use std::sregex_iterator: it repeatedly searches, starting after the previous match, and each element is an smatch. A default-constructed iterator marks the end, which also lets you count matches with std::distance.

For splitting, std::sregex_token_iterator is handier. Given submatch index -1, it yields the pieces between matches, so a separator pattern turns into a split function. Given a group number, it yields just that group from each match.

C++ Iterating over matches and splitting

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Replacing text with regex_replace

std::regex_replace(text, re, format) returns a new string with every match replaced by format. The format string can refer to the match:

  • $& is the whole match, $1 to $99 are groups, $` and $' are the text before and after it, and $$ is a literal dollar sign.
  • std::regex_constants::format_first_only replaces only the first match; format_no_copy drops the text that didn't match.

There's no callback version (unlike JavaScript's replace with a function). When each replacement needs computed text, loop with sregex_iterator and build the result yourself from prefix(), your replacement and the final suffix().

C++ Rewriting text with regex_replace

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The card example uses a lookahead (?=\d{4}): it requires four more digits to follow but doesn't consume them, so the last group stays visible.

Invalid patterns and validating input

A malformed pattern, such as an unclosed bracket, isn't caught at compile time. Constructing the std::regex throws std::regex_error at runtime, with a code() such as std::regex_constants::error_brack. Patterns written in your source code fail on the first run and get fixed; patterns that come from users (a search box, a config file) must be wrapped in try/catch.

The next example validates lines from the Input box. Notice that each pattern is compiled once, outside the loop.

C++ Validating user input

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Performance: the big caveat

std::regex is correct and convenient, but all three major implementations (GCC's libstdc++, Clang's libc++ and Microsoft's) are much slower than dedicated regex engines, often by 10 to 100 times. The interface was fixed in C++11 and can't be changed without breaking existing programs, so it's unlikely to get dramatically faster. Some rules keep it usable:

  • Compile once. Building a std::regex parses the pattern and builds a state machine, which is far more expensive than one match. Never construct it inside a loop or a frequently called function; make it a const local outside the loop, a member, or a static const local.
  • Prefer simple string functions when they're enough: starts_with, ends_with, contains (C++23), find, or std::from_chars for numbers are much faster than a regex.
  • Beware of long inputs. libstdc++'s matcher is recursive, and patterns like (a|b)* applied to very long strings (hundreds of kilobytes) can overflow the stack and crash.
  • Mind build times. <regex> adds seconds to every file that includes it. In a large project, keep it out of headers and use it in a few .cpp files.
  • Catastrophic backtracking affects backtracking engines everywhere: nested quantifiers such as (\w+)+$ can take exponential time on inputs that almost match. Keep patterns specific.
C++ Compiling a regex once versus every time

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Exact times vary from run to run, but the ranking doesn't: rebuilding the regex is by far the slowest, and the hand-written check beats both regex versions comfortably.

When regex matching is on a hot path, reach for a library:

  • CTRE (compile-time regular expressions) compiles the pattern during compilation, giving very fast matching with a similar interface.
  • RE2 (from Google) guarantees linear-time matching, which makes it safe for patterns from untrusted users.
  • PCRE2 and Boost.Regex are mature, fast and support more syntax, including named groups and lookbehind.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. What does std::regex_match("id: 42", std::regex{R"(\d+)"}) return?

    regex_match only succeeds if the entire text matches the pattern. regex_search would return true here.
  2. 2. For the pattern (\w+)@(\w+)\.com and the text [email protected], what is m[2] after a successful match?

    Groups are numbered by their opening parenthesis. m[0] is the whole match, m[1] is ana and m[2] is shop.
  3. 3. What does std::regex_replace("2026-10-17", std::regex{R"((\d+)-(\d+)-(\d+))"}, "$3/$2/$1") return?

    In the format string, $1, $2 and $3 refer to the captured groups, so they are inserted in reverse order.
  4. 4. A function validates thousands of strings and constructs its std::regex on every call. What is the best fix?

    Constructing a std::regex compiles the pattern, which is far more expensive than matching. Build it once and reuse it.
  5. 5. What happens when a std::regex is constructed from the pattern "[0-9"?

    Patterns are parsed at runtime, so syntax errors surface as std::regex_error with a code such as error_brack.

Summary

  • std::regex (ECMAScript syntax by default) compiles a pattern; write patterns as raw strings R"(...)".
  • regex_match checks the whole text (validation); regex_search finds a match anywhere.
  • Capture groups land in std::smatch: m[0] is the whole match, m[1]... the groups; prefix() and suffix() give the surroundings. Keep the searched string alive.
  • sregex_iterator visits every match; sregex_token_iterator with -1 splits text.
  • regex_replace rewrites matches with $1, $& and friends; computed replacements need a loop.
  • Bad patterns throw std::regex_error. std::regex is slow: compile once, prefer plain string functions when possible, and use CTRE, RE2 or PCRE2 for hot paths.

Next: Numeric Limits, Complex Numbers and Bit Manipulation, where you'll query the limits of numeric types and work with complex numbers and bits.

Volg je voortgang

Maak een gratis account om lessen af te vinken en op elk apparaat verder te gaan waar je gebleven was.