regex

The regex module runs regular expressions over strings — testing for matches, extracting matches and capture groups, replacing, splitting, and validating or escaping patterns. Compiled patterns are cached, so reusing the same pattern is cheap. Import it with import regex.

Functions

FunctionSignatureDescription
matchregex.match(pattern: string, s: string) → boolWhether pattern matches anywhere in s
findregex.find(pattern: string, s: string) → stringFirst match, or empty string if none
findAllregex.findAll(pattern: string, s: string) → string[]All non-overlapping matches
replaceregex.replace(pattern: string, s: string, repl: string) → stringReplace all matches with repl
splitregex.split(pattern: string, s: string) → string[]Split s on every match of pattern
groupsregex.groups(pattern: string, s: string) → string[]First match’s capture groups (index 0 is the whole match); empty if no match
findAllGroupsregex.findAllGroups(pattern: string, s: string) → string[]All matches’ groups flattened; stride is groupCount + 1
groupCountregex.groupCount(pattern: string) → intNumber of capture subgroups, excluding group 0
validregex.valid(pattern: string) → boolWhether pattern compiles
escaperegex.escape(s: string) → stringEscape literal text for use inside a pattern

Example

import regex

let line = "user=alice id=42"
if regex.match("id=\\d+", line) {
    let g = regex.groups("(\\w+)=(\\w+)", line)
    print(g[1] + " -> " + g[2])         // user -> alice
}

let words = regex.findAll("\\w+", "one two three")
print(strings.join(words, ","))         // one,two,three
Standard library · View as Markdown · llms-full.txt