Regex
Regex is a native tyrus type. It represents a compiled regular expression and is written with a /pattern/flags literal.
Construction
const slug: Regex = /^[a-z0-9-]+$/i;Patterns and flags are validated during type checking. new is not part of Regex construction.
Flags
Supported flags are i for case-insensitive matching, m for multiline anchors, s for dot-all and x for free-spacing mode. The flags g, u, y and d are not supported.
Methods
test()
Returns whether the pattern matches anywhere in a string.
test(str: string): booleanconst matched: boolean = /cat/.test("a cat");
print(matched); // trueexec()
Returns the first match and its captures, or an absent value when no match exists.
exec(str: string): string[]?const match: string[]? = /(c)(at)/.exec("a cat");
if (match) {
print(match[0]); // cat
print(match[1]); // c
}execAll()
Returns all non-overlapping matches and their captures, or an absent value when no match exists.
execAll(str: string): string[][]?const matches: string[][]? = /\w+/.execAll("one two");
if (matches) {
print(matches[0][0]); // one
print(matches[1][0]); // two
}toString()
Returns the slash-delimited pattern and active flags.
toString(): stringconst text: string = /cat/i.toString();
print(text); // /cat/iString methods with Regex
match()
Returns the first match and its captures, or an absent value when the string does not match.
match(re: Regex): string[]?const match: string[]? = "a cat".match(/(c)(at)/);
if (match) {
print(match[0]); // cat
}matchAll()
Returns all non-overlapping matches and their captures, or an absent value when the string does not match.
matchAll(re: Regex): string[][]?const matches: string[][]? = "one two".matchAll(/\w+/);
if (matches) {
print(matches[1][0]); // two
}search()
Returns the start index of the first match, or -1 when the string does not match.
search(re: Regex): i32const index: i32 = "a cat".search(/cat/);
print(index); // 2replace()
Replaces the first match with the replacement string.
replace(re: Regex, replacement: string): stringconst masked: string = "[email protected]".replace(/@.+$/, "@example.test");
print(masked); // [email protected]split()
Splits the string at every non-overlapping match.
split(re: Regex): string[]const parts: string[] = "one,two".split(/,/);
print(parts[1]); // twoLimitations
Regex values are immutable. There is no mutable lastIndex, no g flag, no well-known symbol hooks, no match-result object, and no look-around or backreferences.
