Expand description
Regular expressions with the grammar and the answers of ECMA-262 (the RegExp of JavaScript), for Rust.
use corvus_regex_ecma262::Regex;
let re = Regex::new(r"(?<word>\p{L}+)(?=!)", "gu").unwrap();
let words: Result<Vec<&str>, _> = re.find_iter("Hej! Grüß dich!").map(|m| m.map(|m| m.as_str())).collect();
assert_eq!(words.unwrap(), ["Hej", "dich"]);
assert_eq!(re.replace("Hej! Grüß dich!", "<$<word>>").unwrap(), "<Hej>! Grüß <dich>!");Regex has is_match, find, find_iter, captures, captures_iter, replace, replace_all and
split over &str, and the same over UTF-16 (&[u16], which may hold lone surrogates) with the suffix _utf16.
Positions are in the units of the text: bytes of UTF-8, or UTF-16 code units. Nothing is transcoded, and a match
allocates nothing once the thread’s working memory has grown to what the pattern and the text need (a
Captures is a vector of its groups; Regex::captures_read_at reads them into a CaptureLocations
without allocating).
A pattern is read as new RegExp(pattern, flags) reads it: with the u flag by the grammar of the u flag and
matched by code point; with none by the Annex B grammar and matched by UTF-16 code unit, as ECMA-262 matches a
pattern with no u flag. The i, m and s flags are the modifiers in force at the start of the pattern, which a
modifier group of ECMAScript 2025 ((?i:...), (?-m:...)) changes for part of it.
The engine came out of the Corvus JSON Schema evaluator for Rust, where it was a port of the ecmaregex
package of the Go module, which the Object Pascal and OCaml ports carry too. The files and the names still
follow the Go source, so that a fix made in one can be carried to the others: parse.rs is parse.go,
compile.rs is compile.go, vm.rs is vm.go, dfa.rs is dfa.go, charset.rs, fold.rs and units.rs
are the files of the same names, and ucd.rs with tables<major>.rs is the ucd package.
§Code units
A pattern with no u flag is matched by UTF-16 code unit. A character beyond the Basic Multilingual Plane is then
two characters, a high surrogate and a low one, to the dot, a class, a quantifier, a group and a backreference. A
match can start or end between the two. Such a character in the pattern is two atoms, and a class range between
two of them is an error. Case is folded by the Canonicalize of a pattern with no u flag. The text stays UTF-8
and no UTF-16 copy of it is made (see units.rs): the position between the halves of a character is the offset
of its third byte. Only a text with a character beyond the Basic Multilingual Plane is read differently with the
u flag and without it.
§The matcher
Every pattern is compiled for a backtracking matcher. A pattern with no lookaround, no backreference, no
multiline anchor and no case-insensitive word boundary also gets a deterministic automaton over ASCII text when
it is small enough and has no word boundary (see dfa.rs), which decides an ASCII text with one table read per
byte.
The backtracking matcher keeps its choices on an explicit stack that the thread reuses, so a long text cannot
overflow the stack of the thread and a match does not allocate once the stack has grown. Four things keep it
from the time a backtracking matcher can take. A repetition whose body cannot consume a character is run once,
or not at all (see simplify), as V8 runs it. A counted loop gives up at a position from which the rest of the
pattern, with the iterations the loop still owes, needs more text than is left (see set_needs). A way the next
character of the text rules out is not taken (see set_quick), as in V8. And where a pattern has no
backreference the matcher remembers the places from which every way has failed (see memo in vm.rs), so a
repetition inside a repetition takes time proportional to the pattern times the text. What is left, a group read
back inside a repetition above all, can still take time that doubles with each character, and is ended by the
limit of the match.
§Limits
A pattern has a match timeout, as a Regex of System.Text.RegularExpressions has: the time each match may take
before it is abandoned, which brings with it a cap on the memory of its backtracking. Every member that matches
returns Result, and a match that reaches either is an Err of MatchError, never an answer.
Regex::with_timeout gives a pattern one, and set_default_match_timeout gives one to every pattern compiled
after it. Without one (the default) a match has no limit of time or of memory, so a program that matches patterns
or texts from outside should set one. The members that end in _within give one match a limit of its own.
Regex::new refuses a pattern over a limit of size (MAX_PATTERN_LENGTH, MAX_NESTING, MAX_SIZE)
with Error::TooLarge, so that reading and compiling a pattern take bounded time and memory whatever the
pattern holds.
§Coverage
The grammar is that of ECMAScript 2025. It includes lookbehind, named groups, group names shared between
separate alternatives, modifier groups, and Unicode property escapes for every property, value and alias
ECMA-262 lists, with Unicode 17 data, and the v flag of ECMAScript 2024: nested classes, the difference and the
intersection of classes, strings in a class (\q{...}) and the seven properties of strings. The properties and
the case folding come from the tables of ucd.rs, tables<major>.rs and strings<major>.rs and never from the
standard library or from a dependency, so a pattern matches the same texts whatever built the program.
RegexBuilder reads a pattern with the grammar of ECMAScript 2020 (Edition::Es2020), the grammar JSON
Schema 2020-12 names, and with the tables of Unicode 13, 17 or 18 (UnicodeVersion), each chosen on its own.
Both are read when the pattern is compiled, so a match costs the same whichever is chosen.
Structs§
- Capture
Locations - Where each group of a match is, read by
Regex::captures_read_atwithout allocating. - Capture
Matches - The captures of the matches of a global search (see
Regex::captures_iter). - Captures
- What a match captured: the match as group 0, then each capturing group, which may not have taken part.
- Flags
- The flags of a pattern, as
new RegExp(pattern, flags)takes them. - Match
- One match: where it starts and ends in the text, in the text’s units (bytes of UTF-8, or UTF-16 code units).
- Matches
- The matches of a global search (see
Regex::find_iter). - Regex
- A compiled ECMA-262 regular expression. It is immutable once compiled, and safe to share between threads; a clone shares nothing that changes.
- Regex
Builder - Compiles a pattern with settings beyond its flags: the match timeout, the edition of ECMA-262 whose grammar it is
read with and the version of Unicode whose tables it is read with, each independent of the others. What it does
not set is as
Regex::newhas it: thedefault_match_timeout, today’s grammar and V8’s Unicode. - TooLarge
Error - Reports a pattern over one of the limits of size.
limitnames the limit andvalueis its value. The pattern was not read to its end, so the error says nothing of whether it is valid.
Enums§
- Edition
- The edition of ECMA-262 whose grammar a pattern is read with.
- Error
- Why a pattern does not compile.
- Limit
- Which limit of size a pattern is over.
- Match
Error - Why a match was abandoned. Neither is an answer.
- Unicode
Version - The version of Unicode whose character database a pattern is read with: the members of each
\p{...}, the characters of a group name, and the case folding of theiflag. It is independent of theEdition.
Constants§
- MAX_
NESTING - Caps the depth of groups, which bounds the recursion of the parser and of the compilers.
- MAX_
PATTERN_ LENGTH - The longest pattern that is read, in bytes of UTF-8.
- MAX_
SIZE - The largest size a pattern may have, in the bytes the parser counts for it:
NODE_SIZEfor each node of its syntax tree, andRANGE_SIZEfor each range of a class as its members are read, for each range a case insensitive group or a negated property adds, for each alternative that encloses a named group and for each group that shares its name. The tree, the program compiled from it and the time to make both are proportional to that size, so it bounds them all: a pattern at the limit takes a few milliseconds and a few megabytes. - MAX_
STACK - The number of entries the backtracking stack of a match with a limit may hold (24 bytes each). A match that
needs more is abandoned. A pattern that keeps a choice for every character of its text needs one entry or a few
for each, so this is room for a text of some hundred thousand characters, and a pattern that pushes without
consuming, such as
(?:a?){2147483647}, reaches it in a few milliseconds. It is looked at with the clock, so the stack can go past it byCHECK_EVERYentries.
Traits§
- Haystack
- A text the engine matches:
str(UTF-8, the engine’s own encoding) or[u16](UTF-16, which may hold lone surrogates). It is sealed: no other type can be one.
Functions§
- default_
match_ timeout - The match timeout a pattern compiled now by
Regex::newtakes (seeset_default_match_timeout). - set_
default_ match_ timeout - Sets the match timeout of every pattern compiled from now on by
Regex::newandRegex::with_flags: the time each match may take before it is abandoned withMatchError::Time, orNone(or zero) for no limit, which is the default. It is the process-wide default ofSystem.Text.RegularExpressions(REGEX_DEFAULT_MATCH_TIMEOUT), and a program that matches patterns or texts from outside should set it when it starts (seeRegex::with_timeout). A pattern already compiled keeps the timeout it was compiled with.