Skip to content

std/regex ​

From the spec

This page is spec/std/regex.md, the specification the compiler and the backends are written from. It is rebuilt from the spec with every deploy (how).

Regular expressions in one dialect on every backend: RE2's linear-time subset, so matching a text takes time proportional to its length times the pattern's size, whatever the pattern (no ReDoS, which matters for user code and for patterns from configuration). It is written in Weft (core/crates/weft-check/src/std/regex.weft) over std/$regex, which parses and matches: on the VM the regex crate (weft-regex), on the JS backend a port of the regex crate's Thompson NFA and PikeVM (src/weft/regex.ts), not the engine's backtracking RegExp. Both give the same matches, captures and iteration (core/crates/weft-regex/tests/cases.json holds them to it). Like std/time, user code (std/sandbox) may import it.

weft
import { regex, find, findAll, replaceAll, split, test } from "std/regex"

let date = regex"(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})"
let m = date.find("due 2026-11-17")                // m.named.get("year") == "2026", m.start == 4
regex"\d+".replaceAll("a1b22c333", "#")           // "a#b#c#"
regex"\s*,\s*".split("a , b,c")                    // ["a", "b", "c"]
regex"(?i)^hello\b".test("Hello, world")          // true
let word = regex"\b{name}\b"                        // a value matches literally: name = "a.b" finds "a.b", not "axb"

The functions are free functions taking the Regex first: re.find(s) is find(re, s) by the method rule (language.md, Functions). A string's own replace, replaceAll and split take strings.

The dialect ​

literalsany character but \ ^ $ . | ? * + ( ) [ ] { }; \ before any ASCII punctuation character is that character
escapes\n \r \t \f \v \0, \xHH, \uHHHH, \u{H…} (a code point, not a surrogate)
.any character but \n (any with s)
\d \w \s and \D \W \SASCII digits; ASCII letters, digits and _; JS's whitespace (what trim() removes)
\p{…} and \P{…}a general category (L, Lu, Letter, gc=Lu), Script=Greek (or sc=; Arabic, Armenian, Bengali, Bopomofo, Braille, Cherokee, Common, Cyrillic, Devanagari, Ethiopic, Georgian, Greek, Gujarati, Gurmukhi, Han, Hangul, Hebrew, Hiragana, Inherited, Kannada, Katakana, Khmer, Lao, Latin, Malayalam, Mongolian, Myanmar, Oriya, Sinhala, Syriac, Tamil, Telugu, Thaana, Thai, Tibetan, Tifinagh), or Alphabetic, White_Space, Uppercase, Lowercase, Emoji, Emoji_Presentation, Extended_Pictographic, ASCII, Any
classes[abc], [^abc], ranges [a-z], and the escapes above inside; - is literal first or last; ], [ and \ are escaped inside, and so are doubled &&, --, ~~
groups(…) captures, (?<name>…) captures by name (ASCII letters, digits, _; unique), (?:…) doesn't
repetition* + ?, {n}, {n,}, {n,m} (counts up to 1,000), each greedy or lazy (*?, {n,m}?)
alternationa|b, empty alternatives allowed
anchors^ and $: the text's start and end (with m, also after and before each \n); \b: between an ASCII word character and anything else
flagsa leading (?ims): i ignores case (Unicode simple case folding), m multi-line anchors, s lets . match \n

Not in the dialect, each an error saying so: backreferences (\1, \k<…>), lookaround ((?=, (?!, (?<=, (?<!), flags anywhere but the start, \B, \A, \z, possessive and doubled quantifiers (a**; group the first), quantified assertions (^*), octal escapes, nested classes and set operations, \b in a class (\x08 is a backspace), unknown escapes and properties. Groups nest at most 100 deep, and a pattern's repetitions may expand it to at most 20,000 (each character, class or . counting 1, a class with a property or a non-ASCII range 10; x{n,m} counts x max(n, m) times): it keeps both engines' programs small.

Matching is leftmost-first, as in Perl and JS: of the matches starting leftmost, the one the pattern prefers (alternatives in order, greedy repetition taking as much as it can, lazy as little). Positions are UTF-16 code units, as every string position (std.md), and characters are code points: a surrogate pair is one character, a lone surrogate matches as U+FFFD. Captures follow the regex crate where it differs from JS: a group inside a repetition keeps its last iteration's text, including an empty one ((a*)* on "b" captures "" at 0, where JS gives undefined). Case folding and Unicode properties use each engine's Unicode tables (the regex crate's, the JS engine's), which can differ for characters newer than either.

regex"…" ​

A tagged string (language.md, Tagged strings) whose pattern is read as written: string escapes aren't applied (\d is the digit class, \\ a literal backslash), and repetitions and properties read as in any regex: \d{4}, \d{2,}, \d{2,5}, \p{L}. (In a tagged string {2,}, {2,5} and \p{…} are text; {4} is a value as anywhere, and this tag takes a number literal there as the count. A count known only at run time is compile's.) It is checked at compile time: a pattern outside the dialect is an error at the literal (tag-check), so a regex"…" never fails at run time. A string value, {x} with x: string, matches its text literally, as one atom (a group: {word}+ repeats all of it); it can't go inside a class. Write braces around a value's position doubled for a literal brace ({{, }}) as in any tagged string, or escaped (\{). The tag is checked when called by its imported name.

Values ​

type
Regex{ source: string }: the pattern in the dialect, flags as a leading (?ims). Data: it compares, converts to json and crosses to the client and the database. Compiled programs are cached by source in each runtime (the 256 latest). One made by hand that isn't a pattern panics (TypeError) when used
Match{ text, start, end, groups, named }: the match and its span (end exclusive), groups: string?[] by index (groups[0] the whole match; null for a group that didn't take part), named: Map<string, string?> for named groups
PatternErrorPatternError { message, at }: why a text isn't a pattern, and where (code units)

Functions ​

regex(parts, ...values: (string | number)[]): Regexthe tag
compile(pattern: string, flags: string = ""): Regex ! PatternErrora pattern made at run time; flags any of i, m, s
escape(text: string): stringa \ before each ASCII punctuation character: a pattern matching text
test(re, text): booleanwhether it matches somewhere
matches(re, text): booleanwhether it matches all of text (as ^(?:…)$)
find(re, text, from: number = 0): Match?the first match starting at or after from (clamped; inside a surrogate pair means after it)
findAll(re, text): Match[]every match, left to right, not overlapping: the next search starts where a match ends, one character later after an empty match (JS's matchAll: findAll(regex"a*", "baaa") gives "" at 0, "aaa", "" at 4)
replace(re, text, template: string): stringthe first match replaced by template: $1…$99 a group (two digits when that group exists, else one), $<name> a named group, $& the match, $$ a $; a group that didn't take part gives ""; anything else stays as written
replaceAll(re, text, template: string): stringevery match (as findAll finds them) replaced
replaceWith<E>(re, text, f: (m: Match) => string ! E): string ! Eevery match replaced by what f gives (failing as f fails)
split(re, text, limit?: number): string[]the pieces between matches; an empty match at either end of the text or right after the previous match doesn't split (split(regex"", "abc") is ["a", "b", "c"]); groups aren't included (unlike JS); with limit, the first limit pieces

std/$regex ​

What the module needs from its host, positions in code units: check(pattern) (the problem, or null), names(pattern) (each group's name, "" for none, the whole match first), exec(pattern, text, from) (the first match's spans, start and end per group, -1 for none; [] for no match), execAll(pattern, text, limit) (every match's spans, as findAll iterates) and whole(pattern, text). Each runtime keeps the parser's messages word for word (the tests compare them).

Weft is in development. The reference is the spec as it stands today.