-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]).