regex
Searching and replacing with a pattern: finding a number, an email address or a date in text and pulling it apart.
import regex
A regular expression is a small language for describing the shape of text; [0-9]+ means "one or more digits". With one you can ask whether text matches a pattern, find every place it matches, and pull pieces out or replace them.
Every function comes in two forms: one takes a Regex made with Compile, and its twin whose name ends in Str takes the pattern as text. They do the same work. Compile checks the pattern and throws when it is not valid, so a Regex in hand always works and the functions that take one cannot fail; the Str twins check the pattern on every call and throw the same way. A Regex value is about naming the pattern once, not about speed.
Use it for patterns: validation, pulling fields out of log lines, rewriting. For a fixed piece of text, the plain functions of str (Contains, Index, Replace, Split) are simpler and faster. For whole-word, Unicode-aware work on Persian text, see unicode.
Parentheses in a pattern make a "group", and (?P<name>...) makes a named one. Group zero is the whole match. In a replacement, $1 and $2 stand for the groups.
Limits that cause surprises
- The engine works on bytes.
.and every class match one byte, so\wnever matches a Persian letter, a range such as[آ-ی]does not work, andب+repeats only the last byte ofب. Put a Persian letter in a group to repeat it,(ب)+, or use a negated class such as[^ ]+. Literal Persian words and alternatives such as(تهران|شیراز)work. - No
\b(it means the letterb), no(?i), no lookahead and no back references (\1means the digit 1).^and$are the start and end of the whole text, never of a line. - At most 16 groups, and a repeat count of at most 64:
a{100}is an invalid pattern. - An invalid pattern is an error, not a pattern that never matches:
Compileand every...Strfunction throw an Error of kindSyntaxwith the coderegex.invalid, a message such asgroup has no closing ')', and inoffsetthe byte where the pattern goes wrong (minus one when the pattern is simply too long). Mark the call withtry, or catch it where the pattern comes from a user. - A match that would take more than 400000 steps is given up and reported as no match. Nested repetition such as
(a+)+on long input can hit that limit. - The functions keep state in globals, so do not use this package from several threads at once.
Checking input
The most common job is deciding whether a value has the right shape: an email address, a phone number, a postal code. Match is true when the pattern matches anywhere in the text, so a pattern used for validation must start with ^ and end with $; otherwise "abc 09121234567 xyz" would pass as a phone number. Giving each pattern a name with Compile, outside the loop or the request handler, keeps them in one place.
import regex
func check(name: str, re: regex.Regex, value: str):
if regex.Match(re, value):
println name, value, "ok"
else:
println name, value, "rejected"
end
end
func main throws:
email := try regex.Compile("^[a-z0-9._]+@[a-z0-9-]+(\\.[a-z0-9-]+)+$")
phone := try regex.Compile("^09[0-9]{9}$")
postal := try regex.Compile("^[0-9]{5}-?[0-9]{5}$")
check("email", email, "sara.k@mail.example.com")
check("email", email, "sara@localhost")
check("phone", phone, "09121234567")
check("phone", phone, "0912123456")
check("postal", postal, "13145-67890")
check("postal", postal, "1314567890")
check("postal", postal, "13145 67890")
endA pattern like this checks shape, not truth: an address that passes may still not exist. For an email the only real test is sending a message to it.
Pulling fields out of lines
Named groups turn a line of text into fields. FindMatch returns a MatchResult; its ok field says whether the line matched at all, and GroupByName reads one field by its name. Checking ok first matters: a line in an unexpected format should be skipped or reported, not read as empty fields.
import regex
func main throws:
lines := ["2026-10-01 12:00:01 INFO server started on :8080",
"2026-10-01 12:00:07 WARN slow query took 1200ms",
"2026-10-01 12:01:13 ERROR db: connection refused",
"not a log line",
"2026-10-01 12:02:40 ERROR db: connection refused"]
re := try regex.Compile("^(?P<date>[0-9-]+) (?P<time>[0-9:]+) (?P<level>[A-Z]+) (?P<msg>.*)$")
counts := HashMap {} as HashMap<str, int>
each line in lines:
m := regex.FindMatch(re, line)
if not m.ok:
println "skipped:", line
continue
end
level := regex.GroupByName(m, "level")
if counts.Has(level):
counts.Put(level, counts.Get(level) + 1)
else:
counts.Put(level, 1)
end
if level == "ERROR":
println regex.GroupByName(m, "time"), regex.GroupByName(m, "msg")
end
end
println "INFO", counts.Get("INFO"), "WARN", counts.Get("WARN"), "ERROR", counts.Get("ERROR")
endRewriting text
ReplaceAll puts the same text in place of every match, which is enough for collapsing runs of spaces. When the replacement depends on what was matched, use ReplaceAllExpand: in its template $1, $2 and so on are the groups and $0 is the whole match. Here a date written year first is turned around, and only the first date is marked. Split with a character class breaks text on any mix of separators.
import regex
func main throws:
text := "Invoice 2026-10-17, due 2026-11-01. Paid: no"
tidy := try regex.ReplaceAllStr("[ \t]+", text, " ")
println tidy
dates := try regex.Compile("([0-9]{4})-([0-9]{2})-([0-9]{2})")
println regex.ReplaceAllExpand(dates, tidy, "$3/$2/$1")
println regex.ReplaceExpand(dates, tidy, "[$0]")
words := regex.Split(try regex.Compile("[ ,.:]+"), "red, green. blue: yellow")
println words.Len(), words
endPatterns that come from users
When the pattern itself is typed by a user, for a search box or a filter rule, call Compile inside try: and show the error's message and offset when it fails; IsValid answers the same question with a plain yes or no. FindAllMatches then gives the position of each match in bytes, which is what you need to highlight the matched words.
import regex
func search(pattern: str, text: str):
try:
re := regex.Compile(pattern)
found := regex.FindAllMatches(re, text, -1)
println pattern, "->", found.Len(), "match(es)"
each m in found:
println " at", m.start, regex.Group(m, 0)
end
catch e:
println "bad pattern:", pattern, "->", e.message, "at byte", e.offset
end
end
func main:
text := "cat catalog concat dog"
search("cat", text)
search("\\w*cat\\w*", text)
search("[a-z]+og", text)
search("cat(", text)
search("[a-z", text)
endThe engine supports the common syntax: classes such as [a-z], the shorthands \d, \w and \s with their capital opposites, repetition with *, +, ? and {n,m}, alternation with |, and plain and named groups. There is no (?i) flag; for a case-insensitive search, lower-case the text with str first and write the pattern in lower case. Positions are in bytes, so a Persian letter takes two of them.
Persian text
Because the engine matches bytes, a pattern for Persian text needs a little care. This program pulls hashtags out of a post, shortens a stretched word and finds a city name.
import regex
import str
func show(label: str, found: Vector<str>):
println label, found.Len(), "|", str.Join(found, ", ")
end
func main throws:
post := "سفر به #تهران و #اصفهان با #قطار_شبانه"
show("#\\w+ finds", try regex.FindAllStr("#\\w+", post))
show("#[^ ]+ finds", try regex.FindAllStr("#[^ ]+", post))
show("هه+ finds", try regex.FindAllStr("هه+", "عالیههههه"))
show("ه(ه)+ finds", try regex.FindAllStr("ه(ه)+", "عالیههههه"))
city := try regex.FindMatchStr("(تهران|اصفهان|شیراز)", post)
println "first city:", regex.Group(city, 0), "at byte", city.start
end\w only knows ASCII letters, digits and _, so #\w+ finds nothing; "anything up to a space" with [^ ]+ works for any script. هه+ finds two pieces because the + applies to the second byte of ه only; the group in ه(ه)+ repeats the whole letter. The position 13 is in bytes: the five Persian letters before the city name take two bytes each, and the two spaces and the # one each.
Which function for which job
| Job | Function |
|---|---|
| Does the text have this shape? | Match with ^...$ |
| Where is the first match? | Find, or FindMatch for the groups too |
| Every match as text | FindAll, FindAllN for at most n |
| Every match with positions and groups | FindAllMatches |
| Read fields from one line | FindMatch then Group or GroupByName |
| Replace with fixed text | Replace, ReplaceAll |
| Replace using the groups | ReplaceExpand, ReplaceAllExpand |
| Break text on a separator pattern | Split, SplitN |
| A pattern typed by a user | Compile inside try:, or IsValid |
Every one of these has a ...Str twin that takes the pattern as text, behaves the same and throws for an invalid pattern.
Types
MatchResult
struct MatchResult| Name | Type | Description |
|---|---|---|
ok | bool = false | True when a match was found. |
start | int = -1 | Where the match starts, in bytes. |
stop | int = -1 | Where the match ends, in bytes; that position is not part of it. |
count | int = 0 | The number of groups, not counting group zero. |
text | str = "" | The whole text that was searched, not only the part that matched. For the match itself use Group(m, 0). |
pattern | str = "" | The pattern the search was made with. |
gs | int[] | Where each group starts. |
ge | int[] | Where each group ends. |
import regex
func main throws:
r := try regex.Compile("(?P<year>[0-9]{4})-(?P<month>[0-9]{2})")
m := regex.FindMatch(r, "date: 2025-09")
println m.ok, m.start, m.stop, m.text
println regex.GroupCount(m), regex.GroupOk(m, 1)
println regex.Group(m, 0), regex.Group(m, 1), regex.Group(m, 2)
println regex.GroupStart(m, 2), regex.GroupEnd(m, 2)
println regex.GroupIndex(m, "month"), regex.GroupByName(m, "year")
m2 := regex.FindMatchFrom(r, "2024-01 and 2025-02", 5)
println regex.Group(m2, 0)
println regex.Group(try regex.FindMatchStr("b+", "aabbbc"), 0)
println regex.FindSubmatch(r, "2025-09")
println try regex.FindSubmatchStr("(a)(b)", "xab")
endRegex
struct RegexCompile. The functions that take one cannot fail. Built by hand with an invalid pattern, it never matches.| Name | Type | Description |
|---|---|---|
pattern | str = "" | The text of the pattern. |
import regex
func main throws:
r := try regex.Compile("[0-9]+")
println r.pattern, regex.IsValid("[0-9]+"), regex.IsValid("[0-9")
println regex.Match(r, "abc123"), regex.Find(r, "abc123")
println regex.Replace(r, "a1 b22 c333", "#")
println regex.ReplaceAll(r, "a1 b22 c333", "#")
println try regex.MatchStr("^[a-z]+$", "salam"), try regex.FindStr("o", "salam donya")
println try regex.ReplaceStr("a", "banana", "o"), try regex.ReplaceAllStr("a", "banana", "o")
try:
bad := regex.Compile("[0-9")
println bad.pattern
catch e:
println e.kind_name(), e.code, e.offset, e.message
end
endFunctions
FindMatch
func FindMatch(re: Regex, text: str): MatchResultThe example for this item is shown with the ones above: regex-Group.salam
FindMatchStr
func FindMatchStr(pattern: str, text: str): Throws<MatchResult>FindMatch, with the pattern as text. Throws Syntax for an invalid pattern.The example for this item is shown with the ones above: regex-Group.salam
FindMatchFrom
func FindMatchFrom(re: Regex, text: str, from: int): MatchResultFindMatch, but starts the search at byte from, for finding the next occurrence.The example for this item is shown with the ones above: regex-Group.salam
GroupCount
func GroupCount(m: MatchResult): intThe example for this item is shown with the ones above: regex-Group.salam
GroupOk
func GroupOk(m: MatchResult, i: int): booli took part in this match. An optional group may stay empty.The example for this item is shown with the ones above: regex-Group.salam
Group
func Group(m: MatchResult, i: int): stri; group zero is the whole match.The example for this item is shown with the ones above: regex-Group.salam
GroupStart
func GroupStart(m: MatchResult, i: int): intThe example for this item is shown with the ones above: regex-Group.salam
GroupEnd
func GroupEnd(m: MatchResult, i: int): intThe example for this item is shown with the ones above: regex-Group.salam
GroupIndex
func GroupIndex(m: MatchResult, name: str): intThe example for this item is shown with the ones above: regex-Group.salam
GroupByName
func GroupByName(m: MatchResult, name: str): strThe example for this item is shown with the ones above: regex-Group.salam
FindSubmatch
func FindSubmatch(re: Regex, text: str): Vector<str>The example for this item is shown with the ones above: regex-Group.salam
FindSubmatchStr
func FindSubmatchStr(pattern: str, text: str): Throws<Vector<str>>FindSubmatch, with the pattern as text. Throws Syntax for an invalid pattern.The example for this item is shown with the ones above: regex-Group.salam
FindAllMatches
func FindAllMatches(re: Regex, text: str, limit: int): Vector<MatchResult>limit of minus one means no limit.import regex
func main throws:
r := try regex.Compile("[0-9]+")
text := "year 1403, month 7, day 12"
println regex.FindAll(r, text)
println regex.FindAllN(r, text, 2)
println try regex.FindAllStr("[a-z]+", "one two three")
println regex.Split(try regex.Compile(" *, *"), "a , b,c , d")
println regex.SplitN(try regex.Compile(","), "a,b,c,d", 2)
println try regex.SplitStr("-+", "2025--09---29")
all := regex.FindAllMatches(r, text, -1)
each m in all:
println regex.Group(m, 0), m.start, m.stop
end
endFindAllN
func FindAllN(re: Regex, text: str, limit: int): Vector<str>limit matches.The example for this item is shown with the ones above: regex-FindAll.salam
FindAll
func FindAll(re: Regex, text: str): Vector<str>The example for this item is shown with the ones above: regex-FindAll.salam
FindAllStr
func FindAllStr(pattern: str, text: str): Throws<Vector<str>>FindAll, with the pattern as text. Throws Syntax for an invalid pattern.The example for this item is shown with the ones above: regex-FindAll.salam
SplitN
func SplitN(re: Regex, text: str, limit: int): Vector<str>limit pieces; the last piece is the rest of the text.The example for this item is shown with the ones above: regex-FindAll.salam
Split
func Split(re: Regex, text: str): Vector<str>str.Split.The example for this item is shown with the ones above: regex-FindAll.salam
SplitStr
func SplitStr(pattern: str, text: str): Throws<Vector<str>>Split, with the pattern as text. Throws Syntax for an invalid pattern.The example for this item is shown with the ones above: regex-FindAll.salam
Expand
func Expand(m: MatchResult, template: str): str$1, $2 and so on stand for the groups.import regex
func main throws:
r := try regex.Compile("([a-z]+)@([a-z]+)")
text := "ali@home, sara@work"
m := regex.FindMatch(r, text)
println regex.Expand(m, "$2 <- $1")
println regex.ReplaceExpand(r, text, "$2:$1")
println regex.ReplaceAllExpand(r, text, "$2:$1")
println try regex.ReplaceExpandStr("(\\w+) (\\w+)", "hello world", "$2 $1")
println try regex.ReplaceAllExpandStr("(a)(b)", "abab", "$2$1")
endReplaceExpand
func ReplaceExpand(re: Regex, text: str, template: str): str$1 and the rest.The example for this item is shown with the ones above: regex-Expand.salam
ReplaceAllExpand
func ReplaceAllExpand(re: Regex, text: str, template: str): strThe example for this item is shown with the ones above: regex-Expand.salam
ReplaceExpandStr
func ReplaceExpandStr(pattern: str, text: str, template: str): Throws<str>ReplaceExpand, with the pattern as text. Throws Syntax for an invalid pattern.The example for this item is shown with the ones above: regex-Expand.salam
ReplaceAllExpandStr
func ReplaceAllExpandStr(pattern: str, text: str, template: str): Throws<str>ReplaceAllExpand, with the pattern as text. Throws Syntax for an invalid pattern.The example for this item is shown with the ones above: regex-Expand.salam
Compile
func Compile(pattern: str): Throws<Regex>Regex. Throws an Error of kind Syntax with the code regex.invalid when the pattern is not valid or is over the limits; offset is the byte where it goes wrong, or minus one when the whole pattern is too long.The example for this item is shown with the ones above: regex-Compile.salam
IsValid
func IsValid(pattern: str): boolCompile, without the error.The example for this item is shown with the ones above: regex-Compile.salam
Match
func Match(re: Regex, text: str): bool^ and $.The example for this item is shown with the ones above: regex-Compile.salam
Find
func Find(re: Regex, text: str): intThe example for this item is shown with the ones above: regex-Compile.salam
Replace
func Replace(re: Regex, text: str, replacement: str): strThe example for this item is shown with the ones above: regex-Compile.salam
ReplaceAll
func ReplaceAll(re: Regex, text: str, replacement: str): strThe example for this item is shown with the ones above: regex-Compile.salam
MatchStr
func MatchStr(pattern: str, text: str): Throws<bool>Match, with the pattern as text. Throws Syntax for an invalid pattern.The example for this item is shown with the ones above: regex-Compile.salam
FindStr
func FindStr(pattern: str, text: str): Throws<int>Find, with the pattern as text. Throws Syntax for an invalid pattern.The example for this item is shown with the ones above: regex-Compile.salam
ReplaceStr
func ReplaceStr(pattern: str, text: str, replacement: str): Throws<str>Replace, with the pattern as text. Throws Syntax for an invalid pattern.The example for this item is shown with the ones above: regex-Compile.salam
ReplaceAllStr
func ReplaceAllStr(pattern: str, text: str, replacement: str): Throws<str>ReplaceAll, with the pattern as text. Throws Syntax for an invalid pattern.The example for this item is shown with the ones above: regex-Compile.salam