Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to strip all blank characters in a string in Erlang?

I know there is string:strip in erlang. But its behaviour is strange for me.

A = "  \t\n"  % two whitespaces, one tab and one newline
string:strip(A)   % => "\t\n"
string:strip(A,both,$\n)  %  string:strip/3 can only strip one kind of character

And I need a function to delete all leading/trailing blank chars, including whitespace, \t, \n, \r etc.

some_module:better_strip(A)    % => []

Does erlang have one function can do this? Or if I have to do this myself, what is the best way?

like image 987
halfelf Avatar asked Oct 09 '12 06:10

halfelf


2 Answers

Try this:

re:replace(A, "(^\\s+)|(\\s+$)", "", [global,{return,list}]).
like image 56
Tilman Avatar answered Oct 16 '22 04:10

Tilman


Try this construction:

re:replace(A, "\\s+", "", [global,{return,list}]).

Example session:

Erlang R15B01 (erts-5.9.1) [source] [async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.9.1  (abort with ^G)
1> A = "  21\t\n  ".
"  21\t\n  "
2> re:replace(A, "\\s+", "", [global,{return,list}]).
"21"

UPDATE

Above solution will strip space symbols inside string too (not only leading and tailing).

If you need to strip only leading and tailing, you can use something like this:

re:replace(re:replace(A, "\\s+$", "", [global,{return,list}]), "^\\s+", "", [global,{return,list}]).

Example session:

Erlang R15B01 (erts-5.9.1) [source] [async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.9.1  (abort with ^G)
1> A=" \t \n 2 4 \n \t \n  ".
" \t \n 2 4 \n \t \n  "
2> re:replace(re:replace(A, "\\s+$", "", [global,{return,list}]), "^\\s+", "", [global,{return,list}]).
"2 4"
like image 40
fycth Avatar answered Oct 16 '22 03:10

fycth