re
The re module has regular expressions: search, extract, validate, replace and split text by pattern. It runs in time linear in the text's length, whatever the pattern, so a pattern from a user or a config file can't hang a server (no "catastrophic backtracking").
import re
fn main() Result[int, str]:
r = re.compile("(\\d{4})-(\\d{2})-(\\d{2})")?
text = "shipped 2026-09-28, delivered 2026-10-02"
for m in r.find_all(text):
print(m.text, "month", m.groups[2])
print(r.test("no dates here"), r.count(text))
print(r.replace_all(text, "$3/$2/$1"))
return Ok(0)2026-09-28 month 09
2026-10-02 month 10
false 2
shipped 28/09/2026, delivered 02/10/2026re.compile returns Result[re.Regex, str]: the error says what's wrong and where. For a pattern written in the program, re.must(pattern) gives the Regex directly (a bad pattern is a runtime error). Compiling is cached: the same pattern compiles once per program, so re.must inside a loop or a handler is fine.
Patterns are ordinary strings, so a backslash is written twice: "\\d+" is the pattern \d+, and "\\." matches a dot.
Functions
re.compile(pattern: str) Result[re.Regex, str]
re.must(pattern: str) re.Regex a bad pattern is a runtime error
r.test(s: str) bool a match anywhere in s
r.full(s: str) bool the whole of s matches (validation)
r.search(s: str) Option[re.Match] the first match
r.search_at(s: str, at: int) Option[re.Match] the first match at or after byte at
r.find_all(s: str) [re.Match] every match, left to right
r.count(s: str) int how many matches
r.replace_all(s: str, repl: str) str $1 ${name} $0 $$ in repl
r.replace_first(s: str, repl: str) str
r.replace_with(s: str, f: fn(re.Match) str) str
r.split_all(s: str) [str] the text between matches
r.names() [str] each group's name ("" if unnamed)
re.escape(s: str) str s as a pattern that matches it literally
re.error() str why the last compile failed
re.literals(pattern: str, min: int) Result[[[str]], str] what every match contains (below)
re.parse(pattern: str) Result[re.Tree, str] the syntax tree (see library/std/re/parse.tn)A re.Match has start and end (byte offsets: s[m.start..m.end] is the match), text, groups (groups[0] is the whole match, groups[1] the first group, "" for a group that didn't take part), starts (each group's start, -1 if it didn't take part), and named ({name: text} for named groups; m.group("name") reads one).
Groups, names and validation
import re
fn main():
email = re.must("(?P<user>[\\w.+-]+)@(?P<domain>[\\w-]+(?:\\.[\\w-]+)+)")
match email.search("contact: Ada.L+news@acme.co.uk (work)"):
Some(m):
print(m.group("user"), "at", m.group("domain"), m.start, m.end)
None:
print("no email")
zip = re.must("\\d{5}(-\\d{4})?")
for s in ["12345", "12345-6789", "1234", "12345 "]:
print(s, zip.full(s))
print(email.names())Ada.L+news at acme.co.uk 9 30
12345 true
12345-6789 true
1234 false
12345 false
["", "user", "domain"]Use full to check that a whole string has a format; test and search look anywhere in it.
Replacing and splitting
import re
fn main():
ws = re.must("\\s+")
print(ws.replace_all(" lots of \t space ", " "))
print(re.must("(\\w+)@(\\w+)").replace_all("ada@home bob@work", "${2}:$1"))
shout = re.must("\\b[a-z]")
print(shout.replace_with("the quick brown fox", fn(m) m.text.upper()))
print(re.must("\\s*[,;]\\s*").split_all("a, b;c , d"))
print(re.must("(?i)warn(ing)?").replace_first("WARNING: disk; warning: cpu", "!")) lots of space
home:ada work:bob
The Quick Brown Fox
["a", "b", "c", "d"]
!: disk; warning: cpuIn a replacement, $1 is group 1 (one digit; ${12} for more), ${name} a named group, $0 the whole match and $$ a dollar sign.
Syntax
The syntax is RE2's, which Go, Rust, Python and JavaScript share for everything below.
. any character but a newline ((?s) for newlines too)
[abc] [a-z] one of the characters; [^abc] any other; [[:alpha:]] [[:digit:]] [[:space:]] ...
\d \w \s a digit, a word character [0-9A-Za-z_], whitespace (ASCII); \D \W \S the rest
^ $ the start / end of the text; with (?m), of any line
\A \z the start / end of the text, always
\b \B a word boundary / not one
(x) a group; (?:x) without capturing; (?P<name>x) or (?<name>x) with a name
x|y x or y (the first that matches wins, like Perl and Python)
x* x+ x? zero or more, one or more, zero or one (as many as possible)
x{n} x{n,} x{n,m} exactly n, at least n, n to m (n and m up to 1000)
x*? x+? x?? x{n,m}? the same, as few as possible
(?i) (?m) (?s) (?x) flags: case-insensitive, multi-line, . matches \n, spaces and # comments
ignored; (?i:x) for part of a pattern, (?-i) to turn one off
\n \t \x41 \x{1F600} \. \* \\ escapes: special characters, and characters by numberText is UTF-8, and matching is by character: . or [à-ÿ] matches é (two bytes) as one character. Offsets are in bytes, like everywhere else in Tern. (?i) folds ASCII, Latin-1, Greek and Cyrillic letters.
Not supported: backreferences (\1) and lookaround ((?=x), (?!x), (?<=x)), because they need a backtracking engine, which can take exponential time; and Unicode classes like \p{L}. The error says so and suggests what to write instead.
import re
fn main():
print(re.compile("(a)\\1").is_err(), re.error())
evil = re.must("(a+)+b") # hangs backtracking engines on a long "aaaa..."
print(evil.test("a".repeat(100000)))true re: backreferences (\1) aren't supported: they need backtracking, which can take exponential time (at byte 5 of the pattern)
falseSearching an index first
re.literals(pattern, min) says which strings every match must contain, for narrowing a search with an index (n-grams, a full-text index) before running the pattern on what's left. It returns groups of literals: a text with a match holds at least one literal of each group. Literals are lowercase and compare ASCII letters without case (so an index that folds case can use them for any pattern); none is shorter than min bytes. [] means nothing is certain (like \w+), so every text has to be checked. Groups come most selective first.
import re
fn main():
print(re.literals("cdn\\.(shopify|bigcommerce)\\.com/s/files", 3).unwrap())
print(re.literals("klaviyo|mailchimp", 3).unwrap())
print(re.literals("(?i)Error: .* timed out", 3).unwrap())
print(re.literals("sk_live_[0-9a-zA-Z]{24}", 3).unwrap())
print(re.literals("\\d+", 3).unwrap())[["cdn.shopify.com/s/files", "cdn.bigcommerce.com/s/files"]]
[["klaviyo", "mailchimp"]]
[[" timed out"], ["error: "]]
[["sk_live_"]]
[]It's the analysis from Russ Cox's code search: alternations and small classes become sets of strings (ab[0-9] is ten), repetition keeps what a match starts and ends with, and sets that grow past a few dozen strings give up, so the answer is always right but less precise for patterns that can match many different strings.
Performance
A pattern compiles once per program (the last 1000 are kept) and is shared by every thread. Searching runs a lazy DFA, built as it's needed and kept with the pattern, that reads each byte of the text once; before it, a literal the matches start with (memchr on its rarest byte), the possible first bytes (16 at a time with simd), a few literal alternatives (Teddy, also with simd), or a literal in the middle (an email's @) skip to where a match could begin. Groups are then filled in over just the matched text (one pass when the pattern allows, else a bounded backtracker). Time grows with the text's length, never exponentially. The engine is written in Tern (library/std/re/). bench/std/results.md (tern run bench/std/run.tn -- regex) compares it with Go's regexp and Rust's regex.