2012-10-09 40 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

相关问题