vho
vho

Reputation: 1141

How effectively split line?

I would like to split line by \t = or ,

I have try to use:

set line [split $line" \t=,"]
set result {}
foreach element $line {
    if { $element != {} } { 
        lappend result $element
    }
}

Lines look like:

name1 name2 name3 floating_point_number1, floating_point_number2 

or

name = floating_point_number1, floating_point_number2 ... floating_point_numbern-1, floating_point_numbern

But it's seem very slow. How can I change the code to be more effective?

Upvotes: 1

Views: 105

Answers (1)

glenn jackman
glenn jackman

Reputation: 247092

You might want to look at the textutil::split module from tcllib.

% set s "this\tis=a,line=,\twith separators="
this    is=a,line=, with separators=
% package require textutil::split
0.7
% textutil::split::splitx $s {[[:blank:]=,]}
this is a line {} {} {with separators} {}

If it's the empty elements you want to avoid, then the tcllib struct::list package helps

% package req struct::list
1.7
% set l [textutil::split::splitx $s {[[:blank:]=,]}]
this is a line {} {} {with separators} {}
% struct::list filterfor field $l {[llength $field] > 0}
this is a line {with separators}

Upvotes: 4

Related Questions