だが、パターンマッチしてヒットしたものすべてを置換することに成功。そのサンプルを。
しかし、もっと良いやり方があるのではと思う。reモジュールをもっと勉強しないと。だが、直近で正規表現は必要ない。正規表現はまた別の機会に。
ソース:
-module(re_replace_multi).
-export([start/0,binList_to_list/1]).
%%--------------------------------------------------------------------
%% @doc
%% @spec start() -> list() | error
%% @end
%%--------------------------------------------------------------------
start() ->
Regexp = ["Erlang"],
%% compile the Regular Expression
case re:compile (Regexp) of
{ok,MP} ->
Subject = ["My favorite Language is Erlang. Erlang. Erlang."],
do_regexp (MP,Subject);
{error, ErrSpec} ->
io:format ("Compile Error ~p~n",[ErrSpec]),
error
end.
%%--------------------------------------------------------------------
%% @doc
%% @spec do_regexp(MP) -> list() | error
%% @type MP = mp()
%% @end
%%--------------------------------------------------------------------
do_regexp (MP,Subject) ->
io:format("subject:~p~n",[Subject]),
case re:run(Subject, MP) of
{match, Captured} ->
io:format ("match:~p~n",[Captured]),
Rep = "Ruby",
io:format("Replace to ~p from \"Erlang\".~n",[Rep]),
Replace = re:replace(Subject, MP, [Rep]),
%Tmp = [binary_to_list(X) || X <- Replace],
%Replace1 = lists:append(Tmp),
Sub = binList_to_list (Replace),
do_regexp(MP,[Sub]);
nomatch ->
io:format ("nomatch~n"),
Subject
end.
%%--------------------------------------------------------------------
%% @doc
%% @spec binList_to_list (list() | binary()) -> list()
%% @end
%%--------------------------------------------------------------------
binList_to_list ([]) ->
[];
binList_to_list (Lists)
when is_binary(Lists)
-> binary_to_list(Lists);
binList_to_list (Lists)
when is_list(Lists)
-> [Head|Tails] = Lists,
case is_binary(Head) of
true ->
HeadStr = binary_to_list(Head),
HeadStr ++ binList_to_list(Tails);
false ->
Head ++ binList_to_list(Tails)
end.
実行結果:
1> c(re_replace_multi).
{ok,re_replace_multi}
2> re_replace_multi:start().
subject:["My favorite Language is Erlang. Erlang. Erlang."]
match:[{24,6}]
Replace to "Ruby" from "Erlang".
subject:["My favorite Language is Ruby. Erlang. Erlang."]
match:[{30,6}]
Replace to "Ruby" from "Erlang".
subject:["My favorite Language is Ruby. Ruby. Erlang."]
match:[{36,6}]
Replace to "Ruby" from "Erlang".
subject:["My favorite Language is Ruby. Ruby. Ruby."]
nomatch
["My favorite Language is Ruby. Ruby. Ruby."]
3>