InStr()

Searches for a given occurrence of a string, from the left or the right.

FoundPos := InStr(Haystack, Needle , CaseSensitive := false, StartingPos := 1, Occurrence := 1)

Parameters

Haystack

The string whose content is searched.

Needle

The string to search for.

CaseSensitive

If the parameter CaseSensitive is omitted or false, the search is not case sensitive (the method of insensitivity depends on StringCaseSense); otherwise, the case must match exactly.

StartingPos

If StartingPos is omitted, it defaults to 1 (the beginning of Haystack). Otherwise, specify 2 to start at the second character, 3 to start at the third, and so on.

If StartingPos is beyond the length of Haystack, 0 is returned. [AHK_L 57+]: If StartingPos is 0 or negative, the search is conducted in reverse (right-to-left) beginning at that offset from the end.

Regardless of the value of StartingPos, the return value is always relative to the first character of Haystack. For example, the position of "abc" in "123abc789" is always 4.

Occurrence [AHK_L 57+]

If Occurrence is omitted, it defaults to the first match of the Needle in Haystack. Specify 2 for Occurrence to return the position of the second match, 3 for the third match, etc.

Return Value

This function returns the position of an occurrence of the string Needle in the string Haystack. Position 1 is the first character; this is because 0 is synonymous with "false", making it an intuitive "not found" indicator.

An occurrence of an empty string ("") can be found at any position; therefore, if Needle is an empty string, the return value is 1. As a blank Needle would typically only be passed by mistake, it will be treated as an error in AutoHotkey v2.

Remarks

This function is a combination of IfInString and StringGetPos.

RegExMatch() can be used to search for a pattern (regular expression) within a string, making it much more flexible than InStr(). However, InStr() is generally faster than RegExMatch() when searching for a simple substring.

RegExMatch(), StringGetPos, IfInString, StringCaseSense, if var in/contains MatchList, if var between, if var is type

Examples

Reports the 1-based position of the substring "abc" in the string "123abc789".

MsgBox % InStr("123abc789", "abc") ; Returns 4

Searches for Needle in Haystack.

Haystack := "The Quick Brown Fox Jumps Over the Lazy Dog"
Needle := "Fox"
If InStr(Haystack, Needle)
    MsgBox, The string was found.
Else
    MsgBox, The string was not found.

Demonstrates the difference between a case insensitive and case sensitive search.

Haystack := "The Quick Brown Fox Jumps Over the Lazy Dog"
Needle := "the"
MsgBox % InStr(Haystack, Needle, false, 1, 2) ; case insensitive search, return start position of second occurence
MsgBox % InStr(Haystack, Needle, true) ; case sensitive search, return start position of first occurence, same result as above