Remove a substring/ string pattern of a string in Erlang

笑着哭i 提交于 2020-01-05 10:02:29

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/25703670/remove-a-substring-string-pattern-of-a-string-in-erlang

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!