Quantcast

How to split such a string elegantly ?

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

How to split such a string elegantly ?

z_axis
The string contains two parts separated by "-", such as "red - blue" .  However, sometimes there may be no red or blue part.   For example, the following are all right string.
"1 2 3 - 33 23",  "- 33 23", "1 2 3 -", etc.

>[NoRed,NoBlue] = string:tokens("1 2 3 - 33 23","-").
["1 2 3 "," 33 23"]

>[NoRed,NoBlue] = string:tokens("- 33 23","-").   % i hope it returns [""," 33 23"]
** exception error: no match of right hand side value [" 33 23"]

>[NoRed,NoBlue] = string:tokens("1 2 3 -","-").   % i hope it returns [1 2 3 ", ""]
** exception error: no match of right hand side value ["1 2 3 "]


Sincerely!
e^(π.i) + 1 = 0
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: How to split such a string elegantly ?

Harsh J
Hey,

You may use re:split(...) for this purpose instead of string:tokens(...).

6> re:split("red - blue", "-", [{return, list}]).
["red "," blue"]
7> re:split("- blue", "-", [{return, list}]).
[[]," blue"]
8> re:split("red -", "-", [{return, list}]).
["red ",[]]

Have a look at re:split(...) in erldocs.com for more info:
http://erldocs.com/R14B02/stdlib/re.html?i=1&search=re:spl#split/3

On Mon, Jun 20, 2011 at 11:38 AM, z_axis <[hidden email]> wrote:

> The string contains two parts separated by "-", such as "red - blue" .
> However, sometimes there may be no red or blue part.   For example, the
> following are all right string.
> "1 2 3 - 33 23",  "- 33 23", "1 2 3 -", etc.
>
>>[NoRed,NoBlue] = string:tokens("1 2 3 - 33 23","-").
> ["1 2 3 "," 33 23"]
>
>>[NoRed,NoBlue] = string:tokens("- 33 23","-").   % i hope it returns ["","
> 33 23"]
> ** exception error: no match of right hand side value [" 33 23"]
>
>>[NoRed,NoBlue] = string:tokens("1 2 3 -","-").   % i hope it returns [1 2 3
> ", ""]
> ** exception error: no match of right hand side value ["1 2 3 "]
>
>
> Sincerely!
>
> -----
> e^(π.i) + 1 = 0
> --
> View this message in context: http://erlang.2086793.n4.nabble.com/How-to-split-such-a-string-elegantly-tp3610585p3610585.html
> Sent from the Erlang Questions mailing list archive at Nabble.com.
> _______________________________________________
> erlang-questions mailing list
> [hidden email]
> http://erlang.org/mailman/listinfo/erlang-questions
>



--
Harsh J
http://harshj.com
_______________________________________________
erlang-questions mailing list
[hidden email]
http://erlang.org/mailman/listinfo/erlang-questions
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: How to split such a string elegantly ?

z_axis
It works great! thanks
e^(π.i) + 1 = 0
Loading...