Search code examples
functional-programmingerlangelixirerlang-shell

Remove a substring/ string pattern of a string in Erlang


I have an xml string like

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

I want to remove the end tag </B>

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

How can I achieve this?


Solution

  • If you only want to remove the specific string literal </B> then getting a sublist will do the trick:

    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\"/>"
    

    If you need a more general approach you can use the re:replace/3 function:

    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\"/>"
    

    Update

    As mentioned in the comments, providing the option {return, list} is much cleaner:

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