StringGetPos

获取指定的子字符串在某个字符串中的位置.

过时的: 不推荐在新脚本中使用此命令. 请使用 InStr 函数代替.

StringGetPos, OutputVar, InputVar, SearchText , Occurrence, Offset

参数

OutputVar

用来存储获取的相对于 InputVar 首个字符的位置的变量名. StringGetPos 中首个字符的位置为 0, 而 InStr() 中首个字符的位置为 1.

InputVar

内容将被搜索的输入变量名. 不要把名称括在百分号中, 除非您希望使用变量的 内容 作为被解析的变量名.

SearchText

要搜索的字符串. 如果没有启用 StringCaseSense, 那么匹配过程不区分大小写.

Occurrence

如果 SearchTextInputVar 中出现多次, 此参数影响那个将被找到. 如果省略此参数, 默认为 L1(意味着将从 InputVar 左边开始查找首个匹配). 要更改此行为, 请指定以下选项之一:

Ln:InputVar 的左边开始搜索, 并继续向右直到找到第 n 个匹配.

Rn:InputVar 的右边开始搜索, 并继续向左直到找到第 n 个匹配. 如果 n 省略(或 Occurrence 参数为 1), 默认为 R1.

例如, 要找到从右边开始的第四个匹配, 请指定 R4. 注意: 如果 n 小于或等于零, 将找不到匹配.

Offset

最左边或最右边 (取决于上面的参数) 需要跳过的字符数. 省略时默认为 0. 例如, 后面的语句会从左边的第十个字符开始查找:StringGetPos, OutputVar, InputVar, abc, , 9. 此参数可以为表达式.

ErrorLevel

InputVar 中的指定位置没有找到 SearchTextErrorLevel 被置为 1, 否则为 0.

备注

StringMidInStr() 不同, StringGetPos 中首个字符的位置为 0.

获取的位置总是相对于 InputVar 的首个字符, 不受 Occurrence 和/或 Offset 的值影响. 例如, 如果在 123abc789 中查找 "abc", 那么获取的位置总为 3, 而不论查找的参数如何.

如果 SearchText 不存在于 InputVar 中的指定出现位置, 那么 OutputVar 将被置为 -1 且 ErrorLevel 被置为 1.

使用 SplitPath 可以更容易地将文件路径分解为目录, 文件名和扩展名.

内置变量 %A_Space%%A_Tab% 分别包含了单个空格和单个 tab 字符. 当您需要搜索单独的空格或 tab 或在 SearchText 的开始或末尾含有空格或 tab 时, 这很有用.

InStr(), RegExMatch(), IfInString, if var in/contains MatchList, StringCaseSense, StringReplace, SplitPath, StringLeft, StringRight, StringMid, StringTrimLeft, StringTrimRight, StringLen, StringLower, StringUpper, if var is type

示例

检索和分析一个子字符串的位置.

Haystack := "abcdefghijklmnopqrs"
Needle := "def"
StringGetPos, pos, Haystack, %Needle%
if (pos >= 0)
    MsgBox, The string was found at position %pos%.

把文件的完整路径名分解成各个部分. 注意使用 StrSplit(), StringSplit解析循环会更容易, 这里只是为了演示.

FileSelectFile, file, , , Pick a filename in a deeply nested folder:
if (file != "")
{
    pos_prev := StrLen(file)
    pos_prev += 1 ; 改变位置到最后一个字符的后面.
    Loop
    {
        ; 从右边开始查找第 N 个匹配:
        StringGetPos, pos, file, \, R%A_Index%
        if ErrorLevel
            break
        length := pos_prev - pos - 1
        pos_prev := pos
        pos += 2  ; 进行调整以便使用 StringMid.
        StringMid, path_component, file, %pos%, %length%
        MsgBox Path component #%A_Index% (from the right) is:`n%path_component%
    }
}
unixetc