Tuesday, 21 February 2012

Mel: Query part of a string, given its index and separator: PART 3

Update from PART 2.
Thanks to Viktoras Makauskas for the suggestions and link.
// get an item from a string given the string, separator and index range // ld_getName "L_test_me_out_bind_jnt" "_" 2 -2 ; global proc string ld_getName(string $obj,string $separator,int $start,int $end) { string $buffer[],$name ; int $numTokens=`tokenize $obj $separator $buffer` ; if($start<0) $start=$numTokens+$start ; if($end<0) $end=$numTokens+$end ; if($start<0 || $start>=$numTokens || $end<0 || $end>=$numTokens || $start>$end) return "" ; $name=$buffer[$start] ; for($n=($start+1);$n<=$end;$n++) $name+=$separator+$buffer[$n] ; return $name ; }
Changes include:
  1.  Separating the indexing to individual ints instead of a string that needs to get split.
  2.  Using the indexes to specify the token, not the separator.
  3.  More error checking.
Main difference is 0 -1 will now return the entire string rather than all but the last token (as it does in Python), mainly for functionality due to the removal of the colon. Can still return one item using the same int (ie the last token would be -1 -1).