You can use the ANYDIGIT function in SAS to return the position of the first digit in a given string.
This function uses the following basic syntax:
- expression: The string to search
- start (optional): The starting position to search from.
The following example shows how to use this function in practice.
Example: Using the ANYDIGIT Function in SAS
Suppose we have the following dataset in SAS that contains information about various employees at some company:
/*create dataset*/ data my_data; input employeeID $ sales; datalines; 54AAF 23 0009A 38 BC18B 40 09H30 12 04429 65 B1300 90 B1700 75 RRHHJ 35 0Y009 40 C6500 23 ; run; /*view dataset*/ proc print data=my_data;
We can use the ANYDIGIT function to search for the position of the first digit in the employeeID column:
/*create new dataset*/ data new_data; set my_data; firstDigit = anydigit(employeeID); run; /*view new dataset*/ proc print data=new_data;
The new column called firstDigit displays the position of the first occurrence of any digt in the employeeID column.
- The first digit in 54AAF is in position 1.
- The first digit in 0009A is in position 1.
- The first digit in BC18B is in position 3.
And so on.
If there are no digits for a given employee ID, then a value of 0 is returned.
We can also use the start argument within the ANYDIGIT function to specify a starting position to search from.
For example, we can use the following code to search for the position of the first digit in the employeeID column starting from position 3:
/*create new dataset*/ data new_data; set my_data; firstDigit = anydigit(employeeID, 3); run; /*view new dataset*/ proc print data=new_data;
Notice that employeeID values that only contain an alphabetical character in the first two positions now receive a value of 0 in the firstDigit column since the search for digits now starts at position 3.
The following tutorials explain how to use other common functions in SAS:
How to Remove Special Characters from Strings in SAS
How to Replace Characters in a String in SAS
How to Convert Character Variable to Numeric in SAS