#270 String Transformations: Add s.index and s.rindex

trunk
open-accepted
core (47)
5
2013-04-01
2013-03-30
No

This patch adds the s.index and s.rindex transformations. These transformations can be used to find the first or last occurrence of a string in another string, returning its
index (beginning at 0) or -1 if it is not found. They also optionally take an index parameter which is explained more below.

Examples:

s.index transformation
Searches for one string within another starting at the beginning of the first string. Returns starting index of the string found or -1 if not found.
The optional index specifies the offset to begin the search at in the string. Negative offsets are supported and will wrap.

$var(strtosearch) = 'onetwothreeone';

$var(str) = 'one';

#Search the string starting at 0 index
$(var(strtosearch){s.index, $var(str)}) #will return 0
$(var(strtosearch){s.index, $var(str), 0}) #Same as above
$(var(strtosearch){s.index, $var(str), 3}) #returns 11
#Negative offset
$(var(strtosearch){s.index, $var(str), -11}) #Same as above
#Negative wrapping offset
$(var(strtosearch){s.index, $var(str), -25}) #Same as above

#Test for existence of string in another
if ($(var(strtosearch){s.index, $var(str)}) >=0) {
xlog("found $var(sstr) in $var(strtosearch)");
....
do some stuff
....
}

#Case insensitive match
$var(str) = 'ONE';
$(var(strtosearch){s.index, $var(str)}) #will return -1
$(var(strtosearch){s.toupper}{s.index, $var(str)}) #will return 0

r.index transformation
Searches for one string within another starting at the end of the first string. Returns starting index of the string found or -1 if not found.
The optional index specifies an offset to start the search before, e.g the start of the found string will be before the supplied offset. Negative offsets are supported and will wrap.

$(var(strtosearch){s.rindex, $var(str)}) #will return 11
$(var(strtosearch){s.rindex, $var(str), -3}) #will return 11
$(var(strtosearch){s.rindex, $var(str), 11}) #will return 11
$(var(strtosearch){s.rindex, $var(str), -4}) #will return 0

These transformations should be helpful for general string manipulation in conjunction with the s.substr transformation.
They also provide a mechanism for searching a string that does not rely on regular expressions.

Discussion

  • Bogdan-Andrei Iancu

    • assigned_to: nobody --> razvancrainea
    • status: open --> open-accepted
     

Log in to post a comment.

Get latest updates about Open Source Projects, Conferences and News.

Sign up for the SourceForge newsletter:





No, thanks