Skip to content

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)
Output
Regex.Match("42" at 5..<7)
42
5
7

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

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

text: String

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)
Output
abc
4 7

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.

group(number: Int): String

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))
Output
ada@example
ada
example

A 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))
Output
nothing
b

named(name: String): String

The 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"))
Output
2026
09
25

Raises 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"))
Output
nothing