删除Erlang中字符串的子字符串/字符串模式

py49o6xq  于 2022-12-08  发布在  Erlang
关注(0)|答案(2)|浏览(222)

我有一个xml字符串,如

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

我要移除结束标记</B>

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

我如何才能做到这一点?

rseugnpd

rseugnpd1#

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

vbopmzt12#

可以使用string模块中的string:replace/3函数。
string:replace/3 -将String中的SearchPattern替换为Replacement。第三个函数参数指示是否要替换SearchPattern的前导、尾随或所有遇到的SearchPattern。

S2 = string:replace(S, "</B>", "", all).

相关问题