Regular expressions
The re module is the PCRE-style regular expression engine of Erlang. It reads a pattern and a subject as strings or binaries, and answers the match as positions, strings or binaries. This lesson matches, captures, replaces and splits, and then shows the mistake a first pattern usually makes: a dot that is too greedy.
re:run
re:run(Subject, Pattern, Options) answers {match, Captures} or the atom nomatch. Without a capture option the captures are byte positions, which is fast but not what a reader wants to see; {capture, all, binary} answers the matched text as binaries. This module pulls every address out of a line:
emails.erl
-module(emails). -export([main/0]). main() -> Text = <<"write to ada@example.com or grace@example.org">>, Pattern = "[a-z]+@[a-z.]+", {match, Matches} = re:run(Text, Pattern, [global, {capture, first, binary}]), Emails = [hd(Match) || Match <- Matches], io:format("~p~n", [Emails]).
erlc emails.erl
erl -noshell -eval 'emails:main(), halt().'
[<<"ada@example.com">>,<<"grace@example.org">>]
global asks for every match, and each match arrives as its own list of captures, so the comprehension takes the first capture of each. A pattern with a group would give that group as a second element of the list; the strings lesson names the binary form the match keeps.
Captures and global
A capture option chooses the shape of the answer. all returns the whole match and every group, all_but_first drops the whole match and keeps the groups, and first is the whole match alone. The third element of the option is index, list or binary:
erl
1> re:run("abc123", "[0-9]+", [{capture, all, binary}]). {match,[<<"123">>]} 2> re:run("a=1", "([a-z]+)=([0-9]+)", [{capture, all_but_first, list}]). {match,["a","1"]} 3> re:run("abc", "[0-9]+"). nomatch
The first answer has one capture because the pattern has no group; the second has two. The third is the ordinary failure: no exception, just nomatch, which a caller matches in the same way as an error tuple.
Replace and split
re:replace/4 substitutes every match with the replacement when the global option is on, and re:split/3 cuts the subject at every match. The replacement may name a group as \1, and the split takes the same capture and return options as a match:
replace.erl
-module(replace). -export([main/0]). main() -> io:format("~p~n", [iolist_to_binary(re:replace("a1 b2", "[0-9]", "#", [global]))]), io:format("~p~n", [re:split("one, two,three", ",\s*", [{return, list}])]).
erlc replace.erl
erl -noshell -eval 'replace:main(), halt().'
<<"a# b#">> ["one","two","three"]
The replacement builds iodata, as the JSON encoder does with json:encode/1, so iolist_to_binary/1 turns it into a binary. The split discards the separators; a pattern with a group keeps the group in the result, which is how a program keeps the delimiter it split on.
The greedy dot
.* matches as much as it can, so the pattern <.*> takes the first opening bracket and the last closing one in the subject, not the first pair. A negated class, <[^>]*>, stops at the first closing bracket and is the pattern that reads one tag at a time:
greedy.erl
-module(greedy). -export([main/0]). main() -> Text = "<a><b>", io:format("~p~n", [re:run(Text, "<.*>", [{capture, all, list}])]), io:format("~p~n", [re:run(Text, "<[^>]*>", [global, {capture, all, list}])]).
erlc greedy.erl
erl -noshell -eval 'greedy:main(), halt().'
{match,["<a><b>"]} {match,[["<a>"],["<b>"]]}
The first pattern answers one match that is both tags; the second answers two. The same trap appears with a quoted string, a comment and a JSON object: any pattern built from .* between two delimiters matches across every delimiter in the subject. A negated class or a lazy .*? is the fix.
Compile once
A pattern that a loop runs many times is worth compiling once. re:compile/1 answers {ok, Compiled} or {error, Reason}, and re:run/3 accepts the compiled value in place of the pattern string. The compile also reports a syntax error once, at startup, instead of on the first request. This module compiles once and uses the value:
compiled.erl
-module(compiled). -export([main/0]). main() -> {ok, Pattern} = re:compile("[a-z]+@[a-z.]+"), io:format("~p~n", [re:run("ada@example.com", Pattern, [{capture, first, binary}])]).
erlc compiled.erl
erl -noshell -eval 'compiled:main(), halt().'
{match,[<<"ada@example.com">>]}
The compiled term prints with internal fields that differ between OTP versions, so a page never quotes it in full. The pattern is what a program stores in a module attribute or a persistent term; the modern Erlang lesson shows persistent_term, which is where a compiled pattern lives in a long-running system.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
re:run/3answer when the pattern does not match?Answer
nomatchA miss is the atom
nomatch, which a caller matches like any other value. -
What does the
globaloption ask for?Answer
Every match in the subject
Without
globalthe run stops at the first match; with it every match is reported. -
Which capture option keeps only the groups, not the whole match?
Answer
all_but_firstall_but_firstdrops the whole match and answers the groups alone. -
Why is
<.*>the wrong pattern for one tag?Answer
The dot is greedy and takes the last closing bracket
.*matches as much as possible, so the match runs from the first < to the last >. -
What does this module print?
-module(q1). -export([main/0]). main() -> io:format("~p~n", [re:run("abc123", "[0-9]+", [{capture, all, binary}])]).Answer
{match,[<<"123">>]}The digits match, and the capture list holds the matched binary.
-
What does this module print?
-module(q2). -export([main/0]). main() -> io:format("~p~n", [re:run("key=1", "([a-z]+)=([0-9]+)", [{capture, all_but_first, list}])]).Answer
{match,["key","1"]}There are two groups, and
all_but_firstanswers them in order. -
What does this module print?
-module(q3). -export([main/0]). main() -> io:format("~p~n", [iolist_to_binary(re:replace("a1 b2", "[0-9]", "#", [global]))]).Answer
<<"a# b#">>globalreplaces both digits, and the iodata is turned into a binary. -
What does this module print?
-module(q4). -export([main/0]). main() -> io:format("~p~n", [re:split("alpha, beta", ",\\s*", [{return, list}])]).Answer
["alpha","beta"]The pattern matches the comma and the space, so the two words are the parts.
-
What does
re:compile/1answer for a valid pattern?Answer
{ok, Compiled}It answers
{ok, Compiled}, and the compiled value can replace the pattern inre:run/3. -
Why compile a pattern that a loop runs many times?
Answer
To parse it once instead of on every call
The compile parses the syntax and builds the matcher; a reused value skips that work and reports a syntax error early.
The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev