SAS Functions

Extract a Substring in SAS with SUBSTR

In SAS you can use the SUBSTR function to read a part of a string. You indicate the input string, the start position, and the number of characters you want to read.

SUBSTR(string, start position, number of characters to read)

For example, you have a data set with zip codes. Each zip code contains four numbers and two characters (in this order). To separate the numbers and the characters and store them in different variables you can use the following code.

data work.ds;
	input zipcode $;

data work.ds_substr;
	set work.ds;
	zipcode_numbers = substr(zipcode, 1,4);
	zipcode_chars = substr(zipcode, 5,2);

If you would like to find and replace a substring, check out this post. If you only want to check if a string contains a substring, see this example.

You can find the official SAS documentation about the SUBSTR function here.

One thought on “Extract a Substring in SAS with SUBSTR

Comments are closed.