Skip to content
Kavachकवच

Standard Library: std.regex

● Intermediate5 min

Every type, method and function of std.regex: what the spec lists, then each declaration in its source, with its examples and the line that declares it.

Spec 14.8 · learn it in Regex.

A declaration below shows what a program writes against: a type's fields, a function's parameters, what it gives, its contracts (require, ensure) and its examples. kavach test runs every example, so each one is true of the code.

What the spec lists

Regular expressions, with two engines:

FunctionGives
regex.new(pattern) -> Regex ! RegexErrorA pattern for the linear-time engine: matching takes time proportional to the text, whatever the pattern and the text. Safe for patterns and text from users
regex.advanced(pattern) -> Regex ! RegexErrorAlso allows lookahead and lookbehind ((?=…), (?<!…)) and backreferences (\1). These can take very long on some text, so matching gives up after a fixed amount of work

Methods of Regex:

MethodGives
is_match(text)Whether the pattern matches anywhere in text
find(text)The first match, or none
find_all(text)Every match that doesn't overlap the one before
captures(text)For the first match: the whole match then each group, none for a group that didn't take part; or none without a match
named_captures(text)For the first match: each named group that took part, by name; or none
replace(text, with), replace_all(text, with)The text with the first or every match replaced; in with, $1 and ${name} insert a group (write with as a raw string, r"${name}", so {…} is not interpolation)
split(text)The parts of text between matches

Everything in std.regex is built into the compiler and runtime, so the spec's tables above are the whole of it.