Skip to content

Regex ​

Regex is a native tyrus type. It represents a compiled regular expression and is written with a /pattern/flags literal.

Construction ​

tyrus
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.

Signaturetest(str: string): boolean
tyrus
const matched: boolean = /cat/.test("a cat");
print(matched); // true

exec() ​

Returns the first match and its captures, or an absent value when no match exists.

Signatureexec(str: string): string[]?
tyrus
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.

SignatureexecAll(str: string): string[][]?
tyrus
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.

SignaturetoString(): string
tyrus
const text: string = /cat/i.toString();
print(text); // /cat/i

String methods with Regex ​

match() ​

Returns the first match and its captures, or an absent value when the string does not match.

Signaturematch(re: Regex): string[]?
tyrus
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.

SignaturematchAll(re: Regex): string[][]?
tyrus
const matches: string[][]? = "one two".matchAll(/\w+/);

if (matches) {
    print(matches[1][0]); // two
}

Returns the start index of the first match, or -1 when the string does not match.

Signaturesearch(re: Regex): i32
tyrus
const index: i32 = "a cat".search(/cat/);
print(index); // 2

replace() ​

Replaces the first match with the replacement string.

Signaturereplace(re: Regex, replacement: string): string
tyrus
const masked: string = "[email protected]".replace(/@.+$/, "@example.test");
print(masked); // [email protected]

split() ​

Splits the string at every non-overlapping match.

Signaturesplit(re: Regex): string[]
tyrus
const parts: string[] = "one,two".split(/,/);
print(parts[1]); // two

Limitations ​

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.