#regex
8 posts tagged #regex.
What compile-time regex costs, measured
Moving work to compile time moves the bill there too. Including the CTRE header costs about three quarters of a second, and each distinct pattern adds to that. The library also declines some PCRE syntax and reports it through an error message that names the offset while wrapping it in template noise.
One function that fills any struct from any pattern
A regex with N captures already describes a record with N fields, and C++26 reflection can enumerate a struct's fields. Joining them gives a parse_into<T, Pattern>() that fills any aggregate with no per-struct code, which builds and runs today on the reflection fork.
A lexer that is one pattern and no allocations
An alternation where each branch is a capture group doubles as a token table: whichever capture engaged names the token kind. Built on tokenize, unmatched input stops the scan instead of being skipped, which is what a lexer wants. The whole thing runs at compile time as readily as at run time.
Iterating matches, and a manual that has fallen behind
search_all, split and tokenize cover scanning, separating and lexing, and the difference between the first and the last one decides which you want. The documentation still teaches ctre::range, which the compiler now reports as deprecated, so this episode is written against the header.
Getting values out of a match
Numbered captures, named captures, and structured bindings that destructure a match directly. C++26 lets the binding itself be the condition, which removes the trailing test, though one compiler currently disagrees about that inside constant expressions.
Validating a string before the program exists
CTRE matches run inside constant expressions, so a regex can check and parse a string literal while the compiler is still working. A malformed version string then stops the build rather than surviving into production, and the parsed result is available as a constant.
The C++20 feature that gave CTRE its interface
Writing ctre::match<"[a-z]+"> requires a string literal to be a template argument, which C++20 allowed and every earlier standard did not. The older spelling still works and still compiles under C++17, so the two sit side by side and show exactly what the feature bought.
Measuring std::regex against a compile-time matcher
std::regex has a reputation, and reputations are worth checking. Measured at its most favourable, with the pattern compiled once outside the timed loop, it takes about seventy times longer per match than CTRE. Include the construction that real code usually pays for and the gap widens by another order of magnitude. Episode 1 of a series on compile-time regular expressions and the language features that make them possible.