Julia Regex Tutorial
last modified November 18, 2026
A regular expression, often shortened to regex, is a compact pattern
for describing text. Patterns such as \d+ (one or more digits)
or \w+ (one or more word characters) let us find, validate, and
rewrite text without writing long loops of character checks. Julia implements
regular expressions in its standard library and integrates them with string
functions.
This tutorial covers regex literals, single and repeated matches, capturing
and named groups, and regex-aware versions of occursin,
findfirst, replace, and split. The
examples were verified with Julia 1.13.4.
Regex Literals and the Regex Constructor
The usual way to write a pattern is the r"..." literal. It is a
raw string: backslashes are passed to the regex engine unchanged, so
we write \d rather than having to escape the backslash for the
string syntax. The Regex constructor builds the same object from
an ordinary string.
p = r"\d+"
println(p)
println(typeof(p))
q = Regex("a+b")
println(q)
println(typeof(q))
Both p and q have type Regex. Printing
a regex shows it in literal form, with the surrounding r" and
quote. The pattern \d+ matches a run of digits: \d
means a digit and the + quantifier means "one or more of the
previous item".
$ julia main.jl r"\d+" Regex r"a+b" Regex
match
The match function searches for the first occurrence of a
pattern. It returns a RegexMatch object when the pattern is
found and nothing otherwise. A match object exposes the matched
text in .match and its starting byte position in
.offset.
m = match(r"\d+", "abc123def") println(m) println(m.match) println(m.offset) println(match(r"\d+", "abcdef"))
The first four digits of the result are "123", beginning at byte
offset four. Julia indices start at one, which is why the offset is four and
not three. The final call finds no digits and prints nothing; a
program should test for that value before using the match.
$ julia main.jl
RegexMatch("123")
123
4
nothing
eachmatch
The eachmatch function returns an iterator over all
non-overlapping matches. Each step yields a RegexMatch object,
so a for loop can handle every occurrence in turn.
for m in eachmatch(r"\d+", "a12 b345 c6")
println("$(m.match) at $(m.offset)")
end
Three groups of digits are found: 12, 345, and
6. The offsets point to their first bytes. Because
eachmatch is lazy, it does not build an array of results; the
matches are produced as the loop requests them.
$ julia main.jl 12 at 2 345 at 6 6 at 11
Capturing Groups
Parentheses in a pattern create a capturing group: a subpattern whose
matched text is remembered separately. The .captures field holds
one entry per group, and a match object can also be indexed with a number to
read a group directly.
m = match(r"(\w+)@(\w+)\.com", "alice@example.com") println(m.captures) println(m[1]) println(m[2]) println(match(r"(\w+)@(\w+)\.com", "bad address"))
The two parenthesized parts capture "alice" and
"example". The literal dot in the pattern is written
\., because an unescaped dot would match any character. The
printed type of .captures is a union with Nothing
because an optional group may capture nothing; here both groups matched. An
input that fails to match produces nothing instead of a match
object.
$ julia main.jl
Union{Nothing, SubString{String}}["alice", "example"]
alice
example
nothing
Named Groups
Groups can be given names with the (?<name>...) syntax. A
named group is read with m[:name], which is easier to remember
than a group number and keeps working when the pattern is edited.
m = match(r"(?<user>\w+)@(?<host>\w+)\.com", "alice@example.com") println(m[:user]) println(m[:host]) println(m.captures)
The names user and host label the two groups. They
do not change the captures themselves: .captures still contains
the same two strings in order. Named groups become especially useful in
longer patterns where counting parentheses would be error-prone.
$ julia main.jl
alice
example
Union{Nothing, SubString{String}}["alice", "example"]
occursin and findfirst with Regex
Several string functions accept a regex in place of a literal substring.
occursin answers whether the pattern appears at all, while
findfirst reports the range of indices it occupies. A flag
written after the closing quote makes the match case-insensitive; the
i flag is the one used here.
println(occursin(r"julia", "Julia programming")) println(occursin(r"julia"i, "Julia programming")) println(findfirst(r"\d+", "abc123def"))
The plain pattern does not match the capitalized Julia, so the
first line is false. Adding the i flag makes the
second line true. The third line shows the digits at byte
positions four through six, returned as the range 4:6.
$ julia main.jl false true 4:6
replace with Regex
The replace function accepts a pattern as the left side of its
pair, so every substring matching the pattern can be rewritten at once. A
replacement written as s"..." is a substitution string:
inside it, \1 refers to the text captured by the first group,
\2 to the second, and so on.
s = "a b\tc d"
println(replace(s, r"\s+" => " "))
println(replace("ab12cd34", r"(\d+)" => s"[\1]"))
In the first call \s+ matches runs of whitespace, including the
tab, and each run becomes a single space. In the second call the pattern
captures each run of digits and s"[\1]" surrounds the captured
text with square brackets. Ordinary strings would not interpret
\1 as a backreference.
$ julia main.jl a b c d ab[12]cd[34]
split with Regex
When the separators in text vary, a regex is more convenient than a single
delimiter string. The split function accepts a pattern and cuts
the string at every match, returning SubString pieces.
println(split("a,b; c d", r"[,;\s]+"))
println(split("one;two|three", r"[;|]"))
The character class [,;\s]+ matches one or more commas,
semicolons, or whitespace characters, so the first string is split into four
words. The class [;|] matches either a semicolon or a pipe,
giving the three fields in the second result.
$ julia main.jl
SubString{String}["a", "b", "c", "d"]
SubString{String}["one", "two", "three"]
Anchors and Alternation
An anchor checks a position rather than a character:
^ means the start of the string and $ means its end.
The vertical bar is alternation, which matches either the pattern on
the left or the one on the right.
println(match(r"^Julia", "Julia is great") !== nothing) println(match(r"^Julia", "I like Julia") !== nothing) println(match(r"\.jl$", "main.jl") !== nothing) println(match(r"cat|dog", "a dog and a cat").match)
The first pattern matches only when the string actually begins with
Julia; the second string mentions Julia but does not begin with
it. The third pattern checks a .jl suffix, and the fourth finds
whichever alternative occurs first, which is dog. Comparing a
match with nothing using !== turns the result into a
plain boolean.
$ julia main.jl true false true dog
Extracting Data with Named Groups
Named groups and eachmatch work well together: we can scan a
whole sentence and label each piece of data as we go. This is a common
pattern for extracting structured information from log files or messages.
text = "Contact: alice@example.com or bob@example.org"
for m in eachmatch(r"(?<user>\w+)@(?<host>\w+\.\w+)", text)
println("$(m[:user]) -> $(m[:host])")
end
The pattern captures a word before the @ sign and a domain made
of two word pieces separated by a dot after it. The loop prints each address
split into its user and host parts. Using names makes the intent of the
pattern clear even though it contains several groups.
$ julia main.jl alice -> example.com bob -> example.org
Source
Julia Regular Expressions documentation
In this article we have worked with regular expressions in Julia: regex
literals and the Regex constructor, match and
eachmatch, capturing and named groups, plus regex versions of
occursin, findfirst, replace, and
split. Plain string operations are covered in
Julia string functions and string
basics in Julia strings.
Author
List all Julia tutorials.