How to remove all empty characters in a string in Erlang?

I know there is a line: strip in erlang. But for me it is strange.

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 remove all leading / trailing empty characters, including spaces, \ t, \ n, \ r, etc.

 some_module:better_strip(A) % => [] 

Can erlang use one function? Or, if I have to do it myself, what's the best way?

+8
string erlang trim strip chomp
source share
3 answers

Try the following:

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

Try this construct:

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

Session Example:

 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

The above solution will also separate the space characters inside the string (not just leading and trailing).

If you need to remove only the lead and tail, you can use something like this:

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

Session Example:

 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" 
+6
source share

Using the built-in function: string:strip/3 , you can have a common abstraction

 clean (Text, Char) -> string: strip (string: strip (Text, right, Char), left, Char).
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> 

It is a clean and general way. Char must be an ASCII value.

0
source share

All Articles