IndigoChild
IndigoChild

Reputation: 844

SAS remove the last characters if special

I have a sas dataset with the variable called response, which has the following records:

enter image description here

and so on.

These are all the same records, I need to remove the last character wherever special and return the records as

enter image description here

When I use a compress function, it removes the asterisk in between and returns: TrailerOffer which is not what I want. Can somebody please help me code this? I need to remove the last characters if these are special.

Upvotes: 0

Views: 930

Answers (2)

Richard
Richard

Reputation: 27536

You can use regular expression character classes to specify the 'special' trailing characters. In this example replacement pattern, any characters that are not letters or numbers will be removed. \s* is needed before $ because SAS character variables will have trailing spaces when their values are passed to the regex engine.

Learn more about regular expression class groupings in the SAS documentation

data have;
length response $20.; input response; datalines;
Trailer*Offer
Trailer*Offer*
Trailer*Offer???
Trailer*Offer?...
Offer#1
Offer#1?
Offer#1*?
;
data want;
  set have;
  response = prxchange ('s/[^a-z0-9]+\s*$//i', 1, response);
run;

enter image description here

Upvotes: 1

Kermit
Kermit

Reputation: 3117

Using PRXCHANGE

prx=prxchange("s/^W*(.*?)\W*$/$1/",-1, response);

will remove trailing special characters

data have;
length response $20.;
response="Trailer*Offer";output;
response="Trailer*Offer*";output;
response="Trailer*Offer???";output;
response="Trailer*Offer?...";output;
run;

data _null_;
set have;
prx=prxchange("s/^W*(.*?)\W*$/$1/",-1, response);
put prx;
run;
 77         
 78         data _null_;
 79         set have;
 80         prx=prxchange("s/^W*(.*?)\W*$/$1/",-1, response);
 81         put prx;
 82         run;
 
 Trailer*Offer
 Trailer*Offer
 Trailer*Offer
 Trailer*Offer

Upvotes: 1

Related Questions