Reputation: 249
I have a bunch of data I am parsing through Tcl but running into issues when using lindex
on the strings since it contains backslashes.
For example,
$data is a list split by lines,
{123 somethinghere/somethingthere/\idontcare 123ff}
{456 apples/oranges/\bananas 921}
{999 pikachu/ratata/\snorlax ftp}
I loop on $data
and use lindex
to split this data and group it according to its type:
foreach item $data {
set num [lindex $item 0]
set paths [lindex $item 1]
set output [lindex $item 2]
}
Unfortunately, the backslashes escape the text I want.
puts "$paths"
somethinghere/somethingthere/dontcare
Ideally I don't even want to preserve the backslashes. My preferred data on $path
would be:
puts "$paths"
somethinghere/somethingthere/idontcare
Suggestions? I don't want to use regexp unless that's the only way.
Upvotes: 5
Views: 663
Reputation: 113906
First rule of lists is: don't treat non-list things as lists (well, there are exceptions to this but your data is a good example why you should follow the rule in 99% of cases).
To convert the string properly to a list use split
:
set i [split $item " "]
If the split character is variable or is more than one char use regexp
:
set i [regexp -inline -all {\S+} $item]
By using commands that return lists you are guaranteed that you get a proper list. Unless you're 100% sure (the exception) strings are not always parseable as lists.
Now, as for how to get rid of \
. You can of course use regexp for this:
set item [regsub -all {\\} $item]
But there's a better way to do this without using regexp (which I'm sure you'd appreciate), use string map
:
set item [string map {"\\" ""} $item]
Upvotes: 7