Monday, 20 February 2012

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

Update to previous post (here), needed to grab a range of items from a string given a separator and index/range (supports reverse and extended indexing).
I do have a horribly sneaky suspicion there is already a built in command for this...
Will work with ranges given as "0", "-1", "0:","-2:", ":2", ":-2", "1:3" and "-3:-1" etc.
// get an item from a string given the string, separator and index number/range as string (supports reverse indexing) //ld_getName "L_test_me_out_bind_jnt" "_" "2:-1" ; global proc string ld_getName(string $obj,string $separator,string $index) { string $mulBuffer[],$indBuffer[],$name ; int $range[],$start,$end ; tokenize $index ":" $mulBuffer ; $range[0]=int($mulBuffer[0]) ; if(startsWith($index,":")) { $mulBuffer[1]=$range[0] ; $range[0]=0 ; } else if(endsWith($index,":")) $mulBuffer[1]=-1 ; tokenize $obj $separator $indBuffer ; $start=$range[0] ; if($range[0]<0) $start=size($indBuffer)-(abs($range[0])) ; if(size($mulBuffer)>1) { $range[1]=int($mulBuffer[1]) ; $end=$range[1] ; if($range[1]<0) $end=size($indBuffer)-abs($range[1]) ; if($end>(size($indBuffer)-1)) return "" ; $name=$indBuffer[$start] ; for($n=($start+1);$n<$end;$n++) $name+=$separator+$indBuffer[$n] ; } else { if($start<0) $name=$indBuffer[size($indBuffer)-int(abs($start))] ; else $name=$indBuffer[$start] ; } return $name ; } Would appreciate any feedback (I know how much simpler this is in python, was curious how simple it was to do in mel).
Python, i think, would handle like this:
"L_test_me_out_bind_jnt".split("_")[2:-1]