Standard library · Text

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 \w never 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 letter b), no (?i), no lookahead and no back references (\1 means 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: Compile and every ...Str function throw an Error of kind Syntax with the code regex.invalid, a message such as group has no closing ')', and in offset the byte where the pattern goes wrong (minus one when the pattern is simply too long). Mark the call with try, 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.

regex-guide-validate.salam
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 throw:
    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")
end
Output
email sara.k@mail.example.com ok
email sara@localhost rejected
phone 09121234567 ok
phone 0912123456 rejected
postal 13145-67890 ok
postal 1314567890 ok
postal 13145 67890 rejected

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

regex-guide-logs.salam
import regex

func main throw:
    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")
end
Output
12:01:13 db: connection refused
skipped: not a log line
12:02:40 db: connection refused
INFO 1 WARN 1 ERROR 2

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

regex-guide-rewrite.salam
import regex

func main throw:
    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
end
Output
Invoice 2026-10-17, due 2026-11-01. Paid: no
Invoice 17/10/2026, due 01/11/2026. Paid: no
Invoice [2026-10-17], due 2026-11-01. Paid: no
4 ["red", "green", "blue", "yellow"]

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

regex-guide-user.salam
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)
end
Output
cat -> 3 match(es)
  at 0 cat
  at 4 cat
  at 15 cat
\w*cat\w* -> 3 match(es)
  at 0 cat
  at 4 catalog
  at 12 concat
[a-z]+og -> 2 match(es)
  at 4 catalog
  at 19 dog
bad pattern: cat( -> group has no closing ')' at byte 3
bad pattern: [a-z -> character class has no closing ']' at byte 0

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

regex-guide-persian.salam
import regex
import str

func show(label: str, found: Vector<str>):
    println label, found.Len(), "|", str.Join(found, ", ")
end

func main throw:
    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
Output
#\w+ finds 0 | 
#[^ ]+ finds 3 | #تهران, #اصفهان, #قطار_شبانه
هه+ finds 2 | هه, هه
ه(ه)+ finds 1 | ههههه
first city: تهران at byte 13

\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

JobFunction
Does the text have this shape?Match with ^...$
Where is the first match?Find, or FindMatch for the groups too
Every match as textFindAll, FindAllN for at most n
Every match with positions and groupsFindAllMatches
Read fields from one lineFindMatch then Group or GroupByName
Replace with fixed textReplace, ReplaceAll
Replace using the groupsReplaceExpand, ReplaceAllExpand
Break text on a separator patternSplit, SplitN
A pattern typed by a userCompile 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

Regex

#
struct Regex

A checked pattern, made with Compile. The functions that take one cannot fail. Built by hand with an invalid pattern, it never matches.

NameTypeDescription
patternstr = ""The text of the pattern.
regex-Compile.salam
import regex

func main throw:
    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.KindName(), e.code, e.offset, e.message
    end
end
Output
[0-9]+ true false
true 3
a# b22 c333
a# b# c#
true 7
bonana bonono
syntax error regex.invalid 0 character class has no closing ']'

MatchResult

#
struct MatchResult

The result of a search. Rather than reading the fields directly, the Group functions are usually simpler.

NameTypeDescription
okbool = falseTrue when a match was found.
startint = -1Where the match starts, in bytes.
stopint = -1Where the match ends, in bytes; that position is not part of it.
countint = 0The number of groups, not counting group zero.
textstr = ""The whole text that was searched, not only the part that matched. For the match itself use Group(m, 0).
patternstr = ""The pattern the search was made with.
gsint[]Where each group starts.
geint[]Where each group ends.
regex-Group.salam
import regex

func main throw:
    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")
end
Output
true 6 13 date: 2025-09
2 true
2025-09 2025 09
11 13
2 2025
2025-02
bbb
["2025-09", "2025", "09"]
["ab", "a", "b"]

Functions

Compile

#
func Compile(pattern: str): Throws<Regex>

Checks a pattern and wraps it in a 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): bool

True when the pattern is well formed and within the limits: at most 16 groups and repeat counts up to 64. The same check as Compile, 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

True when the pattern matches anywhere in the text. To match the whole text, anchor the pattern with ^ and $.

The example for this item is shown with the ones above: regex-Compile.salam

Find

#
func Find(re: Regex, text: str): int

Returns where the first match starts, in bytes, or minus one.

The example for this item is shown with the ones above: regex-Compile.salam

Replace

#
func Replace(re: Regex, text: str, replacement: str): str

Replaces only the first match with new text.

The example for this item is shown with the ones above: regex-Compile.salam

ReplaceAll

#
func ReplaceAll(re: Regex, text: str, replacement: str): str

Replaces every match with new text.

The example for this item is shown with the ones above: regex-Compile.salam

MatchStr

#
func MatchStr(pattern: str, text: str): Throws<bool>

Like 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>

Like 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>

Like 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>

Like 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

FindMatch

#
func FindMatch(re: Regex, text: str): MatchResult

Finds the first place the pattern matches and returns everything about it, groups included.

The example for this item is shown with the ones above: regex-Group.salam

FindMatchStr

#
func FindMatchStr(pattern: str, text: str): Throws<MatchResult>

Like 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): MatchResult

Like FindMatch, 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): int

Returns the number of groups in the pattern, not counting group zero.

The example for this item is shown with the ones above: regex-Group.salam

GroupOk

#
func GroupOk(m: MatchResult, i: int): bool

True when group number i 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): str

Returns the text of group number i; 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): int

Where the group starts, in bytes.

The example for this item is shown with the ones above: regex-Group.salam

GroupEnd

#
func GroupEnd(m: MatchResult, i: int): int

Where the group ends, in bytes.

The example for this item is shown with the ones above: regex-Group.salam

GroupIndex

#
func GroupIndex(m: MatchResult, name: str): int

Returns the number of a named group.

The example for this item is shown with the ones above: regex-Group.salam

GroupByName

#
func GroupByName(m: MatchResult, name: str): str

Returns the text of a named group.

The example for this item is shown with the ones above: regex-Group.salam

FindSubmatch

#
func FindSubmatch(re: Regex, text: str): Vector<str>

Returns the match and all its groups in a vector; element zero is the whole match.

The example for this item is shown with the ones above: regex-Group.salam

FindSubmatchStr

#
func FindSubmatchStr(pattern: str, text: str): Throws<Vector<str>>

Like 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>

Returns every match with its details. A limit of minus one means no limit.

regex-FindAll.salam
import regex

func main throw:
    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
end
Output
["1403", "7", "12"]
["1403", "7"]
["one", "two", "three"]
["a", "b", "c", "d"]
["a", "b,c,d"]
["2025", "09", "29"]
1403 5 9
7 17 18
12 24 26

FindAllN

#
func FindAllN(re: Regex, text: str, limit: int): Vector<str>

Returns the text of at most 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>

Returns the text of every match in a vector.

The example for this item is shown with the ones above: regex-FindAll.salam

FindAllStr

#
func FindAllStr(pattern: str, text: str): Throws<Vector<str>>

Like 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>

Splits the text wherever the pattern matches, into at most 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>

Splits the text wherever the pattern matches. For separators with varying space around them it is more flexible than 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>>

Like 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

Fills a template from the groups of a match; $1, $2 and so on stand for the groups.

regex-Expand.salam
import regex

func main throw:
    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")
end
Output
home <- ali
home:ali, sara@work
home:ali, work:sara
world hello
baba

ReplaceExpand

#
func ReplaceExpand(re: Regex, text: str, template: str): str

Replaces the first match with the template, in which you can use $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): str

Replaces every match with the template.

The example for this item is shown with the ones above: regex-Expand.salam

ReplaceExpandStr

#
func ReplaceExpandStr(pattern: str, text: str, template: str): Throws<str>

Like 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>

Like 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