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?
Try this:
re:replace(A, "(^\\s+)|(\\s+$)", "", [global,{return,list}]).
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With