OK, here's InStr as I always envisaged it, and as a bonus, 'SubStrRange', which I've been 50/50 on for a long time, whether it should be a default function.
Code: Select all
w:: ;test 'SubStrRange'
vText := "abcdefghijklmnopqrstuvwxyz"
MsgBox, % JEE_SubStrRange(vText, 6, 10) ;fghij
MsgBox, % JEE_SubStrRange(vText, 6) ;fghijklmnopqrstuvwxyz
return
;==================================================
q:: ;test 'InStrEx'
vText := "a a a a a"
vOcc := 1
;vOcc := 2
;note: values in comments are values when vOcc = 1
MsgBox, % JEE_InStrEx(vText, "a", 0, 1, vOcc) ;1
MsgBox, % JEE_InStrEx(vText, "a", 0, 2, vOcc) ;3
MsgBox, % JEE_InStrEx(vText, "a", 0, 3, vOcc) ;3
MsgBox, % JEE_InStrEx(vText, "a", 0, -3, vOcc) ;7
MsgBox, % JEE_InStrEx(vText, "a", 0, -2, vOcc) ;9
MsgBox, % JEE_InStrEx(vText, "a", 0, -1, vOcc) ;9
MsgBox, % JEE_InStrEx(vText, "a", 0, 1, -vOcc) ;1
MsgBox, % JEE_InStrEx(vText, "a", 0, 2, -vOcc) ;1
MsgBox, % JEE_InStrEx(vText, "a", 0, 3, -vOcc) ;3
MsgBox, % JEE_InStrEx(vText, "a", 0, -3, -vOcc) ;7
MsgBox, % JEE_InStrEx(vText, "a", 0, -2, -vOcc) ;7
MsgBox, % JEE_InStrEx(vText, "a", 0, -1, -vOcc) ;9
return
;==================================================
;same as InStr with some slight differences:
;- vPos specifies the start position, but not the search direction
;e.g. vPos := 3 means search from 3rd char (forwards/backwards depending on vOcc)
;e.g. vPos := -3 means search from 3rd-to-last char (forwards/backwards depending on vOcc)
;- AHK v2 style is used, so: -1 means last char, -2 means 2nd-to-last char
;- vOcc specificies the occurrence, and the search direction
;use positive vOcc to search forwards, use negative vOcc to search backwards
;e.g. vOcc := 3 means 3rd occurrence at/after position (search forwards)
;e.g. vOcc := -3 means 3rd occurrence at/before position (search backwards)
JEE_InStrEx(vText, vNeedle, vCaseSen=0, vPos=1, vOcc=1)
{
if (vPos = 0) || (vOcc = 0)
return ""
vIsV1 := !!SubStr(1,0)
if (vOcc < 0) && (vPos > 0)
vPos := - StrLen(vText) - !vIsV1 + vPos
else if (vOcc > 0) && (vPos < 0)
vPos := StrLen(vText) + vIsV1 + vPos
else if (vOcc < 0) && (vPos < 0)
vPos += vIsV1
return InStr(vText, vNeedle, vCaseSen, vPos, Abs(vOcc))
}
;==================================================
;specify first and last chars of text to retrieve
JEE_SubStrRange(vText, vPos1, vPos2="")
{
if (vPos2 = "")
return SubStr(vText, vPos1)
else
return SubStr(vText, vPos1, vPos2-vPos1+1)
}