ActiveState Code

Recipe 252145: Gettok


It returns the Xth token in a sentence.. like: i have a sentence divided by : and i want to get the second value sentence: set x "Value 1 : Value 2 : Value 3" [gettok $x 2 :] is returns <b>Value 2</b> if you use 0 as the number...it will returns the number of tokens in this case... <b>3</b>

Tcl
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
proc gettok {1 2 3} {
 if {![string match -nocase *$3* $1]&&$2==1} {return $1}
 if {![string match -nocase *$3* $1]&&$2>1} {return}
 if {$2=="0"} {
  if {[string match -nocase *$3* $1]} {
   set a [split $1 $3];return [llength $a]
  };return 1
 }
 set a [split $1 $3];if {$2>[llength $a]} {return}
 if {[lindex $a [expr $2 - 1]]==""&&[lindex $a $2]!=""} {return [lindex $a $2]}
 return [lindex $a [expr $2 - 1]]
}

Comments

  1. 1. At 3:49 a.m. on 16 dec 2003, Richard Suchenwirth said:

    A simpler alternative. Wouldn't this be simpler and more robust?

    proc gettok {data field separator} {
       string trim [lindex [split $data $separator] $field]
    } ;# RS
    
  2. 2. At 1:54 a.m. on 25 dec 2003, Kiko The King (the author) said:

    A simpler alternative.. simplier yes, more robust no ;] mine checks for mistakes and everything.. if u know mirc scripting..i tried to make a +- port of $gettok to tcl..doesnt do quite the same cose in mirc is more complex supports things like -3 2-4 4-..and that would make gettok bigger... and urs doesnt do the same s mine does..test the examples i gave with urs ;]

Sign in to comment