INDEX Function

Searches a character expression for a string of characters, and returns the position of the string's first character for the first occurrence of the string.

Category: Character
Restriction: I18N Level 0 functions are designed for use with Single Byte Character Sets (SBCS) only.
Tip: DBCS equivalent function is KINDEX in SAS National Language Support (NLS): Reference Guide. See DBCS Compatibility .

Syntax

INDEX(source,excerpt)

Required Arguments

source

specifies a character constant, variable, or expression to search.

excerpt

is a character constant, variable, or expression that specifies the string of characters to search for in source.

Tips Enclose a literal string of characters in quotation marks.
Both leading and trailing spaces are considered part of the excerpt argument. To remove trailing spaces, include the TRIM function with the excerpt variable inside the INDEX function.

Details

The Basics

The INDEX function searches source, from left to right, for the first occurrence of the string specified in excerpt, and returns the position in source of the string's first character. If the string is not found in source, INDEX returns a value of 0. If there are multiple occurrences of the string, INDEX returns only the position of the first occurrence.

DBCS Compatibility

The DBCS equivalent function is KINDEX, which is documented in SAS National Language Support (NLS): Reference Guide. However, there is a minor difference in the way trailing blanks are handled. In KINDEX, multiple blanks in the second argument match a single blank in the first argument. The following example shows the differences between the two functions:
index('ABC,DE F(X=Y)','       ')            => 0  
kindex('ABC,DE F(X=Y)','       ')          => 7

Examples

Example 1: Finding the Position of a Variable in the Source String

The following example finds the first position of the excerpt argument in source.
data _null_;
   a = 'ABC.DEF(X=Y)';
   b = 'X=Y';
   x = index(a,b);
   put x=;
run;
SAS writes the following output to the log:
x=9

Example 2: Removing Trailing Spaces When You Use the INDEX Function with the TRIM Function

The following example shows the results when you use the INDEX function with and without the TRIM function. If you use INDEX without the TRIM function, leading and trailing spaces are considered part of the excerpt argument. If you use INDEX with the TRIM function, TRIM removes trailing spaces from the excerpt argument as you can see in this example. Note that the TRIM function is used inside the INDEX function.
options nodate nostimer ls=78 ps=60;
data _null_;
   length a b $14;
   a='ABC.DEF (X=Y)';
   b='X=Y';
   q=index(a,b);
   w=index(a,trim(b));
   put q= w=;
run;
SAS writes the following output to the log:
q=0 w=10