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.
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
funcmain 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 {} asHashMap<str, int>
each line in lines:
m := regex.FindMatch(re, line)
ifnot m.ok:
println"skipped:", line
continueend
level := regex.GroupByName(m, "level")
if counts.Has(level):
counts.Put(level, counts.Get(level) + 1)
else:
counts.Put(level, 1)
endif level == "ERROR":
println regex.GroupByName(m, "time"), regex.GroupByName(m, "msg")
endendprintln"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
funcmain 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
funcsearch(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)
endcatch e:
println"bad pattern:", pattern, "->", e.message, "at byte", e.offset
endendfuncmain:
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
importstrfuncshow(label: str, found: Vector<str>):
println label, found.Len(), "|", str.Join(found, ", ")
endfuncmain 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
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.
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.
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.