emmtrix Regex-to-C Code Generator (emx-regex-cgen) compiles regular expressions into portable, static C code for embedded and performance-critical applications.
Key Characteristics
- Two backend engines — choose between a table-driven DFA and a
bit-parallel NFA (
--engine dfa,--engine bitnfa, or the default--engine autowhich tries DFA first and falls back to bitnfa when the DFA state limit is exceeded). - Table-driven DFA — every regex is compiled to a minimised deterministic finite automaton; the generated C code performs a single linear scan over the input.
- Bit-parallel NFA — the regex is compiled to a position NFA (a
Thompson NFA without ε-states) and simulated with precomputed bitmasks; the hot loop is fully unrolled
with no loops over words. The variant (
uint8,uint16,uint32, oruint32_t[N]) is selected automatically based on the number of NFA positions. - Code-point classes — in UTF-8 mode the DFA can read whole code
points instead of bytes (
unit, default"auto": whenever its tables are smaller). Code points that the pattern does not tell apart share a class, so\p{L}is one column instead of hundreds of UTF-8 byte states: the GPT-2 pre-tokenizer DFA shrinks from 277 KB to 6.5 KB, its scan DFA from 382 KB to 6.7 KB. - No dynamic memory allocation — all data is
static const; nomalloc, nofree. - Simple inner loop — the matching loop performs a single table
lookup per byte (DFA, branch-free unless
early_exitis set), per code point (DFA over code-point classes, plus the UTF-8 decoding and the class lookup) or one bit test per NFA position (bitnfa). - re2 feature set — supports the same subset of regular expressions
as Google's re2 library (no
back-references, no look-behind), plus look-ahead. With
syntax="oniguruma"patterns are read as Hugging Face tokenizers' Oniguruma reads them (see Oniguruma syntax). - Fullmatch semantics — the generated function checks whether the entire input matches the pattern.
- Scan mode — with
scan=True/--scanthe DFA instead finds matches in a text as a backtracking engine (Oniguruma, PCRE, Pythonre) does: the first alternative that matches, not the longest. This is how Hugging Face tokenizers split text with their pre-tokenizer regexes.
Installation
pip install emx-regex-cgen
The distribution name is emx-regex-cgen. The Python import path is
emx_regex_cgen.
After installation, you can use the package either as a CLI tool via
emx-regex-cgen or as a Python library via
from emx_regex_cgen import generate.
Quick Start
Python Library
generate() returns a GeneratedCode object with four parts.
Call .render() to get the combined C source string, or access individual
fields to embed them in an existing code-generation pipeline.
from emx_regex_cgen import generate
# generate() returns a GeneratedCode object
result = generate(r"\d{4}-\d{2}-\d{2}")
# .render() assembles the complete C source (same output as before)
print(result.render())
# Access individual parts:
result.includes # ['stddef.h', 'stdbool.h', 'stdint.h']
result.globals # static const transition table (and optional maps)
result.match_function # bool regex_match(const char *input, size_t len) { … }
result.main_function # int main(…) { … } — None when emit_main=False
# Include a main() for standalone testing
result = generate(r"[a-z]+", emit_main=True)
# Bytes mode: '.' matches any single byte, classes work on raw byte values
result = generate(r"[\x80-\xff]+", encoding="bytes")
# Use the bit-parallel NFA backend instead of DFA
result = generate(r"hello", engine="bitnfa")
# Scan mode: bool regex_find(input, len, from, &start, &end)
result = generate(r"\s+(?!\S)|\s+", scan=True, syntax="oniguruma")
Invalid or unsupported patterns raise emx_regex_cgen.PatternError, a
subclass of re.error; invalid option values raise ValueError.
from emx_regex_cgen import PatternError, generate
try:
generate(r"(?<=a)b")
except PatternError as exc:
print(exc) # look-behind is not supported at position 0
generate() options
generate(
pattern,
flags="",
*,
emit_main=False,
prefix="regex",
encoding="utf8",
engine="auto",
row_dedup="auto",
comb_compression="auto",
alphabet_compression="auto",
size_threshold=8192,
early_exit=False,
unicode_classes=False,
max_dfa_states=10000,
scan=False,
syntax="re2",
unit="auto",
)
Library arguments map directly to the generator settings:
| Argument | Type | Default | Meaning |
|---|---|---|---|
pattern |
str |
- | Regular expression to compile. |
flags |
str |
"" |
Regex flags: i (ignore case), s (dot-all), m (multiline). x is accepted and ignored; inline (?x) enables free-spacing syntax. |
emit_main |
bool |
False |
Include a standalone main() function in the generated C code. |
prefix |
str |
"regex" |
Prefix for generated C identifiers such as regex_match; must be a C identifier (ValueError otherwise). |
encoding |
str |
"utf8" |
"utf8" for Unicode-aware UTF-8 input, or "bytes" for raw byte semantics (as re2's Latin-1 mode: the i flag folds ASCII letters only). |
engine |
str |
"auto" |
Backend engine: "auto" (DFA first, bitnfa fallback), "dfa", or "bitnfa". |
unit |
str |
"auto" |
DFA only: what a transition reads, "byte" or "codepoint" (see Code-point unit); "auto" takes "codepoint" when its tables are smaller and the pattern allows it (with scan=True only when the byte table has more than size_threshold cells), unless alphabet_compression="yes" asks for the byte unit. "codepoint" raises ValueError with encoding="bytes", engine="bitnfa" or a pattern that matches ill-formed UTF-8 (\C); with it "auto" does not fall back to bitnfa. |
row_dedup |
str |
"auto" |
DFA only: "yes", "no", or "auto" (above size_threshold, when it saves at least 25 % of the table bytes: it costs ~70 % speed) for transition-row deduplication. |
comb_compression |
str |
"auto" |
DFA only: "yes", "no", or "auto" (above size_threshold, when it saves at least 25 % of the table bytes; in place of row deduplication) for comb compression of the transition rows (see Comb compression); "yes" with row_dedup="yes" raises ValueError. |
alphabet_compression |
str |
"auto" |
DFA, byte unit only: "yes", "no", or "auto" (when it makes the tables smaller) for byte equivalence-class compression; "yes" also makes unit="auto" take the byte unit. |
size_threshold |
int |
8192 |
DFA only: threshold (cells = states × columns) used by "auto" for row_dedup, comb_compression and, with scan=True, for unit. |
early_exit |
bool |
False |
DFA only: break out of the loop once the dead state is reached. |
unicode_classes |
bool |
False |
\d = Unicode Nd and \s = Unicode White_Space (also negated and inside classes), as in Hugging Face tokenizers; \w, \b and POSIX classes then raise PatternError. Requires encoding="utf8". |
max_dfa_states |
int |
10000 |
Limit for the subset construction; beyond it "auto" falls back to bitnfa and "dfa" raises DFAStateLimitExceeded. |
scan |
bool |
False |
Generate the search function <prefix>_find instead of <prefix>_match (see Scan mode). DFA only: "auto" does not fall back to bitnfa, "bitnfa" raises ValueError; it always stops early, so early_exit=True raises ValueError. |
syntax |
str |
"re2" |
Pattern syntax: "re2" or "oniguruma" (Hugging Face tokenizers, see Oniguruma syntax). "oniguruma" implies unicode_classes=True; flag m and encoding="bytes" raise ValueError. |
Example with multiple options:
from emx_regex_cgen import generate
result = generate(
r"[a-z]+\d+",
flags="i",
prefix="user_id",
emit_main=True,
engine="dfa",
encoding="utf8",
row_dedup="yes",
alphabet_compression="auto",
size_threshold=4096,
early_exit=True,
)
print(result.render())
CLI
# Write generated C code to stdout
emx-regex-cgen '[a-z]+\d+'
# Write to a file with a main() function
emx-regex-cgen '[a-z]+\d+' --emit-main -o matcher.c
# Compile and test
gcc -O2 -o matcher matcher.c
./matcher "hello42" # exit 0 (match)
./matcher "HELLO" # exit 1 (no match)
# Bytes mode: match any sequence of high bytes
emx-regex-cgen --encoding bytes '[\x80-\xff]+' --emit-main -o byte_matcher.c
# Use the bit-parallel NFA backend
emx-regex-cgen --engine bitnfa 'hello' --emit-main -o bitnfa_matcher.c
# Hugging Face tokenizer regex: \s is Unicode White_Space (e.g. U+00A0, U+3000)
emx-regex-cgen --unicode-classes ' ?[^\s\p{L}\p{N}]+' -o punct.c
# ... read exactly as tokenizers' Oniguruma reads it (^/$ match at lines)
emx-regex-cgen --syntax oniguruma --scan '^\s+|\p{L}+' -o pretok.c
# Scan mode: print every match as "start end" (byte offsets)
emx-regex-cgen --scan 'a|ab' --emit-main -o scanner.c
gcc -O2 -o scanner scanner.c
./scanner "abab" # 0 1 / 2 3: the first alternative wins
CLI Reference
usage: emx-regex-cgen [-h] [-o OUTPUT] [--emit-main] [--scan]
[--prefix PREFIX] [--syntax {re2,oniguruma}]
[--flags FLAGS] [--encoding {utf8,bytes}]
[--unicode-classes] [--max-dfa-states MAX_DFA_STATES]
[--unit {auto,byte,codepoint}]
[--row-dedup {auto,yes,no}]
[--comb-compression {auto,yes,no}]
[--alphabet-compression {auto,yes,no}]
[--size-threshold SIZE_THRESHOLD]
[--early-exit {yes,no}] [--engine {auto,dfa,bitnfa}]
pattern
Generate C code that performs a fullmatch (or, with --scan, a search) for a
regular expression.
positional arguments:
pattern Regular expression pattern
options:
-h, --help show this help message and exit
-o, --output OUTPUT Output file (default: stdout)
--emit-main Also emit a main() function (exit 0=match, 1=no match,
2=error; with --scan: print each match as 'start end')
--scan Generate <prefix>_find(), a search for the leftmost
match that a backtracking engine (e.g. Hugging Face
tokenizers) reports; DFA only
--prefix PREFIX Prefix for all generated C identifiers: arrays and
match function; must be a C identifier (default:
regex)
--syntax {re2,oniguruma}
Pattern syntax: re2 (default) or oniguruma (Hugging
Face tokenizers: ^/$ match at lines, (?m) is dot-all,
\h is a hex digit, ...; implies --unicode-classes)
--flags FLAGS Regex flags: i (case-insensitive), s (dot-all), m
(multiline); x is accepted and ignored (use inline
(?x) for free-spacing)
--encoding {utf8,bytes}
Input encoding: utf8 (default, Unicode-aware) or bytes
(raw byte semantics)
--unicode-classes Unicode \d (Nd) and \s (White_Space), as in Hugging
Face tokenizers; rejects \w, \b and POSIX classes
(utf8 only)
--max-dfa-states MAX_DFA_STATES
DFA state limit; beyond it engine auto falls back to
bitnfa and engine dfa fails (default: 10000)
--unit {auto,byte,codepoint}
What a DFA transition reads: byte, codepoint (decodes
UTF-8 and looks up the code point's class; rejects
ill-formed UTF-8), or auto (codepoint when its tables
are smaller, with --scan when the byte table also
exceeds --size-threshold, and --alphabet-compression
is not yes; default)
--row-dedup {auto,yes,no}
Transition-row deduplication: yes (always), no
(never), auto (when the table exceeds --size-threshold
and it saves at least 25 % of the table bytes;
default)
--comb-compression {auto,yes,no}
Comb compression of the transition rows (each row
keeps only the entries that differ from its most
frequent successor, the rows overlaid in one array):
yes (always; not with --row-dedup yes), no (never),
auto (when the table exceeds --size-threshold and it
saves at least 25 % of the table bytes; default)
--alphabet-compression {auto,yes,no}
Alphabet compression of the byte unit into equivalence
classes: yes (unless it needs 256 columns), no
(never), auto (when it makes the tables smaller;
default)
--size-threshold SIZE_THRESHOLD
Table-size threshold (cells = states × columns) for
--row-dedup auto, --comb-compression auto and, with
--scan, --unit auto (default: 8192)
--early-exit {yes,no}
Emit early-exit check inside the DFA loop: yes (break
when dead state is reached), no (always process full
input; default)
--engine {auto,dfa,bitnfa}
Backend engine: auto (try DFA first, fall back to
bitnfa; default), dfa (table-driven minimised DFA),
bitnfa (bit-parallel NFA)
Supported Features
Regex Features
Syntax and Semantics
The accepted syntax and the match semantics follow re2:
- Groups —
(…),(?:…),(?P<name>…)and(?<name>…)all group (a name is letters, digits and_, as in re2); captures do not exist in a fullmatch automaton. Lazy quantifiers (*?,+?, …) and theUflag ((?U):*is lazy,*?greedy) are accepted; for a fullmatch they match the same language as their greedy forms, in scan mode they prefer the shorter match. - Inline flags —
(?i),(?s),(?m),(?x)and(?i:…)/(?-i:…). A bare(?flags)applies until the end of the enclosing group, including later alternatives. Under(?x)blanks and#comments are ignored, also before a quantifier ((?x)a *isa*). - Anchors —
^/\Amatch at the start of the input,$/\zonly at its end (no "before a final\n" as in Python or PCRE). Withm,^and$also match after / before every\n.\b/\Bare ASCII word boundaries. Since the generated function performs a fullmatch, anchors matter where they sit inside the pattern, e.g.a(?m:$)\nb. - Character classes — ranges, escapes,
\p{…}/\P{…}and POSIX classes[[:alpha:]]/[[:^alpha:]](ASCII, inside a bracket expression only).\d,\sand\ware ASCII as in re2; withunicode_classes\dand\sfollow Unicode as in Hugging Face tokenizers (Oniguruma), while\w,\band POSIX classes are rejected because engines disagree on their Unicode meaning. - Unicode version —
\p{…}, Unicode\dand(?i)use Unicode 15.1, as re2 does, whatever the Python that runs the generator has. - Look-ahead —
(?=R)and(?!R)are supported (re2 rejects them), as used by Hugging Face tokenizers (\s+(?!\S)). The look-ahead only sees the input: at its end a pending(?!R)holds and a pending(?=R)fails, as in Python and PCRE. R may not contain anchors or further look-arounds. - Errors as in re2 — back-references, look-behind,
unknown escapes (
\h,\R,\Z, …: only ASCII punctuation may be escaped to stand for itself), reversed ranges ([z-a]),{m,n}with m > n and a counted repeat of a repeat (a*{2}) raisePatternError. - Repeat counts — unlike re2, counts above 1000 are accepted; the automaton size limits apply instead.
Oniguruma syntax
syntax="oniguruma" (--syntax oniguruma) reads a pattern the way
Hugging Face tokenizers do: their Regex is Oniguruma with Ruby syntax.
It differs from re2 in:
- Anchors —
^and$always match at lines:^at the start and after a\nthat does not end the input,$before every\nand at the end.\Zmatches at the end or before a final\n. - Flags — inline flags are
i,mandx, where(?m)is dot-all;(?s)and(?U)are errors. Of theflagsargument,i,s(dot-all) andxkeep their meaning andmraisesValueError. - Quantifiers —
x{n}?is an optionalx{n}(not a lazy{n}),x{n}+repeatsx{n},{,n}is{0,n}and a quantifier may follow another (a**,a{2}{3}). Possessive*+,++and?+never give back what they matched (a*+amatches nothing); they are supported on one character or class ([^\s\p{L}]++, also in a group:(\s)++), as a greedy repeat followed by a negative look-ahead (x*+isx*(?!x),x?+is(?:x|(?!x))), so not inside a look-ahead; on a longer group ((?:ab)*+) they raisePatternError. - Escapes —
\h/\Hare (non-)hex digits,\Nis any character but\nand\Oany character. Further character escapes are\e,\cX,\C-X,\o{…},\xNwith one digit and\uHHHH(exactly four digits).\xHHand octal escapes above 0x7F are bytes of the UTF-8 pattern:\xc3\xa9isé(use\x{…}for a code point). A byte from 0xF5 or a byte sequence that is no character (overlong, a surrogate) never matches; a continuation byte does not either in a class ([a\x80]isa) and is rejected outside one. A range of bytes ends at 0x7F ([\x00-\xff]is ASCII). Anchors and look-aheads cannot be repeated (^*).\p{…}property names ignore case, spaces,_and-(\p{lowercase letter}); the short form\pLis rejected. - Groups —
(?<name>…),(?'name'…)and comments(?#…)(\)does not end one);(?P<name>…)is an error. - Unicode version —
\p{…},\dand(?i)use Unicode 16.0, as the Oniguruma of tokenizers 0.23 does (\p{Garay},(?i)\x{1c89}matches U+1C8A).\p{LC}isLu,LlandLt. - Classes —
\d,\sfollow Unicode (as withunicode_classes), and so does\w: letters (Alphabetic), marks,NdandPc; a bare\w(not in a bracket class) also matches²³¹¼½¾, which Oniguruma's Latin-1 table counts as word characters. A nested class is a union ([a[xy]]),&&an intersection ([a-z&&[^aeiou]], an empty operand is the empty set), and a leading^negates the whole class;(?i)folds the whole class once, after its nested classes ((?i)[a[^x]]matchesX).\band POSIX classes are rejected, as are escapes Oniguruma reads as a plain letter (\y,\Q,\R,\K, …: these mean something else in other engines). - Case folding —
(?i)also uses multi-character folds:ßmatchesss,SSandẞ, andssmatchesß. A run of literals is cut into folds from the left and not regrouped, so(?i)sssmatchesßsbut notsß; a run ends at a capture group, a quantifier, an alternation or a flag change ((?i)(s)sdoes not matchß). A bracket class matches the folds of its members ((?i)[ß]matchesss) and the code points that share one ((?i)[ſt]matchesst), and complements a negated item before it folds it; a bare\p{…}is not folded ((?i)\p{Lu}does not matcha). A class with many such members ((?i)[\p{L}]) exceeds thebitnfaposition limit; the DFA engine is not affected.
Scan mode
generate(..., scan=True) (--scan) emits
bool regex_find(const char *input, size_t len, size_t from,
size_t *start, size_t *end);
It returns the leftmost match that starts at or after from and, of the
matches starting there, the one a backtracking engine (Oniguruma, PCRE,
Python re) reports: alternatives are tried in order, greedy repeats
take as much and lazy repeats as little as the rest of the pattern
allows, and a repeat whose iteration matched the empty string stops.
The DFA follows RE2's leftmost-first construction; a match whose
look-ahead is still undecided is confirmed later, so \s+(?!\S)
works. <prefix>_find tries each start position in turn (in UTF-8 mode
only character boundaries, so the input must be valid UTF-8: a stray
continuation byte never starts a match), so a search costs O(n²) in the
worst case, typically far less because the DFA stops as soon as the
match is decided.
- Anchors and look-ahead see the whole input, not just the text
after
from:^matches at position 0 (and after a\nwithmor in Oniguruma syntax),\blooks at the byte beforefrom. - Successive matches — call
<prefix>_findagain withfrom= the previous end. When it returns an empty match right at the previous end, skip that match and search again fromfrom+ 1, as Oniguruma, PCRE and Python do; themain()ofemit_maindoes this and prints every match asstart end(byte offsets). - Hugging Face tokenizers — compile
tokenizer.jsonregexes withsyntax="oniguruma"(and no flags). The pieces ofSplit(…, behavior="isolated")are the matches and the text between them; they are checked against thetokenizerslibrary for the pre-tokenizer regexes oftests/data/tokenizer_compat_results.json. - Limits — a look-ahead must be decided within 254 bytes after the
end of a match (
a(?=b*c)is rejected withValueError). A counted repeat{m,n}whose body can match the empty string may stop differently from Oniguruma, whose empty-iteration check depends on how it expands the repeat (e.g.(?:^.?){3}); the result is that of the Pythonregexmodule.
CLI Options
| Option | Effect | Golden reference |
|---|---|---|
--flags i |
Case-insensitive matching | flag_ignorecase.c · bitnfa |
--flags s |
Dot matches \n (dot-all) |
flag_dotall.c · bitnfa |
--flags m |
Multiline anchors | flag_multiline.c · bitnfa |
--flags x |
Accepted and ignored; free-spacing needs inline (?x) (as in the golden) |
flag_verbose.c · bitnfa |
--encoding bytes |
Raw byte semantics (no UTF-8) | encoding_bytes.c · bitnfa |
--prefix NAME |
Custom identifier prefix | prefix.c · bitnfa |
--emit-main |
Include standalone main() |
emit_main.c · bitnfa |
--unit byte |
DFA reads bytes (the default auto reads code points where that is smaller, as in unicode.c) |
unit_byte.c |
--alphabet-compression yes |
Byte equivalence-class compression (byte unit) | alphabet_compression.c |
--row-dedup yes |
Transition-row deduplication | row_dedup.c |
--comb-compression yes |
Comb compression of the transition rows | comb_compression.c |
--early-exit yes |
Break DFA loop on dead state (early exit) | early_exit.c |
--unicode-classes |
Unicode \d (Nd) and \s (White_Space) |
unicode_classes.c · bitnfa |
--max-dfa-states N |
DFA state limit (default 10000); auto falls back to bitnfa beyond it |
max_dfa_states.c |
--scan |
Leftmost-first search regex_find instead of a fullmatch (with --emit-main) |
scan.c · codepoint |
--syntax oniguruma |
Read the pattern as Hugging Face tokenizers' Oniguruma does | syntax_oniguruma.c |
Bit-NFA Variants
The bitnfa engine automatically selects the narrowest integer type
that can hold all NFA positions:
| Variant | NFA positions | Golden reference |
|---|---|---|
uint8_t |
≤ 8 | bitnfa_uint8.c |
uint16_t |
≤ 16 | bitnfa_uint16.c |
uint32_t |
≤ 32 | bitnfa_uint32.c |
uint32_t[N] |
> 32 | bitnfa_uint32_array.c |
Generated Code Structure
DFA Engine (default)
With the byte unit (unit="byte", or "auto" when it is smaller) the
generator produces:
- An optional alphabet map (
static const uint8_t regex_alphabet[256]) mapping each byte to its equivalence class (emitted when alphabet compression is active). - A transition table (
static const uint8_t regex_transitions[M][C]) mapping(row, column) → next_state. Dimensions depend on active optimisations: M is the number of unique rows (with row dedup) or states; C is the number of equivalence classes rounded up to a power of two (with alphabet compression) or 256. The power of two keeps the row address a shift: a multiply would make every byte ~16 % slower. With more than 128 classes the table stays at 256 columns. - An optional row map (
static const uint8_t regex_row_map[N]) mappingstate → row index(emitted when row deduplication is active). With comb compression the transition table and row map are replaced by the comb arrays (see Comb compression). - A match function with the signature:
bool regex_match(const char *input, size_t len);
- Optionally a
main()function for standalone executables.
Example Output (pattern hello, --alphabet-compression yes --row-dedup yes)
static const uint8_t regex_alphabet[256] = { /* byte → class */ };
static const uint8_t regex_transitions[6][8] = {
/* states 0, 6 */ { 0 },
/* state 1 */ { [2] = 2 },
...
};
static const uint8_t regex_row_map[7] = { 0, 1, 2, 3, 4, 5, 0 };
bool regex_match(const char *input, size_t len) {
uint8_t state = 1;
for (size_t i = 0; i < len; i++) {
state = regex_transitions[regex_row_map[state]][regex_alphabet[(unsigned char)input[i]]];
}
return state >= 6;
}
Comb compression
Most transition rows lead almost everywhere to one state (the dead state,
or the state a .* loops in). Comb compression keeps of each row only
the entries that differ from its default (its most frequent
successor) and overlays the rows in one array, each row shifted so that
its entries hit no other row's entries (first fit, the fullest rows
first):
static const uint8_t regex_comb_base[N]; /* row s starts at comb_base[s] */
static const uint8_t regex_comb_default[N]; /* omitted when all rows share one */
static const uint8_t regex_comb_next[L]; /* the successors */
static const uint8_t regex_comb_check[L]; /* the row that owns the slot (N: free) */
state = regex_comb_check[regex_comb_base[state] + c] == state
? regex_comb_next[regex_comb_base[state] + c] : regex_comb_default[state];
It applies to every table (byte unit with or without alphabet
compression, code-point unit, scan) and takes the place of row
deduplication. The lookup costs a dependent load and a compare more
(gcc emits a branch, which on a run in the dead state costs nothing;
while the state changes ~70 % speed, as row deduplication), so
"auto" applies it under the same rule: above size_threshold, when it
saves at least 25 % of the table bytes. On the suites it shrinks long
literal chains most (a DFA of 1447 states: 311 KB → 9 KB); over all
suite DFAs the code-point tables shrink from 1.29 MB to 0.75 MB, the
largest from 311 KB to 14 KB. The tokenizer DFAs, whose size is the
class map, hardly change. See
comb_compression.c.
Code-point unit
With unit="codepoint" (or "auto" when it is smaller) the DFA reads
whole code points. It is derived from the byte DFA: its states are the
byte DFA's states between two characters, and code points that lead every
such state to the same successor form one class. The generator produces:
- A class legend comment (up to four ranges per class).
- The class map:
regex_ascii_class[128](when the ASCII classes are not read from the leaf table) and one to three stagesregex_cp_stage1,regex_cp_stage2,regex_cp_class; equal blocks of a stage are stored once, and the block sizes are those that make the map smallest. Code points from the last class change on all share one class and are not stored. - The transition table
regex_transitions[M][C]with one column per class (rounded up to a power of two), and an optional row map as for bytes, or the comb arrays. - A match function that decodes UTF-8: ASCII takes its class from a table at once; a multi-byte character is decoded and checked, and ill-formed UTF-8 (a stray continuation byte, an overlong form, a surrogate, more than U+10FFFF, a truncated character) does not match. The byte unit rejects such input as well, so both units match the same strings.
The class lookup does not depend on the state, so it overlaps with the
transition chain: on mostly ASCII text the code-point unit is as fast as
the byte unit, on other text faster (one transition per character). See
unicode.c (\x{00e9}+; the byte unit:
unit_byte.c).
In scan mode the code-point DFA is derived from the scan DFA in the same
way. A look-ahead can confirm a match in the middle of a character (a(?![a-z])
is decided by the first byte of é); the code-point state records that
match, and its regex_match_back counts back from the start of the
character that led to it, so that characters of any length lead to the
same state. An ill-formed character ends the match attempt the way the
byte DFA ends it: it reads as byte 0xFF (regex_fail_back), which
decides the pending look-aheads, so both units report the same matches
on any input. A search decodes a character at every start position,
which on small tables costs up to ~60 % speed, so "auto" takes the
code-point unit only when the byte table has more than size_threshold
cells; on the large tokenizer DFAs it is ~8 % faster. See
scan_unit_codepoint.c.
Scan Mode (--scan)
The transition table is emitted as for the DFA engine (state 0 is the dead state), followed by
regex_match_back[N]— non-zero k when the state reached on a byte confirms a match that ends k bytes before the position after that byte (k = 1: right before the byte; more when a look-ahead was decided later). 0: no new match.regex_eoi_back[N]— non-zero k when, at the end of the input, the match ending k − 1 bytes before the end is the best one; there a pending(?!R)holds and a pending(?=R)fails.- An optional
regex_initial[257]— the start state by the byte before the start position (256: start of input), emitted when anchors or\bmake them differ. regex_match_at()(static) runs the DFA from one start position until the dead state, a terminal state (numbered last: only the dead state can follow, so its match is final) or the end; the last match it saw is the result.regex_find()tries the start positions fromfromon.- Optionally a
main()that prints every match ofargv[1].
See scan.c for the complete output for a|ab,
and Code-point unit for the scan over code points.
Bit-NFA Engine (--engine bitnfa)
The generator produces:
- One transition mask table per NFA position that needs one
(
static const uint8_t regex_trans_P[256]). Each entry is the bitmask of destination positions for the input byte. The integer width (uint8_t/uint16_t/uint32_t, oruint32_t[N]words beyond 32 positions) is chosen automatically. A position that moves on a single byte gets an inline comparison instead of a table. - A match function with a fully unrolled inner loop — one
if (state & bit) next |= …;per active position. - Optionally a
main()function for standalone executables.
Example Output (pattern h[ae]llo, --engine bitnfa)
static const uint8_t regex_trans_1[256] = { ['a'] = 0x04u, ['e'] = 0x04u };
bool regex_match(const char *input, size_t len) {
uint8_t state = 0x01u;
for (size_t i = 0; i < len; i++) {
unsigned char b = (unsigned char)input[i];
uint8_t next = 0;
if (state & 0x01u) next |= ((b == 'h') ? 0x02u : 0u);
if (state & 0x02u) next |= regex_trans_1[b];
if (state & 0x04u) next |= ((b == 'l') ? 0x08u : 0u);
if (state & 0x08u) next |= ((b == 'l') ? 0x10u : 0u);
if (state & 0x10u) next |= ((b == 'o') ? 0x20u : 0u);
state = next;
}
return (state & 0x20u) != 0;
}
Testing
pytest holds the unit, feature and golden tests; scan mode and
syntax="oniguruma" are checked against the pieces the tokenizers
library splits text into (tests/test_scan.py, tests/test_oniguruma.py).
The pattern corpora are not pytest cases.
tests/data/support_status.md lists, per
test provider, how many patterns are supported and why the others are not
(generated by tools/support_status.py; CI commits it in pull requests
and fails on main when it is stale):
| Provider | Patterns | Oracle |
|---|---|---|
| re2/PCRE2 | re2_compat_results.json: 2 500+ patterns of the PCRE2 test suite |
Google re2 |
| HF full match | tokenizer_compat_results.json: pre-tokenizer regexes of popular Hugging Face tokenizer.json files (unicode_classes=True) |
regex module |
| HF scan | tokenizer_scan_results.json: every tokenizer.json regex of the models in tests/data/parse_hf_tokenizers.py (syntax="oniguruma") |
tokenizers |
# Run all tests (parallel)
pytest -n auto -q
# Run linter
ruff check src/ tests/ tools/
# Regenerate the support report
python tools/support_status.py
Test Strategy
- Generate C code from the regex pattern.
- Compile with
gcc -Werror. - Execute the binary on each test subject.
- Compare the match result (or scan pieces) against the oracle's.
Development
# Clone
git clone --recurse-submodules https://github.com/emmtrix/emx-regex-cgen.git
cd emx-regex-cgen
# Install
pip install emx-regex-cgen
# Or, for local development
pip install -e ".[dev]"
# Test
pytest -n auto -q
# Lint
ruff check src/ tests/
License
MIT — Copyright (c) 2026 emmtrix Technologies GmbH
Maintained by
Metadata
Release files for emx-regex-cgen 0.3.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| emx_regex_cgen-0.3.0.tar.gz | 361.8 kB | With provenance | Details for emx_regex_cgen-0.3.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| emx_regex_cgen-0.3.0-py3-none-any.whl | Python 3 | none | any | Details for emx_regex_cgen-0.3.0-py3-none-any.whl |
Total release size: 501.3 kB
Release files / emx_regex_cgen-0.3.0.tar.gz
| Download URL | emx_regex_cgen-0.3.0.tar.gz |
|---|---|
| Size | 361.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
53a960ddc1b03b795cb1a6f9ffd7a32e34c83f1dfbb7737e7b00d240c51ddef5
|
|
BLAKE2b-256 checksum How to use checksums |
efd18729d558a16d3c5d0d2421fde538bfa83217d82557ea5b863b3c1e12b129
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 2, 2026.
Transparency logRelease files / emx_regex_cgen-0.3.0-py3-none-any.whl
| Download URL | emx_regex_cgen-0.3.0-py3-none-any.whl |
|---|---|
| Size | 139.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
9b71f61e9803ab28637869c3347e6c6ee2136dd908c3e6aecf35a54ff28cc74a
|
|
BLAKE2b-256 checksum How to use checksums |
712718f04d93dd90907802780244a3420fa82b308c957befe9b7997c55eb38ac
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 2, 2026.
Transparency logSecurity for emx-regex-cgen 0.3.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for emx_regex_cgen-0.3.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 2, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.