Skip to main content

emmtrix Regex-to-C Code Generator (emx-regex-cgen) compiles regular expressions into portable, static C code for embedded and performance-critical applications.

CI License: MIT

Key Characteristics

  • Two backend engines — choose between a table-driven DFA and a bit-parallel NFA (--engine dfa, --engine bitnfa, or the default --engine auto which 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, or uint32_t[N]) is selected automatically based on the number of NFA positions.
  • Code-point classes — in UTF-8 mode the DFA and the bit-parallel NFA 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 (one NFA position) 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, its bit-parallel NFA from 878 positions (over the limit of 256) to 26.
  • No dynamic memory allocation — all data is static const; no malloc, no free.
  • Simple inner loop — the matching loop performs a single table lookup per byte (DFA, branch-free unless early_exit is 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 / --scan the DFA instead finds matches in a text as a backtracking engine (Oniguruma, PCRE, Python re) 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" What a DFA transition or a bitnfa step reads, "byte" or "codepoint" (see Code-point unit and bitnfa over code-point classes); "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" or a pattern that matches ill-formed UTF-8 (\C).
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 (or beyond the NFA's limit) unit "auto" (unless alphabet_compression="yes") and "codepoint" build the DFA over code-point classes in UTF-8 mode (see Code-point classes), then engine="auto" falls back to bitnfa and "dfa" raises DFAStateLimitExceeded; other size limits raise SizeLimitExceeded, its base class.
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 unit auto and codepoint
                        (utf8) build the DFA over code-point classes, then
                        engine auto falls back to bitnfa and engine dfa fails
                        (default: 10000)
  --unit {auto,byte,codepoint}
                        What a DFA transition or bitnfa step 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

Feature Example pattern DFA bitnfa
Literal string hello literal.c literal_bitnfa.c
Character class [a-z0-9_]+ char_class.c char_class_bitnfa.c
Negated class [^aeiou]+ negated_class.c negated_class_bitnfa.c
Dot (any char except \n) .+ dot.c dot_bitnfa.c
Alternation cat|dog|fish alternation.c alternation_bitnfa.c
Star quantifier * ab*c quantifier_star.c quantifier_star_bitnfa.c
Plus quantifier + ab+c quantifier_plus.c quantifier_plus_bitnfa.c
Optional quantifier ? colou?r quantifier_optional.c quantifier_optional_bitnfa.c
Bounded repeat {m,n} a{2,4} quantifier_repeat.c quantifier_repeat_bitnfa.c
Digit escape \d \d{4}-\d{2}-\d{2} escape_digit.c escape_digit_bitnfa.c
Word escape \w \w+ escape_word.c escape_word_bitnfa.c
Space escape \s \s+ escape_space.c escape_space_bitnfa.c
Unicode / UTF-8 \x{00e9}+ unicode.c unicode_bitnfa.c
Anchors ^ / $ ^start.*end$ anchors.c anchors_bitnfa.c
Word boundary \b / \B \bword\b word_boundary.c word_boundary_bitnfa.c
Unicode property \p{…} / \P{…} \p{Nd}+ unicode_property.c unicode_property_bitnfa.c
Look-ahead (?=…) / (?!…) [a-z]+(?!ing)\w* lookahead.c lookahead_bitnfa.c

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 the U flag ((?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 * is a*).
  • Anchors — ^ / \A match at the start of the input, $ / \z only at its end (no "before a final \n" as in Python or PCRE). With m, ^ and $ also match after / before every \n. \b / \B are 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, \s and \w are ASCII as in re2; with unicode_classes \d and \s follow Unicode as in Hugging Face tokenizers (Oniguruma), while \w, \b and POSIX classes are rejected because engines disagree on their Unicode meaning.
  • Unicode version — \p{…}, Unicode \d and (?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 contain further look-aheads and end anchors ((?=(?:\d{3})*(?!\d)), (?=a\z)), not ^, \A or \b, which would need the character before the look-ahead (Oniguruma's \b and look-behinds may: the look-ahead is compiled per kind of character before it).
  • 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}) raise PatternError.
  • 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 \n that does not end the input, $ before every \n and at the end. \Z matches at the end or before a final \n. \G matches where the search started: in scan mode at the first position <prefix>_find tries, for a whole match at its start (scan_search_start.c); it is not supported inside a look-ahead.
  • Flags — inline flags are i, m and x, where (?m) is dot-all; (?s) and (?U) are errors. Of the flags argument, i, s (dot-all) and x keep their meaning and m raises ValueError.
  • Quantifiers — x{n}? is an optional x{n} (not a lazy {n}), x{n}+ repeats x{n}, {,n} is {0,n} and a quantifier may follow another (a**, a{2}{3}). Possessive *+, ++ and ?+ never give back what they matched (a*+a matches 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*+ is x*(?!x), x?+ is (?:x|(?!x))); on a longer group ((?:ab)*+) they raise PatternError.
  • Escapes — \h / \H are (non-)hex digits, \N is any character but \n and \O any character. Further character escapes are \e, \cX, \C-X, \o{…}, \xN with one digit and \uHHHH (exactly four digits). \xHH and octal escapes above 0x7F are bytes of the UTF-8 pattern: \xc3\xa9 is é (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] is a) 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 \pL is rejected.
  • Groups — (?<name>…), (?'name'…) and comments (?#…) (\) does not end one); (?P<name>…) is an error.
  • Unicode version — \p{…}, \d and (?i) use Unicode 16.0, as the Oniguruma of tokenizers 0.23 does (\p{Garay}, (?i)\x{1c89} matches U+1C8A). \p{LC} is Lu, Ll and Lt.
  • Classes — \d, \s follow Unicode (as with unicode_classes), and so does \w: letters (Alphabetic), marks, Nd and Pc; 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]] matches X). POSIX classes are rejected, as are escapes Oniguruma reads as a plain letter (\y, \Q, \R, \K, …: these mean something else in other engines).
  • Word boundaries — \b / \B lie between a character of a bare \w and one that is not (or the edge of the input). The NFA knows whether the character before a position is a word character; the one after it is checked with the look-ahead (?=\w). A search decodes the character before its start (scan_word_boundary.c). The bitnfa engine exceeds its position limit with them, as with \w.
  • Look-behind — (?<=X) / (?<!X) of one character or class X ((?<=\w), (?<![\d.,])) or of an anchor ((?<!^); (?<!\b) is \B); before the input there is no character. Longer bodies and alternatives ((?<=ab), (?<=a|b)) raise PatternError. As for \b, the NFA knows which look-behind classes the character before a position lies in (at most 6 classes per pattern), and a search decodes the character before its start (scan_lookbehind.c).
  • Atomic groups — (?>X) never gives back what X matched. It is supported where that needs no backtracking control: when all matches of X have the same number of characters it is (?:X) ((?>\p{Nd}{3}), (?>ab|cd)); a greedy repeat of one character or class takes all it can, as a possessive one ((?>x*) is x*+, (?>x{1,3}) is (?:x{3}|x{1,2}(?!x))); a lazy repeat of a group of one length stops after its minimum ((?>x{2,5}?) is x{2}; with minimum 0 any group matches the empty string). Others ((?>a|ab), (?>(?:ab)*), and under (?i) literals and bracket classes, which may fold to several characters) raise PatternError (syntax_atomic.c).
  • Back-references — \1 to \9 are supported after their group when it matches one of at most 64 characters, as a literal, a bracket class of literals and ranges or an alternation of them (([.!?])\1*, (a|b)\1), not under (?i): (C)R becomes the alternation of cR' over the characters c of C, where R' is R with \1 replaced by c. A back-reference before or inside its group, in another alternative or outside a repeat of it (\1(a), (a)|\1, (?:(a)|b)\1) and one to a longer group ((\w+)\1) raise PatternError, as do \n without group n and numbered back-references next to named groups, as in Oniguruma, and groups that expand to more than 4096 alternatives together. \1 followed by a digit is not a back-reference (syntax_backref.c).
  • Case folding — (?i) also uses multi-character folds: ß matches ss, SS and ẞ, and ss matches ß. A run of literals is cut into folds from the left and not regrouped, so (?i)sss matches ßs but not sß; a run ends at a capture group, a quantifier, an alternation or a flag change ((?i)(s)s does not match ß). A bracket class matches the folds of its members ((?i)[ß] matches ss) and the code points that share one ((?i)[ſt] matches st), and complements a negated item before it folds it; a bare \p{…} is not folded ((?i)\p{Lu} does not match a). A class with many such members ((?i)[\p{L}]) exceeds the bitnfa position limit over UTF-8 bytes; over code-point classes it is one position.

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. A look-ahead that can stay undecided for more than 254 bytes (\d{1,3}(?=(?:\d{3})*(?!\d)), up to the end of a run of digits), or whose tracking exceeds the DFA state limit, is instead evaluated where it is entered, by running its own DFA over the input that follows, as a backtracking engine does (scan_lookahead_checked.c). <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 \n with m or in Oniguruma syntax), \b and look-behinds look at the character before from. Only Oniguruma's \G depends on from: it holds at the first position tried (from, or the next character boundary after it).
  • Successive matches — call <prefix>_find again with from = the previous end. When it returns an empty match right at the previous end, skip that match and search again from from + 1, as Oniguruma, PCRE and Python do; the main() of emit_main does this and prints every match as start end (byte offsets).
  • Hugging Face tokenizers — compile tokenizer.json regexes with syntax="oniguruma" (and no flags). The pieces of Split(…, behavior="isolated") are the matches and the text between them; they are checked against the tokenizers library for the pre-tokenizer regexes of tests/data/tokenizer_compat_results.json.
  • Limits — at most 6 look-aheads evaluated that way may be entered at one position; each evaluation can read up to the end of the input, so with such look-aheads a search costs O(n³) in the worst case (e.g. (?:a(?=a*b))+ on a long run of a). 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 Python regex module.

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); beyond it the DFA is built over code-point classes, then auto falls back to bitnfa max_dfa_states.c · code-point classes
--scan Leftmost-first search regex_find instead of a fullmatch (with --emit-main) scan.c · codepoint · checked look-ahead · code-point classes · word boundary · look-behind · \G
--syntax oniguruma Read the pattern as Hugging Face tokenizers' Oniguruma does syntax_oniguruma.c · atomic group · back-reference

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

Over UTF-8 bytes or over code-point classes (unit, see Over code-point classes): bitnfa_unit_byte.c · bitnfa_codepoint_classes.c.

Generated Code Structure

DFA Engine (default)

With the byte unit (unit="byte", or "auto" when it is smaller) the generator produces:

  1. An optional alphabet map (static const uint8_t regex_alphabet[256]) mapping each byte to its equivalence class (emitted when alphabet compression is active).
  2. 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.
  3. An optional row map (static const uint8_t regex_row_map[N]) mapping state → 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).
  4. A match function with the signature:
    bool regex_match(const char *input, size_t len);
    
  5. 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:

  1. A class legend comment (up to four ranges per class).
  2. The class map: regex_ascii_class[128] (when the ASCII classes are not read from the leaf table) and one to three stages regex_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.
  3. 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.
  4. 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.

Code-point classes

Over UTF-8 bytes a large class costs a state for every byte position of its characters: \p{Nd}{510} is a chain of 510 tries of byte ranges, 37 000 NFA states. When the byte construction exceeds a size limit (the NFA's, max_dfa_states, or that of a look-ahead's DFA), unit "auto" and "codepoint" build the automaton over code-point classes instead: the character sets of the pattern cut the code points into atoms, every set is a union of atoms, and an atom is one symbol of the NFA, so \p{Nd}{510} takes 1020 states. The subset construction, the scan DFA and the look-aheads run unchanged on these symbols, which keep the context of the bytes they replace ("\n" and the ASCII word characters are atoms of their own) for the anchors and \b; atoms with equal columns share a class. Checked look-aheads then read classes too (regex_next_class decodes the next character for them), and a match must be decided by the character after it (a delay counts characters, which regex_match_back cannot express), else its look-aheads are checked. Oniguruma's look-behinds and \b and the byte escape \C need the byte construction. ERNIE's \p{Nd}{1,510}(?=(?>\p{Nd}{510})*(?:\P{Nd}|$))|\G\p{Nd}{510} becomes a scan DFA of 3061 states and 2 classes with a look-ahead of 512 states. See unit_codepoint_classes.c and scan_codepoint_classes.c.

Scan Mode (--scan)

The transition table is emitted as for the DFA engine (state 0 is the dead state), followed by

  1. 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.
  2. 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.
  3. An optional regex_initial[257] — the start state by the byte before the start position (256: start of input), emitted when anchors, \b or look-behinds make them differ. After a non-ASCII byte, Oniguruma's \b and look-behinds take it from regex_by_mask[], by the classes regex_prev_mask() finds the character before the start in. With Oniguruma's \G, regex_initial_g[] / regex_by_mask_g[] hold the start states for the first position regex_find() tries, which it tells regex_match_at() with the argument g.
  4. 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.
  5. regex_find() tries the start positions from from on.
  6. Optionally a main() that prints every match of argv[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:

  1. 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, or uint32_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.
  2. A match function with a fully unrolled inner loop — one if (state & bit) next |= …; per active position.
  3. 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;
}

Over code-point classes

Over UTF-8 bytes a class costs a position for every byte position of its characters: GPT-2's pre-tokenizer regex needs 878 positions (26 over classes), more than the limit of 256. With unit="codepoint", or "auto" when the tables are smaller or the byte NFA exceeds its positions, the NFA reads the code-point classes of the DFA construction instead: a class of any size is one position ( ?\p{L}+| ?\p{N}+: 5), the tables regex_trans_P[C] have a column per class, and the match function decodes UTF-8 and looks the class up as the code-point unit does (ill-formed input does not match). Oniguruma's look-behinds and \b and \C need the bytes. See bitnfa_codepoint_classes.c.

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

  1. Generate C code from the regex pattern.
  2. Compile with gcc -Werror.
  3. Execute the binary on each test subject.
  4. 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

emmtrix Technologies GmbH

Metadata

Release files for emx-regex-cgen 0.3.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for emx-regex-cgen 0.3.1
File Size Uploaded Provenance Actions
emx_regex_cgen-0.3.1.tar.gz 400.3 kB With provenance Details for emx_regex_cgen-0.3.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for emx-regex-cgen 0.3.1
File Interpreter ABI Platform Actions
emx_regex_cgen-0.3.1-py3-none-any.whl Python 3 none any Details for emx_regex_cgen-0.3.1-py3-none-any.whl

Total release size: 560.1 kB

Release files / emx_regex_cgen-0.3.1.tar.gz

Download URL emx_regex_cgen-0.3.1.tar.gz
Size 400.3 kB
Tags Source
SHA-256 checksum
How to use checksums
4b27fb7cccfb165ad6ea3ac4dd361189d4b0f07e534c508ba5184990e644aa74
BLAKE2b-256 checksum
How to use checksums
4b62d4ace01f942e45c515a75f380351355bd05e9fbeede1d39f3ffc14255461
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 log

Release files / emx_regex_cgen-0.3.1-py3-none-any.whl

Download URL emx_regex_cgen-0.3.1-py3-none-any.whl
Size 159.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
12d6dfb349e0c3154404fc1fcceeb041d0dbb3939e74b9541c92a20308947d25
BLAKE2b-256 checksum
How to use checksums
7f0349f8feed434b5bc9fc8ebee2fa2b2bc212815ac81ed639ecea5c329ebbaa
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 log

Security for emx-regex-cgen 0.3.1

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.

Select from 2 files

Attestation for emx_regex_cgen-0.3.1.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 log

A 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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page