INSTR function

Purpose

Search a string for the existence of a second string.

Syntax

y& = INSTR([Position&,] MainStr$, [ANY] MatchStr$)

Remarks

INSTR returns the position of MatchStr$ within MainStr$.  The return value is indexed to one, while zero means "not found".

Position& specifies the character position to begin the search.  If Position& is one or greater, MainStr$ is searched left to right.  The value one starts at the first character, two the second, etc.  If Position& is -1 or less, MainStr$ is searched from right to left.  The value -1 starts at the last character, -2 the second to last, etc.  If Position& is not given, the default value of +1 is assumed.

x& = INSTR("xyz", "y")  ' returns 2

x& = INSTR("xyz", "a")  ' returns 0

a$ = "My Dog" : b$ = " "

x& = INSTR(a$, b$)      ' returns 3

It is important to note that in all cases, even when Position& is negative, the return value of INSTR() is the absolute position of the match, from left to right, starting with the first character.

ANY

If the ANY keyword is included, MatchStr$ specifies a list of single characters.  INSTR searches for each of these characters individually. As soon as any one of these characters is found, INSTR returns the position of the match.

x& = INSTR(-2, "efcdef", ANY "ef")   returns a result of 5

INSTR is case-sensitive, meaning that upper-case and lower-case letters must match exactly in MatchStr$ and MainStr$.

Restrictions

Special search terms are evaluated in this sequence:

  1. If Position& is zero, or beyond the length of MainStr$, the value zero is returned.

  2. If MainStr$ is null, the value zero is returned.

  3. If MatchStr$ is null, the absolute Position& value (default of 1) is returned.

See also

EXTRACT$, LCASE$, LEFT$, LTRIM$, MID$, RIGHT$, RTRIM$, SHRINK$, TALLY, TRIM$, UCASE$, VERIFY

Example

' x$ = first command-line argument, assuming spaces, commas,
' periods, and tabs are valid delimiters.

IF INSTR(COMMAND$, ANY " ,." + CHR$(9)) > 0 THEN

 x$ = "There is more than one command-line argument"

ELSE

 x$ = "There is at most one command-line argument"

END IF