Fede
Fede

Reputation: 31

Replace specific characters (a list of them) in a string without removing blanks

I'm trying to work with manually inserted strings in SAS and I need to remove specific special characters (maybe by inserting a list of them) without removing blank spaces between words.

I've found a possible solution with a combination of compbl and transtrn to remove special characters and substitute them with blanks, reduced to one by compbl but this requires multiple steps.

I'm wondering if there is a function that allows me to do this in a single step. I've tried with the compress function (with the 'k' modifier to keep only letters and digits) but it removes blanks between words.

I'd like to go from a string like this one:

O'()n?e /, ^P.iece

To:

One Piece

With a single blank between the two words.

If someone can help me it would be awesome!

Upvotes: 2

Views: 1532

Answers (2)

Sanek Zhitnik
Sanek Zhitnik

Reputation: 726

Use the next tags for compress function:

k -- Keep chars instead replace it

a -- Alphabetic chars

s -- Space characters

d -- Digits

And after it, use function COMPBL.

Code:

data have;
   value="O'()n?e /, ^P.iece";
run;

data want;
   set have;
   value_want=COMPBL((compress(value,,"kasd"));
run;

        

So:

+--------------------+------------+
|       value        | value_want |
+--------------------+------------+
| O'()n?e /, ^P.iece | One Piece  |
+--------------------+------------+

Upvotes: 1

Llex
Llex

Reputation: 1770

You could use regex and prxchage.

data have;
   value="O'()n?e /, ^P.iece";
run;

data want;
   set have;
   value_want=value_want=prxchange("s/\s\s+/ /",-1,prxchange("s/[^a-zA-Z0-9\s]*//",-1,value));
run;

Result:

+--------------------+------------+
| value              | value_want |
+--------------------+------------+
| O'()n?e /, ^P.iece | One Piece  |
+--------------------+------------+

Upvotes: 0

Related Questions