Regex.Match
Standard library struct · Nested in Regex, made by find and find_all
A Regex.Match is one piece of text that a Regex found: what it found, where, and, if
the pattern has groups, what each group caught. A program doesn’t make one itself; it comes from
find, find_all, or the block of replace_each.
const found = Regex('\d+').find("room 42, floor 7")print(found)print(found?.text)print(found?.start)print(found?.end)Regex.Match("42" at 5..<7)4257A match prints with its text and where it is, as above. Positions count characters, as indexing does,
so text[found.start..<found.end] is found.text.
At a glance
Section titled “At a glance”| Where | |
|---|---|
text, start, end |
What was found, and where |
| Groups | |
|---|---|
group(number), group_maybe(number) |
A group by its number |
named(name), named_maybe(name) |
A group by its name |
The text that matched, and where it is: start is the position of its first character, and end is the
position just after its last. Each is read without parentheses.
const found = Regex('[a-z]+').find("123 abc 456")print(found?.text)print(found?.start, found?.end)abc4 7Groups
Section titled “Groups”A group is part of a pattern in parentheses, which remembers the text it matched. Groups are
numbered from the left by their opening parenthesis. Group 0 is always the whole match, so in
((\w+)@(\w+)), group 1 is the whole address and groups 2 and 3 are its two parts.
The text a group matched.
const found = Regex('(\w+)@(\w+)').find("mail ada@example now")print(found?.group(0))print(found?.group(1))print(found?.group(2))ada@exampleadaexampleA group repeated with * or + holds what it matched the last time round.
Raises a RegexError when the group took no part in the match, such as (x)? with no
x to match, or the branch not taken in (a)|(b). It is also raised when the pattern has no such group;
the message says which groups it does have.
group_maybe(number: Int): String?
Like group, but gives nothing for a group that took no part in the match. Asking for a group the
pattern doesn’t have still raises an error, since that is always a mistake.
const found = Regex('(a)|(b)').find("b")print(found?.group_maybe(1))print(found?.group_maybe(2))nothingbThe text of the group written (?<name>...). Naming groups makes a pattern easier to read, and the code
that uses it too.
const date = Regex('(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})').find("on 2026-09-25.")print(date?.named("year"))print(date?.named("month"))print(date?.named("day"))20260925Raises a RegexError in the same cases as group, naming the groups the pattern
has.
named_maybe(name: String): String?
Like named, but gives nothing for a group that took no part in the match.
const found = Regex('(?<unit>cm)?\d+').find("42")print(found?.named_maybe("unit"))nothing