Sep 082012
 

Few time ago I had a tcl chalange that in other languages is straight forward: split a string using as separator a substring.
In tcl there is a split function: [split $myStr $subStr] but, by default it splits by any char of $subStr.
To be more precise let’s assume that we have a string $my_str like

"set1 line1
set1 line 2
set 1 line 3

set2 line 1
set2 line 2

set3 line1
set3 line2
set3 line3"

and we want to split by empty line (“\n\n”).

If we try soemething like
set list_str [split $my_str "\n\n"]
the $list_str is
{set1 line1 } {set1 line 2} {set 1 line 3} {} {set2 line 1} {set2 line 2} {} {set3 line1} {set3 line2} {set3 line3}
it is the same thing as set list_str [split $my_str "\n"] .

The trick is to replace the “\n\n” sequence in $my_str with one single char , a char which does not exists in $my_str, and the to split the result by this single char.
And one char which probable does not exists in $my_str is something like “\x00”.

So, a line like
set list_str [split [string map [list "\n\n" "\x00"] $my_str] "\x00"]
is exactly what you need

  One Response to “split a string by substring (multichars) in tcl”

  1. Hey There. I found your blog using msn. This is a really well written article. I will be sure to bookmark it and come back to read more of your useful information. Thanks for the post. I will certainly return. Occhiali

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)