hal*_*elf 10 string erlang trim strip chomp
我知道erlang中有string:strip.但它的行为对我来说很奇怪.
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
Run Code Online (Sandbox Code Playgroud)
我需要一个函数来删除所有前导/尾随空白字符,包括空格,\ t,\n,\ r \n等.
some_module:better_strip(A) % => []
Run Code Online (Sandbox Code Playgroud)
erlang有一个功能可以做到这一点吗?或者如果我必须自己做,最好的方法是什么?
Til*_*man 16
试试这个:
re:replace(A, "(^\\s+)|(\\s+$)", "", [global,{return,list}]).
Run Code Online (Sandbox Code Playgroud)
尝试这种结构:
re:replace(A, "\\s+", "", [global,{return,list}]).
Run Code Online (Sandbox Code Playgroud)
示例会话:
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"
Run Code Online (Sandbox Code Playgroud)
UPDATE
上面的解决方案也会删除字符串内的空格符号(不仅仅是引导和拖尾).
如果你只需要剥离前导和拖尾,你可以使用这样的东西:
re:replace(re:replace(A, "\\s+$", "", [global,{return,list}]), "^\\s+", "", [global,{return,list}]).
Run Code Online (Sandbox Code Playgroud)
示例会话:
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"
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9302 次 |
最近记录: |