InStr()

AutoHotkey

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.

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.

Related

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

Example

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

; Example 2
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.

; Example 3
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