2012-10-09 46 views
8

我知道那裏有字符串:在erlang中。但其行爲對我來說很奇怪。如何去除Erlang中字符串中的所有空白字符?

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 

我需要一個函數來刪除所有前導/尾隨空白字符,包括空格,\ t,\ n,\ r等

some_module:better_strip(A) % => [] 

二郎是否有一個功能,能做到這一點?或者如果我必須自己做這個,最好的方法是什麼?

+0

這不是「奇怪」,它被記錄爲只修剪*空格* aka空格:http://erlang.org/doc/man/string.html#strip-1。 – Tommy

回答

14

試試這個:

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

嘗試這種結構:

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

實施例的會話:

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

上述溶液將去除內部字符串空間符號太(不僅前導和拖尾)。

如果你只需要剝離領導和拖尾,你可以使用這樣的事情:

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

舉例會議:

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" 
+1

這將刪除非前導/尾隨空白。 – Tilman

+1

是的。如果只需要去掉前導符號和尾部符號,可以使用兩個結構re:replace(A,「^ \\ s +」,「」,[global,{return,list}])。和're:替換(A,「\\ s + $」,「」,[global,{return,list}])。' – fycth

0

使用內置函數:string:strip/3,你可以有一個普通的抽象

 
clean(Text,Char)-> string:strip(string:strip(Text,right,Char),left,Char). 
的你會使用這樣的:

 
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> 

這是一個乾淨的方式,和一般。 Char必須是ASCII值。

+0

謝謝。但我知道這個,並寫下爲什麼我不在問題中使用它。 – halfelf

相關問題