Regular Expressions in Erlang

Regular expressions in Erlang are handled by the re module. Here are some examples of common regexp-related tasks in Erlang.

-module(regular_expressions).
-export([main/0]).

main() ->
    % This tests whether a pattern matches a string.
    {ok, MP} = re:compile("p([a-z]+)ch"),
    io:format("~p~n", [re:run("peach", MP) =/= nomatch]),

    % Above we compiled a pattern, which is generally more efficient
    % for repeated use. Here's how to use it:
    io:format("~p~n", [re:run("peach", MP) =/= nomatch]),

    % This finds the match for the regexp.
    case re:run("peach punch", MP, [{capture, first, list}]) of
        {match, [Match]} -> io:format("~s~n", [Match]);
        nomatch -> io:format("No match~n")
    end,

    % This finds the first match but returns the start and end
    % indexes for the match instead of the matching text.
    case re:run("peach punch", MP) of
        {match, [{Start, Length}]} ->
            io:format("idx: [~B ~B]~n", [Start, Start + Length]);
        nomatch ->
            io:format("No match~n")
    end,

    % The 'all' option returns information about all matches in the input.
    case re:run("peach punch pinch", MP, [global, {capture, all, list}]) of
        {match, Matches} ->
            io:format("~p~n", [Matches]);
        nomatch ->
            io:format("No match~n")
    end,

    % Providing a positive integer as the 'capture' option will limit
    % the number of captures.
    case re:run("peach punch pinch", MP, [global, {capture, 2, list}]) of
        {match, Matches} ->
            io:format("~p~n", [Matches]);
        nomatch ->
            io:format("No match~n")
    end,

    % The re module can also be used to replace subsets of strings
    % with other values.
    Replaced = re:replace("a peach", MP, "<fruit>", [{return, list}]),
    io:format("~s~n", [Replaced]),

    % The 'fun' option allows you to transform matched text with a given function.
    ReplaceFun = fun(Match, _) ->
        string:to_upper(Match)
    end,
    ReplacedUpper = re:replace("a peach", MP, ReplaceFun, [{return, list}]),
    io:format("~s~n", [ReplacedUpper]).

To run this program, save it as regular_expressions.erl and use:

$ erlc regular_expressions.erl
$ erl -noshell -s regular_expressions main -s init stop

This will compile and run the Erlang code, producing output similar to:

true
true
peach
idx: [0 5]
[["peach","ea"],["punch","un"],["pinch","in"]]
[["ea"],["un"],["in"]]
a <fruit>
a PEACH

Note that Erlang’s regular expression syntax and functionality are similar to Perl Compatible Regular Expressions (PCRE). The re module provides a rich set of functions for working with regular expressions, including compilation, matching, and replacement operations.

For a complete reference on Erlang regular expressions, check the re module documentation.