INSTR function

Purpose

Search a string for the existence of a second string.

Syntax

y& = INSTR([Position&,] Main$, [ANY] Match$)

Remarks

INSTR returns the position of Match$ within Main$.  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, Main$ is searched left to right.  The value one starts at the first character, two the second, etc.  If Position& is -1 or less, Main$ 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, Match$ 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 Match$ and Main$.

Restrictions

Special search terms are evaluated in this sequence:

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

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

  3. If Match$ 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