Erlang解析占位符变量

时间:2018-10-11 11:33:34

标签: erlang

我正在尝试创建一种特殊的模板格式,该格式必须找到{{{--example_id--}}}的出现并单独替换该内容,并使用括号括起来的值来获取它。

我最初的尝试是拆分自己的方式,下面发布一些示例代码,这些代码尚未(尚未针对多个占位符进行优化),一次只能处理一个占位符。

parse_text() ->
    Text = <<"this is text {{{--test_placeholder_1--}}} and this also">>,
    % would not work here:
    % Text = <<"this is text {{{--test_placeholder_1--}}} and this {{{--test_placeholder_2--}}} also">>,
    [_,Tail] = binary:split(Text, [<<"{{{--">>],[global]),
    [Id|_] = binary:split(Tail, [<<"--}}}">>],[global]),

    Pattern = <<"{{{--", Id/binary, "--}}}">>,
    Replacement = get_content(Id),
    Result = binary:replace(Text, Pattern, Replacement),

    io:fwrite("~p\n", [Result]).


get_content(<<"test_placeholder_1">>)->
    <<"test id 1!">>;
get_content(<<"test_placeholder_2">>)->
    <<"test id 2!">>;
get_content(_)->
    <<"not found text!">>.

我的问题是,我应该进一步优化它以在一个文本中支持多个占位符,还是有一种更好的方法来处理此类问题?

干杯!

1 个答案:

答案 0 :(得分:2)

我不确定这是否是个好主意,但是它可以用于多个占位符

window

如果您需要更强大的工具来执行此类任务

我认为您应该检查ErlyDTL插件-ErlyDTL Wiki