O que faz
- Classes, âncoras, grupos nomeados, quantificadores gulosos e preguiçosos
- Propriedades Unicode (<code>\p{…}</code>) pelo módulo <code>text</code>
- Motores em camadas: literal AVX2/SSE2, pré-filtro, DFA preguiçoso, PikeVM
- A busca não aloca. A compilação tem um teto de memória exato
- <code>IsMatch</code>, <code>Find</code>, iterador, <code>Split</code>, <code>Replace</code>
- Uso em várias threads, com uma área de scratch por thread
Medido
- i7-6700, Release, GCC 15.2 / MSVC 19.51. Literal sobre 1 MB: 14,4 e 14,1 GB/s (meta de 10 GB/s)
- <code>(a+)+b</code> contra 100.000 letras <code>a</code>: 0,7 e 0,5 ms
- Compilação de um padrão típico: 1,2 a 3,1 µs e 2,1 a 5,2 µs (meta de 10 µs)
- Contra <code>std::regex</code>, 7 padrões sobre 2 MB: de 10x a 351x vs. libstdc++ em seis dos sete, de 1,3x a 42x vs. MSVC. Meta de 10x em todos não cumprida
- Compilação de um padrão: 1,0x a 2,2x a velocidade do <code>std::regex</code> no GCC, 0,2x a 0,7x no MSVC. Meta de ser 10x mais rápido não cumprida
Limites conhecidos
- Sem backreferences, lookaround, grupos atômicos ou recursão. A compilação rejeita cada um pelo nome
- A compilação não é 10x mais rápida que <code>std::regex</code> (1,0x a 2,2x no GCC, 0,2x a 0,7x no MSVC)
Ethereal::Regex · Tier 1
The module uses automata and never backtracking. The time of a search is linear in the size of the text, always: (a+)+b against one hundred thousand a takes less than a millisecond, where a backtracking engine would take centuries (and where libstdc++'s own std::regex, used here as the reference in the tests, got stuck for more than five minutes on a single generated pattern, see "How it was tested"). The price, stated up front: there are no backreferences, lookaround, atomic groups, possessive quantifiers, conditionals or recursion, and Compile rejects them by name and by the byte where they are.
#include <ethereal/cpp/regex/regex_inc.hpp>
namespace R = Ethereal::Regex;
R::CRegex Re;
R::SRegexError E;
if( R::CRegex::Compile( "(?<user>\\w+)@(?<host>[\\w.]+)", {}, &Re, &E ) != R::ERegexStatus::eOk )
std::printf( "%s at byte %zu\n", E.pMessage, E.uOffset ); // e.g.: "lookahead" at byte 3
bool b = Re.IsMatch( sText ); // the fastest: no groups
std::string_view aG[ 3 ];
R::SMatch M{ {}, aG };
if( Re.Find( sText, &M ) ) // aG[ 1 ] and aG[ 2 ]: views into the text
...
R::CMatchIterator It( Re, sText, aG ); // all of them, one by one, with the groups
while( It.Next( &M ) ) { ... }
char aOutput[ 256 ]; std::size_t n = 0;
Re.Replace( sText, "${host}:$1", aOutput, &n, true );Compile once, search many times. Compiling is the cold path: it allocates the program and the scratch area (with a ceiling, uMaxProgramBytes). Searching allocates nothing, not even once: the tests run every operation under ETL_EXPECT_NO_ALLOC, including the cache filling up and the PikeVM.
---
What there is, and the semantics
Literals, ., classes ([a-z], [^…], [[:alpha:]], \d \w \s and their negations), anchors (^ $ \A \z \b \B), alternation, groups ((…), (?:…), (?<name>…), (?P<name>…), (?'name'…)), quantifiers (* + ? {n} {n,} {n,m}, greedy and lazy), escapes (\t \n \r \f \v \a \e \xHH \x{HHHH}), inline options ((?i) (?m) (?s) (?x) (?U), (?i:…), (?-i)) and, with the Text module, \p{L}, \p{Greek}, \p{Script=Greek}, \p{gc=Nd}, \P{…} and Unicode case.
The semantics are those of RE2 and Perl: the leftmost match and, within it, the first alternative (greedy quantifiers try more first). There are three points where engines diverge. What was chosen in each:
- **
$without(?m)is only the end of the text** (as in RE2. In Perl it also matches before a final\n). - An empty iteration of a loop ends the loop, as in Perl, RE2 and libstdc++:
(|a)*on "aa" matches "". MSVC'sstd::regexfollows the letter of ECMAScript (the empty iteration beyond the minimum fails and forces backtracking) and gives a different result on these patterns. In the automata this needs an explicit rule: a thread that returns to a loop split already seen at the same position takes its exit there, instead of dying. The automaton, the PikeVM and the backtracker apply this rule, all three of them. - Empty matches in
FindAll,Split,Replaceand the iterator follow Rust: an empty match right at the end of the previous one does not count.a*on "baaa" gives "" and "aaa".Splitof "abc" by "" gives["", "a", "b", "c", ""].
The text and the pattern are UTF-8: . and the classes match a whole code point, and an invalid UTF-8 byte in the text matches none of them. Positions are in bytes. An invalid pattern is eInvalidUtf8.
ASCII mode (bAsciiOnly) treats everything as bytes, the pattern too: . matches one byte, \xHH is that byte, a non-ASCII character written in the pattern becomes its bytes one by one ([é] is "C3 or A9"), with no \p and no Unicode case. It is faster when there are captures with . (1.3 to 2×: the PikeVM and the backtracker have fewer instructions).
---
How it works
The pattern becomes a tree, and the tree becomes two programs over bytes (as in RE2): one forward and the reverse one, to find where the match starts. A class of code points is compiled into the UTF-8 sequences that match it, with shared suffixes. The engines never decode.
| Engine | When | What it does |
|---|---|---|
| Literal | the entire pattern is fixed text | substring search, AVX2 (64 starts at a time) or SSE2, with no automaton at all. The program does not even have a scratch area |
| Prefilter | every match starts with a fixed prefix | when stopped at the start, the automaton jumps to the next occurrence of the prefix |
| Accelerator | no prefix, but the possible first bytes are few (≤ 64) | when stopped at the start, it skips the bytes that cannot start anything |
| Lazy automaton | always | states are created as the text asks for them, in a cache of fixed size. A stored transition carries three flags in the top bits, and the fast loop is one read and one test per byte |
| Reverse automaton | the match has ended | read backward from the end, it gives the leftmost start |
| Bounded backtracking | groups were requested, and the map (instructions × bytes) fits in 64 Kbits | only over the already delimited span, each (instruction, position) pair visited once: linear |
| PikeVM | the backtracker does not fit, or the cache enters a cycle of flushes | all threads at once, with the captures. Linear, slower |
A full cache is flushed and the search continues. If it is flushed three times with fewer than 256 bytes between flushes (a pattern that generates states without end), the automaton gives up and the PikeVM does the search. The CacheRoundsGiveSameResult test checks that the result is exactly the same.
Threads. A CRegex can be shared across threads: searches use its scratch area, one at a time (a std::mutex). To search in parallel, each thread creates its own CRegexScratch (once) and passes it. A scratch area from another pattern is not used blindly: the search falls back to the internal one.
The iterator with a scratch area (2026-10-17, AI-01 stage 3). CMatchIterator( Re, sText, aG, Scratch ) walks the matches in the caller's scratch area, with no lock at all per match (the iterator without a scratch area locks the internal one for each match). Seek( uPos ) continues the iteration from uPos as if the previous match had ended there (an empty match right at uPos does not count): it serves whoever shortens a match before moving on, like the fallback of the AI-01 pre-tokenizers, which trims the last space of a run. The IteratorWithScratchAndSeek test checks the same result with and without a scratch area, a scratch area from another pattern, Seek with empty matches, and four threads on the same pattern. ZeroAllocationsWhileSearching covers both.
---
Memory
- **
ProgramSize()** is the program and its scratch area (without the automata cache), and it is exactly whatuMaxProgramByteslimits. The test compiles each pattern with the ceiling equal to itsProgramSize(passes) and with one byte less (eTooBig). What is allocated to compile is proportional to the pattern and to the ceiling. - The automata cache (
uDfaCacheBytes) is fixed and allocated at compile time, without being touched: the first search clears the table. The default is automatic: 1 KB per instruction, between 32 KB and 1 MB, which is amply enough for common patterns (tens of states). A pattern with thousands of states stays correct and linear, through the PikeVM. Giving it more cache restores the speed. - The scratch area is two allocations (the memory for the caches and one block with the rest), so that compiling is cheap on Windows as well.
---
Unicode (with the Text module)
\p{…}accepts the general categories (L,Lu,L&, the long names,gc=…) and the scripts (Greek,Grek,sc=…,Script=…). The first time a property appears, all of Unicode is walked (a few milliseconds). The ranges are kept per process, and the next\pcopies them.(?i)outside ASCII mode adds to each code point its simple case orbit (K,kand the Kelvin K,σ,ςandΣ), throughText::SimpleCaseOrbitNext: a rule over the simple mappings plus a table of 57 exceptions (456 bytes), which the generator checks for every code point.- Without Text,
\pand Unicode case areeNeedsText. Never a different semantics in silence. The(?i)of ASCII mode works without it.
---
Performance
Measured by ethereal_regex_measurements in Release, on an i7-6700 (3.4 GHz), best of three. GCC 15.2 on WSL, MSVC 19.51 on Windows.
| Measurement | GCC | MSVC | Spec target |
|---|---|---|---|
| literal, 1 MB (in cache) | 14.4 GB/s | 14.1 GB/s | > 10 GB/s ✅ |
literal, 32 MB (from memory, with the C library's memchr in parentheses) | 9.9 GB/s (16.9) | 10.8 GB/s (15.0) | no target |
log, error:\s+\d+ with the prefilter | 14.5 GB/s | 14.5 GB/s | "measured gain" ✅ |
| the same without prefilter | 297 MB/s | 525 MB/s | 49× and 28× |
[0-9]{3}-[0-9]{4} through the automaton (accelerator) | 12.1 to 13.7 GB/s | 10.1 GB/s | > 1 GB/s ✅ |
(\w+)@(\w+)\.com, all matches, with the groups | 209 to 214 MB/s | 199 MB/s | > 100 MB/s ✅ |
| compile a typical pattern | 1.2 to 3.1 µs | 2.1 to 5.2 µs | < 10 µs ✅ |
compile \p{L}+ (the whole class, 509 KB) | 0.3 ms | 0.25 to 0.82 ms | "bounded worst case" ✅ |
(a+)+b against 100,000 a | 0.7 ms | 0.5 ms | milliseconds ✅ |
captures with .: Unicode / ASCII (best of each) | 27 / 40 MB/s | 22 / 35 MB/s | ASCII faster ✅ |
| the same ratio, median of 15 interleaved pairs | 1.43 to 1.51× | 1.17 to 1.55× | the test requires > 1.1× |
**Against std::regex** (all matches of 7 patterns on a 2 MB text, half prose with addresses and half a log. std::regex runs on 512 KB, because it is slow, and the result is scaled. On both, best of three):
| Pattern | This (GCC) | libstdc++ | ratio | This (MSVC) | MSVC std::regex | ratio | |
|---|---|---|---|---|---|---|---|
exemplo (literal) | 5.5 to 6.1 GB/s | 58 MB/s | 94× to 102× | 3.6 GB/s | 2.4 GB/s | 1.5× | |
(\w+)@(\w+)\.com | 304 to 310 MB/s | 11 to 12 MB/s | 25× to 27× | 330 MB/s | 9.4 MB/s | 35× | |
error:\s+\d+ | 19.6 to 20.3 GB/s | 56 to 59 MB/s | 345× to 351× | 20.6 GB/s | 6.7 GB/s | 3× | |
\d{4}-\d{2}-\d{2} | 393 to 661 MB/s | 39 to 62 MB/s | 10× to 11× | 499 MB/s | 121 MB/s | 4× | |
[A-Z][a-z]+ing | 8.9 to 16.5 GB/s | 60 to 63 MB/s | 147× to 261× | 10.1 GB/s | 242 MB/s | 42× | |
| `(?:fox\ | dog) (\w+)` | 335 to 336 MB/s | 41 to 42 MB/s | 8× | 213 MB/s | 164 MB/s | 1.3× |
t[a-z]*out | 582 to 588 MB/s | 56 to 57 MB/s | 10× | 291 MB/s | 101 MB/s | 3× |
The 10× target is met against libstdc++ on six of the seven patterns and not met on (?:fox|dog) (\w+) (8×). **Against MSVC's std::regex it is met on two** (35× and 42×). On the patterns with a literal, MSVC's std::regex already scans the text at 2.4 to 6.7 GB/s, and 10× that would be 24 to 67 GB/s, above the cache bandwidth of this machine. On those patterns no engine reaches the target. Overall (the total time of the seven patterns, one against the other) the ratios are ~20× against libstdc++ and ~10× against MSVC, dominated by (\w+)@…, where std::regex is slowest. The test prints the worst ratio and the status of the target without requiring it, because the target is relative to a third-party library that changes from platform to platform.
**What is missing on (?:fox|dog) (\w+)** is the captures. With Unicode \w, bounded backtracking walks, at each character, the cascade of alternatives over byte ranges that \w compiles into (~23 ns per byte). Closing that gap would require a "byte table" instruction (one byte → the next instruction) in the compiler, which changes all four engines. That was not done.
What changed to get here (batch 3, second pass. Before: 0.6× to 26× against MSVC):
- The automaton loop went from ~3.6 ns per byte to ~1.9. Two causes, measured one at a time. The state and the position were passed by reference to two lambdas, and the compiler kept them in memory on every byte. And the index of each transition was
state + 3 + class, a three-termlea(3 cycles on Skylake) in the dependency chain. The loop is now a separate function, and a transition already stores the start of the next state's table (state + 3). - The accelerator is judged by what it saves. Skipping to the next byte that can start a match cost more than it saved when the text is full of those bytes (
\win prose:(\w+)@(\w+)\.comran at 178 MB/s). After 256 skips, if they saved fewer than 8 bytes on average, the scratch area stops skipping (only the speed changes, never the result). With up to 3 byte ranges, the candidate search is done with SSE2, 16 bytes at a time. - The candidate search. When the pattern does not match empty and has a set of first bytes (or a fixed prefix), every match starts at a candidate. The automaton runs anchored from each one, in order, and the first one that matches is the leftmost match, without the reverse automaton. A second-byte filter discards most false candidates without running the automaton. Linear time is guaranteed by a budget: if the failed runs reread more than 4 times what was advanced (
a\w*bover "aaaa…"), the scratch area switches to the unanchored automaton plus the reverse one, for good. - A literal no longer takes any lock: its search does not use the shared scratch area, and each match was paying for a
std::mutexfor nothing.
**Compiling against std::regex** (the spec asks for 10× here too): 1.0× to 2.2× on GCC (and 0.3× on (?i)hello|world), 0.2× to 0.7× on MSVC. Not met. std::regex compiles into a backtracking automaton and nothing else. This one compiles two programs, does the accelerator analysis (first bytes, ranges, second byte) and allocates the scratch areas, so that searching neither allocates nor backtracks. 10× would require compiling in 0.1 to 0.5 µs, which does not fit that work. The absolute target (< 10 µs) is met on both.
Compilation has an arena (2026-09-28). The same pattern compiled in 3.0 µs on GCC and in 7.5 to 9.7 µs on MSVC, close to the target. The difference was in the allocations: one compilation made 29 to 68 ([a-z]+ and (\w+)@(\w+)\.com, counted), spread across the vectors of the tree and the compiler, and on Windows each allocation with its release costs several times more than on glibc (and MSVC's vector grows 1.5× at a time, against 2× on GCC). Now the tree and the compiler's work live in a std::pmr::monotonic_buffer_resource over 16 KB on the stack of Compile, and only what stays in the program goes to the normal allocator: 8 to 10 allocations per compilation, and the worst typical pattern on MSVC went from 7.5 to 9.7 µs down to 5.2 µs. On GCC it barely changes. A large pattern (\p{L}+) overflows from the stack to new, as before. Before that, a quadratic cost that the second-byte filter had brought in was removed (one closure per start instruction, and Unicode \w has hundreds).
Timing tests on Windows. On this machine, with the browser and the resident antivirus programs, there are bursts of +30 to +45% lasting hundreds of milliseconds, and the same pattern measures from 20 to 37 MB/s from one run to the next. That is why regex.measurements spreads the rounds over time: compilation measures one round of each pattern at a time, the literal is measured at three moments, and the ASCII/Unicode ratio is the median of the ratios of 15 pairs, each pair back to back. The limit for that ratio went down from 1.2× to 1.1× (the spec asks for "measurably faster", with no number): with 1.2×, MSVC failed 4 runs in 30 because of the machine. With this: 0 in 30.
---
C layer
Header ethereal/c/regex/regex.h (source src/c/regex/regex.cpp), 14 ETLC_Regex* functions. Compiling a pattern with options (a handle the library allocates and ETLC_RegexDestroy releases), the compile error with the status, the rejected construct (ETLC_RegexConstructName) and the pattern byte, IsMatch, Find from a given byte and FullMatch with the groups in a caller array (positions in bytes, ETLC_REGEX_NPOS for a group that did not participate), FindAll and Split (the count comes back even when the array is short), Replace into a buffer, and the group count, the index by name and the program size. Texts and patterns go as pointer and size, so they can contain the zero byte.
Left out is the per-thread search scratch area (CRegexScratch): a handle can already be used by several threads, one search at a time, and whoever wants parallelism creates one handle per thread. Also left out is CMatchIterator, which ETLC_RegexFind with the start byte replaces.
Tests regex.cabi.c11 and regex.cabi.c17 (tests/regex_c_abi.c): the rejections with the byte of each construct, the groups and the absent group, the empty match rule, splitting, replacement with groups by number and by name and the short buffer, and \p{Greek} and case folding when Text is built.
---
How it was tested
| Test | What |
|---|---|
regex.basic | the syntax, the semantics case by case, UTF-8 and ASCII mode, each rejected construct by name and by byte, syntax errors, the memory ceiling (exact to the byte), FindAll/Split/Replace/iterator with empty matches, per-thread scratch areas and five threads on the same pattern, zero allocations, the cache in a cycle of flushes against the roomy cache, and linear time (the ReDoS corpus, with the ratio between 20 K and 80 K) |
regex.differential | against std::regex (ECMAScript): 9,000 patterns from a grammar, 16 texts each, in three configurations (Unicode, ASCII and minimal cache, where the PikeVM does everything), the match and the groups outside quantifiers, and FullMatch against regex_match |
regex.unicode | \p{…}, \P{…} and [\p{…}] against the UCD at every code point (29 categories, the 7 groups, L&, 15 scripts, the alternate names), and (?i)\p{Lu} over the whole orbit |
regex.fuzz | patterns from random bytes and from a grammar, valid and invalid UTF-8 text: IsMatch = Find, the match inside the text and the groups inside it, the minimal cache = the roomy one, FindAll = the iterator = Split − 1, and Replace("$0") returns the text |
regex.measurements | the performance targets (above) |
The differential test found three real defects, and all three were the same idea: an empty iteration of a loop has to end it with the priority it has.
- The first, in the test suite: the empty iteration died at the already visited split, and the exit was left for after all the branches of the body. It led to the loop split rule.
- The other two came from a campaign outside the test suite (13 seeds × 6,000 patterns):
- seed 44: with a group in the body, the empty iteration died before the split, at the end of the group.
- seed 111: the same, with an assertion (
\B) at the end of the body.
The rule now applies to the tail of the body (guards, jumps and assertions, the latter checked again). All three stayed as tests, and seeds 44 and 111 now give 0 differences.
Nine seeds did not finish. In all of them, the trace (ETL_REGEX_TRACE, formerly ETL_REGEX_RASTO, still accepted) shows libstdc++'s std::regex stuck on a generated pattern (the exponential backtracking this module exists to escape), after this engine had already answered the same pattern.
After the second pass (the candidate search changes the path of almost every search), a new campaign, outside the test suite: 16 seeds × 1,500 patterns (3,000 with case folding), 144,000 comparisons each. 13 seeds finished with 0 differences. The other 3 (37, 43, 53) ran over the time limit, and the trace of 37 ends, once again, in the stuck std::regex (ref-search) after this engine's answer. The test suite (regex.basic, regex.differential, regex.fuzz, regex.unicode) passes on GCC, on MSVC and under ASan+UBSan.
The two references disagree with each other in one case, and the test says which: a quantifier whose body matches empty. libstdc++ does as Perl and RE2 do (and as this one does), and everything is compared. MSVC's std::regex follows the letter of ECMAScript, and those patterns (651 + 320 of the 9,000) are skipped there, and counted.
---
Status against the spec (section 6)
| Criterion | Status | ||
|---|---|---|---|
| Linear time | ✅ (a+)+b against 100,000 a: 0.5 to 0.7 ms, with the test requiring the limit | ||
| The ReDoS corpus | ✅ 12 classic patterns, 20 K and 80 K: all linear (and the test requires it) | ||
| Allocations | ✅ zero in search, with ETL_EXPECT_NO_ALLOC (the cache filling up and the PikeVM included) | ||
| Literal path | ✅ 14.6 to 15.5 GB/s, and with no automaton (the program does not even have a scratch area) | ||
| Prefilter | ✅ 25 to 26× on a log | ||
| Simple pattern | ✅ 2.1 to 3.4 GB/s | ||
| With captures | ✅ 108 to 122 MB/s | ||
10× std::regex | ⚠️ against libstdc++: 10× to 351× on six of the seven patterns, 8× on `(?:fox\ | dog) (\w+)`. Against MSVC: 1.3× to 42×, and unreachable on the patterns with a literal (its engine already scans at 2.4 to 6.7 GB/s). Overall (total time), ~20× and ~10×. See "Performance" | |
| Compile < 10 µs | ✅ 1.2 to 3.1 µs on GCC, 2.1 to 5.2 µs on MSVC (with the compilation arena, see "Performance"). 10× std::regex when compiling: ❌ (1.0× to 2.2× on GCC, 0.2× to 0.7× on MSVC) | ||
| Correctness | ✅ the differential test, fixed seed, three configurations, 0 differences | ||
| Cache in a cycle of flushes | ✅ the PikeVM continues with the same results, verified with `(a\ | b)*a(a\ | b){12}` |
| Rejected constructs | ✅ by name and by byte, each one | ||
| Memory ceiling | ✅ compilation fails, exact to the byte. What is allocated to compile is proportional to the pattern and to the ceiling | ||
| Unicode | ✅ against the UCD at every code point. ASCII mode faster with captures (paired median 1.43 to 1.51× on GCC, 1.17 to 1.55× on MSVC) | ||
| Fuzzing | ✅ clean (grammar and bytes), 3 seeds × 30,000 with ASan and UBSan (seeds 4, 5 and 6, each a different stream. Until 2026-09-27 the driver did `seed \ | 1`, and seeds 4 and 5 gave the same campaign. It was fixed with a mixer, and all three ran again) | |
| Sanitizers | ✅ ASan and UBSan clean on all Regex tests |
---
Deviations from the spec
- The types:
std::string_view,std::span< char >+std::size_t * pWritten,ERegexStatus, as in the rest of the batches.FindAllreturns the views of the whole matches (std::span< std::string_view >). The groups of each one come throughCMatchIterator. - **"Consumes
IAllocator"**: it does not. Compiling uses the globalnew(and only compiling). Searching allocates nothing, so there is nothing to inject on the hot path. - There is no:
constexprcompilation of literals, RE2's one-pass engine (see "Performance") or the optional backtracking engine (ETL_REGEX_BACKTRACKING, which the spec lists as optional). Whoever needs backreferences needs another tool, and finds that out throughCompile. - **Ethereal's
CMutexis not used here.** Measured while writing this module: with the Bundle license guard compiled in (USING_BUNDLE_CHECK), aLock+Unlockcost ~21.6 µs, against ~10 ns forstd::recursive_mutex. In a 25 ns search that was everything. Regex usesstd::mutex, as do Telemetry, Scheduler and Storage. (Since 2026-09-28, by the owner's decision,CMutexlocks no longer go through the guard:Lock+Unlockcosts ~7 ns. Regex stays onstd::mutex, which does not need the recursive depth ofCMutex.)