When working with strings in SAS, you can remove specific characters from a string with the SAS compress() function.

For example, if we wanted to remove the letters “a” and “b” from a string, we could do so with the following SAS code.

data k;
    a = 'Alfred and Betty went to the beach to play with a ball. ';
    b = compress(a,"abAB");
    put b=;
run;

/* Output: */
b=lfred nd etty went to the ech to ply with  ll.

When working with string variables in our SAS programs, the ability to be able to easily manipulate and change string variables is valuable.

One such case is when we want to remove specific characters from a string.

The SAS compress() function allows us to remove characters from strings easily.

compress() takes 3 arguments. The first argument is a character variable. The second argument is the characters you want to keep or remove – we can keep characters with compress() as well. For the third argument, you can add modifiers.

Below is an example of how you can remove specific characters from a string using compress() in SAS. In the example below, we are remove all “a”, “b”, “A”, and “B” characters.

data k;
    a = 'Alfred and Betty went to the beach to play with a ball. ';
    b = compress(a,"abAB");
    put b=;
run;

/* Output: */
b=lfred nd etty went to the ech to ply with  ll.

Removing Special Characters from a String in SAS with compress() Function

A common case where you might need to remove characters from a string variable is when you need to remove special characters from a string.

Special characters include punctuation, quotes, parentheses, etc.

We can remove special characters from a string variable in SAS with the help of the compress() function modifiers.

We can pass “kas” as a modifier which keeps (k) the alphabetical characters (a) and spaces (s) of a string variable.

data k;
    a = 'This is a -- string with some ^ ?,. special ## characters.';
    b = compress(a,,"kas");
    put b=;
run;

/* Output: */
b=This is a  string with some   special  characters

Hopefully this article has been useful for you to learn how to remove characters from strings in SAS.

Categorized in:

SAS,

Last Update: February 26, 2024