halfelf
halfelf

Reputation: 10107

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?

Upvotes: 11

Views: 12507

Answers (5)

justastranger
justastranger

Reputation: 21

Here is the short way of doing it in erlang:

145> A = "  \t\n".
"  \t\n"
146> A1 = [X || X<-A, X =/= 32].
"\t\n"

The 32 above represents a ' ' character.

Upvotes: 1

N. Hoogervorst
N. Hoogervorst

Reputation: 156

Nowadays use string:trim

1> string:trim("  \t\n").
[]

Upvotes: 9

Muzaaya Joshua
Muzaaya Joshua

Reputation: 7836

Using a built in function: string:strip/3, you can have a general abstraction

clean(Text,Char)-> string:strip(string:strip(Text,right,Char),left,Char).
The you would use it like this:

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Windows\System32>erl
Eshell V5.9  (abort with ^G)
1> Clean = fun(Text,Char) -> string:strip(string:strip(Text,right,Char),left,Char) end.
#Fun<erl_eval.12.111823515>
2> Clean(" Muzaaya   ",32).
"Muzaaya"
3> Clean("--Erlang Programs--",$-).
"Erlang Programs"
4> Clean(Clean("** WhatsApp Uses Erlang and FreeBSD in its Backend  ",$*),32).
"WhatsApp Uses Erlang and FreeBSD in its Backend"
5> 

This is a clean way, and general. The Char must be an ASCII value.

Upvotes: 1

Tilman
Tilman

Reputation: 2005

Try this:

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

Upvotes: 18

fycth
fycth

Reputation: 3489

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"

Upvotes: 9

Related Questions