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
| Function | Signature | Description |
|---|---|---|
match | regex.match(pattern: string, s: string) → bool | Whether pattern matches anywhere in s |
find | regex.find(pattern: string, s: string) → string | First match, or empty string if none |
findAll | regex.findAll(pattern: string, s: string) → string[] | All non-overlapping matches |
replace | regex.replace(pattern: string, s: string, repl: string) → string | Replace all matches with repl |
split | regex.split(pattern: string, s: string) → string[] | Split s on every match of pattern |
groups | regex.groups(pattern: string, s: string) → string[] | First match’s capture groups (index 0 is the whole match); empty if no match |
findAllGroups | regex.findAllGroups(pattern: string, s: string) → string[] | All matches’ groups flattened; stride is groupCount + 1 |
groupCount | regex.groupCount(pattern: string) → int | Number of capture subgroups, excluding group 0 |
valid | regex.valid(pattern: string) → bool | Whether pattern compiles |
escape | regex.escape(s: string) → string | Escape 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