[erlang-questions] Formatting strings with named arguments

John Doe donpedrothird@REDACTED
Sun Feb 15 20:54:30 CET 2015


yeah, already wrote something like this

format(String, Parameters) ->
Parts = re:split(String, "~(.*?)\\((.*?)\\)(.)", [{return, binary}, group,
trim]),
Replace = fun
([Bin]) -> Bin;
([Prefix, Modifier, Name, F]) ->
case lists:keyfind(Name, 1, Parameters) of
false -> exit([<<"String format: parameter ">>, Name, <<" not found.">>]);
{_, Val} ->
[Prefix, io_lib:format(<<"~", Modifier/binary, F/binary>>, [Val])]
end
end,
[Replace(Part) || Part <- Parts].




>iolist_to_binary(format("start~(foo)Bmiddle~10(bar)send", [{<<"foo">>,
123}, {<<"bar">>, <<"qwerty">>}])).
<<"start123middle    qwertyend">>




2015-02-15 22:44 GMT+03:00 Imants Cekusins <imantc@REDACTED>:

> io_lib:format
> substitutes multiple placeholders, converts to string, does padding.
>
> You could
> 1) search for named placeholders using re:run
>
> 2) replace placeholders with ~s or ~p using re:replace
>
> 3) prepare a list with substitutes from a map|dict
>
> 4) pass this list to io_lib:format.
>
> A bit of work but doable.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20150215/1832c81e/attachment.htm>


More information about the erlang-questions mailing list