Remove white space with Erlang Regex
I want to remove all spaces, i.e. tabs / spaces / newlines.
T = {xmlelement,"presence",
[{"xml:lang","en"}],
[{xmlcdata,<<"\n">>},
{xmlelement,"priority",[],
[{xmlcdata,<<"5">>}]},
{xmlcdata,<<"\n">>},
{xmlelement,"c",
[{"xmlns",
"http://jabber.org/protocol/caps"},
{"node","http://psi-im.org/caps"},
{"ver","0.12.1"},
{"ext","cs ep-notify html"}],
[]},
{xmlcdata,<<"\n">>}]}.
I tried the following, but it doesn't work:
trim_whitespace(Input) ->
re:replace(Input, "(\r\n)*", "").
+1
a source to share
4 answers
I faced the same problem ... came here to share my more efficient work:
trim(Subject) ->
{match, [[Trimmed]|_]} = re:run(Subject, "^\\s*([^\\s]*(?:.*[^\\s]+)?)\\s*$",
[{capture, all_but_first, binary}, global, dollar_endonly, unicode, dotall]),
Trimmed.
The idea is the same. Regular expression is only better.
+2
a source to share
All the spaces in your question are in the cdata sections - why not just filter them out of the tuple?
remove_cdata(List) when is_list(List) ->
remove_list_cdata(List);
remove_cdata({xmlelement, Name, Attrs, Els}) ->
{xmlelement, Name, remove_cdata(Attrs), remove_cdata(Els)}.
remove_list_cdata([]) ->
[];
remove_list_cdata([{xmlcdata,_}|Rest]) ->
remove_list_cdata(Rest);
remove_list_cdata([E = {xmlelement,_,_,_}|Rest]) ->
[remove_cdata(E) | remove_list_cdata(Rest)];
remove_list_cdata([Item | Rest]) ->
[Item | remove_list_cdata(Rest)].
remove_cdata(T) =:=
{xmlelement,"presence",
[{"xml:lang","en"}],
[{xmlelement,"priority",[],[]},
{xmlelement,"c",
[{"xmlns","http://jabber.org/protocol/caps"},
{"node","http://psi-im.org/caps"},
{"ver","0.12.1"},
{"ext","cs ep-notify html"}],
[]}]}
0
a source to share
re: replace is hard, you need to keep in mind:
Eshell V5.9.3.1 (abort with ^G)
1> re:replace("0 1 2 3 4 5 6 7 8 9", " ", "", [global, {return, list}]).
"0123456789"
2> re:replace("0 1 2 3 4 5 6 7 8 9", " ", "", [{return, list}]).
"01 2 3 4 5 6 7 8 9"
3> re:replace("0 1 2 3 4 5 6 7 8 9", " ", "").
[<<"0">>,[]|<<"1 2 3 4 5 6 7 8 9">>]
0
a source to share