【问题标题】:Remove a substring/ string pattern of a string in Erlang在 Erlang 中删除字符串的子字符串/字符串模式
【发布时间】:2014-10-31 10:58:45
【问题描述】:

我有一个类似的 xml 字符串

 S = "<B xmns=\"som2\"> <a other='v1' more='v2'/><b some=\"v3/></B>".

我想去掉结束标签&lt;/B&gt;

 S2 = "<B xmns=\"som2\"> <a other='v1' more='v2'/><b some=\"v3/>"

我怎样才能做到这一点?

【问题讨论】:

    标签: functional-programming erlang elixir erlang-shell


    【解决方案1】:

    如果您只想删除特定的字符串文字&lt;/B&gt;,那么获取子列表就可以了:

    S = "<B xmns=\"som2\"> <a other='v1' more='v2'/><b some=\"v3\"/></B>",
    lists:sublist(S, 1, length(S) - 4).
    %%= "<B xmns=\"som2\"> <a other='v1' more='v2'/><b some=\"v3\"/>"
    

    如果您需要更通用的方法,可以使用re:replace/3 函数:

    S1 = re:replace(S, "</B>", ""),
    S2 = iolist_to_binary(S1),
    binary_to_list(S2).
    %%= "<B xmns=\"som2\"> <a other='v1' more='v2'/><b some=\"v3\"/>"
    

    更新

    如 cmets 中所述,提供选项 {return, list} 更简洁:

    re:replace(S, "</B>", "", [{return,list}]).
    %%= "<B xmns=\"som2\"> <a other='v1' more='v2'/><b some=\"v3\"/>"
    

    【讨论】:

    • re:replace(S, "&lt;/B&gt;", "", [{return,list}]) 将使iolist_to_binary/1 . binary_to_list/1 变得不必要。
    猜你喜欢
    • 2014-03-15
    • 2015-11-20
    • 2019-09-08
    • 1970-01-01
    • 2018-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多