silk.text.regex.
ECMAScript Unicode regular expressions for text and JSON Schema patterns.
When to use#
Use Regex.compile and Regex.test to reuse a Pattern across many searches. Use
Regex.validate to check syntax or Regex.matches for a one-off unanchored search. Patterns
use the ECMA-262 Unicode (u) grammar, not shell glob syntax.
Details#
The engine is Silk's own regular-expression compiler and backtracking matcher. It started from
the QuickJS engine (Copyright (c) 2017-2021 Fabrice Bellard and Charlie Gordon, under the MIT
license in licenses/quickjs.txt). A pattern compiles to bytecode once; a search then runs it
with search hints (literal runs, anchors and first-character sets) and a heap backtracking
stack, so long text never exhausts the native stack. Matching supports captures, named and
numeric backreferences, forward and backward assertions, alternation, character classes, Unicode
properties, greedy and lazy repetition, and scoped i, m, and s modifiers. Unicode
properties and case folding use Unicode 17.0.0.
Text is UTF-8. ASCII text is matched in place; other text is converted to UTF-16 for the
search, and a surrogate pair is one character, as in ECMAScript's u mode. Syntax failures
and exhausted resource limits are errors, never a negative match.
Import as Regex with import silk.text.regex { Regex }.
Public declarations: 8.
RegexReason#
pub enum RegexReasonThe kind of failure a regular expression reports.
Syntax#
SyntaxThe pattern does not follow the ECMAScript Unicode (u) grammar.
PatternLimit#
PatternLimitThe pattern exceeds 65,536 bytes, nests groups deeper than 255 levels, or has 255 or more captures, too many class ranges or too many nested quantifiers.
MatchLimit#
MatchLimitA search exhausted its work budget of about 1,000,000 backtracking steps.
RegexError#
pub struct RegexErrorA structured regex failure, distinct from a valid pattern that does not match.
Field reason#
pub reason: RegexReasonThe syntax or resource-limit failure.
Field message#
pub message: string<'static>What is wrong, in the words of the ECMAScript grammar; empty for a resource limit.
Field offset#
pub offset: usizeThe byte offset in the pattern where the failure was detected; zero for a resource limit.
Pattern#
pub struct PatternAn owned, immutable ECMAScript Unicode regular-expression program.
Details#
Construct it with Regex.compile and search any number of strings with Regex.test. It owns
its bytecode and does not borrow the source pattern. Matching does not mutate it.
Regex#
pub struct RegexThe owner of ECMAScript Unicode pattern validation and unanchored matching operations.
Implementation Regex#
impl RegexAssociated function compile#
pub effect fn compile(pattern: string) -> Pattern
! RegexError | OutOfMemoryError
? &mut AllocatorCompiles an ECMAScript Unicode (u) pattern for repeated unanchored searches.
Details#
Patterns have no surrounding slashes or flags. Scoped (?ims-ims:...) modifiers are
supported. Captures, backreferences, lookarounds and Unicode property escapes compile to
bytecode; property aliases and case folding use Unicode 17.0.0. The result owns its program
and does not borrow pattern.
Errors#
RegexErrorwithSyntaxfor invalid syntax, orPatternLimitfor more than 65,536 pattern bytes, groups nested deeper than 255 levels, 255 or more captures, or too many class ranges or nested quantifiers.OutOfMemoryErrorif the allocator cannot supply the program.
Associated function validate#
pub effect fn validate(pattern: string) -> ()
! RegexError | OutOfMemoryError
? &mut AllocatorChecks the entire pattern against the ECMAScript Unicode (u) grammar.
Details#
There are no surrounding slashes or flags. Scoped (?ims-ims:...) modifiers are accepted.
Unicode property names and values are exact, case-sensitive Unicode 17.0.0 aliases. Legacy
octal and identity escapes are not accepted in Unicode mode.
Errors#
RegexErrorwithSyntaxfor invalid syntax, orPatternLimitfor more than 65,536 pattern bytes, groups nested deeper than 255 levels, 255 or more captures, or too many class ranges or nested quantifiers.OutOfMemoryErrorif the allocator cannot supply the program.
Associated function matches#
pub effect fn matches(pattern: string, text: string) -> bool
! RegexError | OutOfMemoryError
? &mut AllocatorReturns whether any substring of text matches an ECMAScript Unicode (u) pattern.
Details#
The pattern has no surrounding slashes or flags. Matching is case-sensitive, with . excluding
LF, CR, U+2028 and U+2029, unless scoped i, m or s modifiers change those rules. Without
m, ^ and $ mean the actual beginning and end, including when text ends in a newline.
\d and \w are ASCII classes; \s is ECMAScript whitespace and line terminators.
Captures, backreferences and repetition have ECMAScript backtracking order.
Errors#
RegexErrorfor an invalid pattern, asRegex.compilereports it, orMatchLimitwhen the search exhausts its work budget. Exhaustion is never reported asfalse.OutOfMemoryErrorif the allocator cannot supply the program or matcher state.
Associated function test#
pub effect fn test(pattern: &Pattern, text: string) -> bool
! RegexError | OutOfMemoryError
? &mut AllocatorSearches text with a previously compiled ECMAScript Unicode pattern.
Details#
Searches are unanchored unless the pattern supplies anchors. Captures and repetition use ECMAScript backtracking order. ASCII text is searched in place; other text is first converted to UTF-16 in storage that belongs to this call. The pattern is immutable.
Errors#
RegexErrorwithMatchLimitafter about 1,000,000 backtracking steps. Exhaustion is never reported asfalse.OutOfMemoryErrorif the allocator cannot supply converted text or backtracking storage.
Associated function find#
pub effect fn find<'a>(pattern: &Pattern, text: string<'a>) -> Option<Match<'a>>
! RegexError | OutOfMemoryError
? &mut AllocatorReturns the first match of a compiled pattern in text, with its capture groups.
Details#
The search is the one Regex.test runs: unanchored unless the pattern supplies anchors, with
ECMAScript backtracking order deciding which match is first and what each group holds. The
match borrows text; its offsets count UTF-8 bytes even when the search ran on UTF-16.
Errors#
RegexErrorwithMatchLimitafter about 1,000,000 backtracking steps. Exhaustion is never reported as no match.OutOfMemoryErrorif the allocator cannot supply converted text, backtracking storage or the capture offsets.
Associated function typed#
pub static fn typed<T>(pattern: string<'static>) -> Typed<T>Checks a pattern against a capture struct at compile time.
Details#
T is a struct with named fields, written at 'static. Every named group of pattern must
be a field of T and every field a named group; a field is Option<string<'a>> exactly when
a match can leave its group unset (under ?, * or {0,n}, in one alternative of |, in a
negative lookaround, or a name two alternatives share) and string<'a> otherwise. Unnamed
groups need no field. An invalid pattern or a mismatch is a compile error.
In the editor, each group name of a constant's pattern acts as a use of its field: an inlay hint shows the field's type, hover shows the field and its doc, and find references on the field lists the group.
Gotchas#
Regex.typed reads only whether a field type is a union. A field type that is neither
string<'a> nor Option<string<'a>>, such as i32, is refused where the pattern is
searched, by the Capture bound of find and whole.
Examples#
Read a version tag#
import silk.core.option { Option }
import silk.mem.allocator { Allocator, OutOfMemoryError }
import silk.text.regex { Regex, RegexError, Typed }
struct Version<'a> {
pub major: string<'a>,
pub minor: string<'a>,
pub patch: string<'a>,
pub pre: Option<string<'a>>,
}
const VERSION: Typed<Version<'static>> = Regex.typed<Version<'static>>(
"^v(?<major>\\d+)\\.(?<minor>\\d+)\\.(?<patch>\\d+)(-(?<pre>[0-9a-z.]+))?$",
)
// The prerelease part of a tag such as v0.1.0-dev.58, if it is a version with one.
effect fn prerelease<'a>(tag: string<'a>) -> Option<string<'a>>
! RegexError | OutOfMemoryError
? &mut Allocator {
let versions = run VERSION.compile()
let found = run versions.whole<Version<'a>>(tag)
match move found {
Option<Version<'a>>.Some { value } => {
return value.pre
}
Option<Version<'a>>.None => {
return Option<string<'a>>.none()
}
}
}Associated function groupCount#
pub fn groupCount(pattern: &Pattern) -> usizeReturns the number of capture groups in a compiled pattern, counting group 0, the whole match.
Associated function groupIndex#
pub fn groupIndex(pattern: &Pattern, name: string) -> Option<usize>Returns the number of the first capture group named name, or none.
Details#
Groups are numbered from 1 in the order their ( appears; group 0 is the whole match. A name
that ECMAScript lets two alternatives share, as in (?<n>a)|(?<n>b), gives the first group.
Match#
pub struct Match<'a>One match of a compiled pattern in a text: the matched span and the span of each capture group.
Details#
Group 0 is the whole match; groups 1 and up are the pattern's capture groups, numbered in the
order their ( appears. A group that took no part in the match has no text. Offsets count
UTF-8 bytes of the searched text, so they cut it with String.slice. The match borrows the
text it was found in.
Implementation Match<'a>#
impl<'a> Match<'a>Method groupCount#
pub fn groupCount(self: &Self) -> usizeReturns the number of groups, counting group 0, the whole match.
Method start#
pub fn start(self: &Self) -> usizeReturns the byte offset where the match starts.
Method end#
pub fn end(self: &Self) -> usizeReturns the byte offset just past the end of the match.
Method text#
pub fn text(self: &Self) -> string<'a>Returns the matched text.
Method group#
pub fn group(self: &Self, index: usize) -> Option<string<'a>>Returns the text of group index, or none when the group took no part in the match.
Gotchas#
The program traps if index is not less than groupCount().
Method named#
pub fn named(self: &Self, pattern: &Pattern, name: string) -> Option<string<'a>>Returns the text of the group named name, or none when no group of that name took part.
Details#
pattern is the pattern this match came from. A name that two alternatives share, as in
(?<n>a)|(?<n>b), gives the text of whichever group took part.
Gotchas#
The program traps if pattern has more groups than the match, a sign it is another pattern.
Capture#
pub interface Capture<'a>A field type that a typed pattern fills from one named capture group.
Details#
string<'a> holds a group every match sets, and Option<string<'a>> a group a match can
leave unset. Regex.typed requires a field to be optional exactly when its group can be
unset, and counts a field type that is a union, such as Option, as optional.
Operation capture#
fn capture(group: Option<string<'a>>) -> SelfBuilds the value from the group's text, or from none when the group took no part.
Implementation Capture<'a> for string<'a>#
impl<'a> Capture<'a> for string<'a>Operation capture#
fn capture(group: Option<string<'a>>) -> string<'a>Returns the group's text. Regex.typed admits a string only for a group every match sets.
Implementation Capture<'a> for Option<string<'a>>#
impl<'a> Capture<'a> for Option<string<'a>>Operation capture#
fn capture(group: Option<string<'a>>) -> Option<string<'a>>Returns the group's text, or none when the group took no part in the match.
Typed#
pub struct Typed<T>A pattern checked at compile time against T, a struct with one field per named group.
Details#
Build it with Regex.typed, usually as a const. T is the struct at 'static; a search
names the same struct at the text's lifetime, as in matcher.find<Version<'a>>(tag).
Implementation Typed<T>#
impl<T> Typed<T>Method pattern#
pub fn pattern(self: &Self) -> string<'static>Returns the pattern text.
Method compile#
pub effect fn compile(self: &Self) -> Matcher<T>
! RegexError | OutOfMemoryError
? &mut AllocatorCompiles the pattern for repeated typed searches.
Errors#
RegexErrorwithPatternLimitfor a limit only the compiled program reveals: too many class ranges or nested quantifiers.Regex.typedhas already rejected every syntax error.OutOfMemoryErrorif the allocator cannot supply the programs.
Matcher#
pub struct Matcher<T>A compiled typed pattern: searches return the capture struct directly.
Implementation Matcher<T>#
impl<T> Matcher<T>Method find#
pub effect fn find<'a, U>(self: &Self, text: string<'a>) -> Option<U>
! RegexError | OutOfMemoryError
? &mut AllocatorReturns the first match in text as a U, the capture struct at the text's lifetime.
Details#
U is the struct Regex.typed checked, named again with the lifetime of text because
its fields borrow it: matcher.find<Version<'a>>(tag) for a Matcher<Version<'static>> and
a tag: string<'a>. A U whose fields differ from T's in name or optionality is a
compile error.
Errors#
RegexErrorwithMatchLimitafter about 1,000,000 backtracking steps, never no match.OutOfMemoryErrorif the allocator cannot supply search storage.
Method whole#
pub effect fn whole<'a, U>(self: &Self, text: string<'a>) -> Option<U>
! RegexError | OutOfMemoryError
? &mut AllocatorReturns the match that spans all of text as a U, or none.
Details#
As find, but the match must start at the beginning of text and end at its end, as if the
pattern were written ^(?:pattern)$.
Errors#
RegexErrorwithMatchLimitafter about 1,000,000 backtracking steps, never no match.OutOfMemoryErrorif the allocator cannot supply search storage.
Category: Text.
Profiles: aarch64-apple-darwin, aarch64-unknown-linux-gnu, aarch64-unknown-linux-gnu-no-libc, x86_64-unknown-linux-gnu, x86_64-unknown-linux-gnu-no-libc, wasm32-unknown-unknown, wasm32-wasip1, wasm32-wasip2, x86_64-pc-windows-msvc, wasm64-unknown-unknown.