BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
Agent1592
Pyrite | Level 9

 Hi guys:

I am looking for a smart solution to remove the last character (last two characters) from a string that is preceded by a space(blank). I know how to do it for the & character but I am not sure about the others. I have more than 23,000 company names and I would not like to strip these company names from letters accidentally. 

 

data test;
input cname $40.;
string=prxchange('s/\&&$//',-1,strip(ur_string));
cards;
A G SIMPSON AUTOMOTIVE &
A G SIMPSON AUTOMOTIVE A A G SIMPSON AUTOMOTIVE I A G SIMPSON AUTOMOTIVE C A G SIMPSON AUTOMOTIVE U A G SIMPSON AUTOMOTIVE H A G SIMPSON AUTOMOTIVE H
A G SIMPSON AUTOMOTIVE PA ; run;

 

1 ACCEPTED SOLUTION

Accepted Solutions
PGStats
Opal | Level 21

To remove a space followed by 1 or 2 non spaces, possibly followed by spaces until the end of the string:

 

data test;
input cname $60.;
string=prxchange('s/\s\S{1,2}\s*$//o', 1, cname);
cards;
A G SIMPSON AUTOMOTIVE &
A G SIMPSON AUTOMOTIVE A
A G SIMPSON AUTOMOTIVE I
A G SIMPSON AUTOMOTIVE C
A G SIMPSON AUTOMOTIVE U
A G SIMPSON AUTOMOTIVE H
A G SIMPSON AUTOMOTIVE H
A G SIMPSON AUTOMOTIVE PA
A G SIMPSON AUTOMOTIVE INC
;

proc print; run;
PG

View solution in original post

3 REPLIES 3
PGStats
Opal | Level 21

To remove a space followed by 1 or 2 non spaces, possibly followed by spaces until the end of the string:

 

data test;
input cname $60.;
string=prxchange('s/\s\S{1,2}\s*$//o', 1, cname);
cards;
A G SIMPSON AUTOMOTIVE &
A G SIMPSON AUTOMOTIVE A
A G SIMPSON AUTOMOTIVE I
A G SIMPSON AUTOMOTIVE C
A G SIMPSON AUTOMOTIVE U
A G SIMPSON AUTOMOTIVE H
A G SIMPSON AUTOMOTIVE H
A G SIMPSON AUTOMOTIVE PA
A G SIMPSON AUTOMOTIVE INC
;

proc print; run;
PG
andreas_lds
Jade | Level 19

Another solution without regular expressions:

 

data test;
   length cname $ 40 string $ 40 ;
   input cname $40.;

   string = substr(cname, 1, findc(trim(cname), ' ', 'b'));

   cards;
A G SIMPSON AUTOMOTIVE &A G SIMPSON AUTOMOTIVE A
A G SIMPSON AUTOMOTIVE I
A G SIMPSON AUTOMOTIVE C
A G SIMPSON AUTOMOTIVE U
A G SIMPSON AUTOMOTIVE H
A G SIMPSON AUTOMOTIVE HA G SIMPSON AUTOMOTIVE PA
; 
run;

Ready to join fellow brilliant minds for the SAS Hackathon?

Build your skills. Make connections. Enjoy creative freedom. Maybe change the world. Registration is now open through August 30th. Visit the SAS Hackathon homepage.

Register today!
How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 3 replies
  • 1488 views
  • 5 likes
  • 3 in conversation