Julia Regular Expressions
A regular expression describes a pattern for string matching; it can be used to check whether a string contains a certain substring, replace a matched substring, or extract a substring that meets certain conditions from a string.
Julia uses the PCRE library and supports regular expressions compatible with Perl (Perl-Compatible Regular Expressions).
In Julia, regular expressions are created with the non-standard string literal of the form r"..."; inside a regex literal no string interpolation or escaping is done (except for double quotes):
Example
julia
re = r
"^\s*(?:#|$)"
r
"^\s*(?:#|$)"
julia
typeof
(
re
)
Regex
Common operations on regular expressions fall into three categories:
| Operation | function | Description |
|---|---|---|
| Determine whether it matches | occursin(re, str) |
Return true or false |
| Find the matched content | match(re, str), eachmatch(re, str) |
Return the match object or an iterator |
| Replace the matched content | replace(str, re => new) |
Replace the matched part with new content |
Checking a Match: occursin
To check whether a regex matches a string, use occursin:
Example
julia
occursin
(
r
"^\s*(?:#|$)"
,
"not a comment"
)
false
julia
occursin
(
r
"^\s*(?:#|$)"
,
"# a comment"
)
true
Finding a Match: match
occursin only returns true or false. If you want to knowhowa string matched, and capture the match information, use the match function instead:
Example
julia
match
(
r
"^\s*(?:#|$)"
,
"not a comment"
)
julia
match
(
r
"^\s*(?:#|$)"
,
"# a comment"
)
RegexMatch
(
"#"
)
If the regex does not match the given string, match returns nothing, a special value that prints nothing in the interactive prompt. Apart from not printing, it is a perfectly normal value that can be tested by a program:
Example
A typical use: take different branches depending on the match result
m =
match
(
r
"^\s*(?:#|$)"
, line
)
if
m === nothing
println
(
"not a comment"
)
else
println
(
"blank or comment"
)
end
If the regex matches, the return value of match is a RegexMatch object, which records the matched substring and the captured substrings. The following example captures the non-empty text after the comment character #:
Example
julia
m =
match
(
r
"^\s*(?:#\s*(.?)\s$|$)"
,
"# a comment "
)
RegexMatch
(
"# a comment "
,
1
=
"a comment"
)
When calling match, you can optionally specify the index at which to start the search:
Example
julia
m =
match
(
r
"[0-9]"
,
"aaaa1aaaa2aaaa3"
,
1
)
RegexMatch
(
"1"
)
julia
m =
match
(
r
"[0-9]"
,
"aaaa1aaaa2aaaa3"
,
6
)
RegexMatch
(
"2"
)
julia
m =
match
(
r
"[0-9]"
,
"aaaa1aaaa2aaaa3"
,
11
)
RegexMatch
(
"3"
)
Extracting Match Information
You can extract the following information from a RegexMatch object:
| Field | Description |
|---|---|
m.match |
The entire matched substring |
m.captures |
The array of captured substrings |
m.offset |
The offset where the whole match begins |
m.offsets |
The offset vector of the captured substrings |
When a capture does not match, m.captures contains nothing at that position and m.offsets has an offset of 0:
Example
julia
m =
match
(
r
"(a|b)(c)?(d)"
,
"acd"
)
RegexMatch
(
"acd"
,
1
=
"a"
,
2
=
"c"
,
3
=
"d"
)
julia
m.
match
"acd"
julia
m.
captures
3
-element
Vector
{
Union
{
Nothing, SubString
{
String
}
}
}
:
"a"
"c"
"d"
julia
m.
offset
1
julia
m.
offsets
3
-element
Vector
{
Int64
}
:
1
2
3
The second capture group (c)? did not match any content
julia
m =
match
(
r
"(a|b)(c)?(d)"
,
"ad"
)
RegexMatch
(
"ad"
,
1
=
"a"
,
2
=nothing,
3
=
"d"
)
julia
m.
captures
3
-element
Vector
{
Union
{
Nothing, SubString
{
String
}
}
}
:
"a"
nothing
"d"
The RegexMatch object implements iterator methods and can be destructured directly into variables:
Example
julia
first, second, third = m
;
first
"a"
Named Capture Groups
Access to captures is also possible by indexing the RegexMatch object with the number or name of a capture group:
Example
julia
m =
match
(
r
"(?
,
"12:45"
)
RegexMatch
(
"12:45"
, hour=
"12"
, minute=
"45"
)
julia
m
[
:minute
]
"45"
julia
m
[
2
]
"45"
Finding All Matches: eachmatch
match returns only the first match; to find all matches, use eachmatch:
Example
julia
for
m
in
eachmatch
(
r
"runoob"
,
"runoob RUNOOB runoob.com"
)
println
(
"Match: $(m.match) at offset $(m.offset)"
)
end
Match: runoob at
offset
1
Match: runoob at
offset
14
julia
collect
(
m.
match
for
m
in
eachmatch
(
r
"[0-9]+"
,
"1 tomato 2 oranges"
)
)
2
-element
Vector
{
SubString
{
String
}
}
:
"1"
"2"
Replacement: replace
The replace function can replace content matched by a regex with a new string:
Example
Replace all numbers with
julia
replace
(
"a1b2c3"
, r
"[0-9]"
=
"#"
)
"a#b#c#"
Replace only the first match
julia
replace
(
"a1b2c3"
, r
"[0-9]"
=
"#"
,
count
=
1
)
"a#b2c3"
In the replacement string you can use \n to refer to the nth capture group; in this case the replacement string needs the s prefix. Capture group 0 refers to the whole match, and named capture groups use \g to refer to:
Example
\g Refer to named capture groups, \1 refers to the first capture group, achieving a word swap
julia
replace
(
"first second"
, r
"(\w+) (?
=
s
"\g
)
"second first"
julia
replace
(
"a"
, r
"."
=
s
"\g<0>1"
)
"a1"
Date format conversion
julia
replace
(
"2024-05-01"
, r
"(?
=
s
"\g
)
"01/05/2024"
Regular Expression Flags
You can add the i, m, s, and x flags after the closing double quote to modify the regular expression:
| Flag | Meaning |
|---|---|
i |
Case-insensitive matching |
m |
Multi-line mode, ^ and $ match the beginning and end of each line |
s |
Single-line mode, lets . also match newline characters |
x |
Extended mode, ignores whitespace and # comments, making it easier to write readable regexes |
Example
julia
occursin
(
r
"^runoob$"
i,
"RUNOOB"
)
i flag: ignore case
true
The ism three flags used together
julia
match
(
r
"a+.*b+.*d$"
ism,
"Goodbye,\nOh, angry,\nBad world\n"
)
RegexMatch
(
"angry,\nBad world"
)
x flag: can be written across lines with comments
julia
match
(
r
"""
(\d{4}) - # year
(\d{2}) - # month
(\d{2}) # day
"""
x,
"2024-05-01"
)
RegexMatch
(
"2024-05-01"
,
1
=
"2024"
,
2
=
"05"
,
3
=
"01"
)
Tip:If you need to build a regular expression dynamically from variables, you can use the Regex constructor: Regex("Day " * string(day)); in this case the concatenated content needs attention to escaping.
For more regular expression syntax, see:Regular Expressions - Tutorial