I have a variable with values like
TUXEDO PARTNERS INC-AT
KEYES HOWARD AUTO DLRHSPS-PX
SPRING HILL FORD INC-CH
MEGASTAR INC
BRANDON CHRY-PLYM INC-TM
The ending "-XX" is the city abbreviations. I want to remove this part.
It can't be coded as removing characters after "-" because "-" can appear in the middle of the string. Or remove the last three characters because some values don't have ending "-XX".
Any tips on dealing with this situation?
Thanks!
data have;
input str $40.;
cards;
TUXEDO PARTNERS INC-AT
KEYES HOWARD AUTO DLRHSPS-PX
SPRING HILL FORD INC-CH
MEGASTAR INC
BRANDON CHRY-PLYM INC-TM
;
data want;
set have;
_n_=findc(str,'-','b');
if _n_ then want=substr(str,1,_n_);
else want=str;
run;
I hope you did not mean _n_ 🙂
@smantha wrote:
I hope you did not mean _n_ 🙂
@novinosrin seems to like playing with fire and often uses a variable _n_ instead of considering the possible confusion with the SAS automatic variable of the same name.
Using PRXMATCH to determine if the string ends with "-XX":
data have;
input str $40.;
cards;
TUXEDO PARTNERS INC-AT
KEYES HOWARD AUTO DLRHSPS-PX
SPRING HILL FORD INC-CH
MEGASTAR INC
BRANDON CHRY-PLYM INC-TM
TEST-ABC-DEF-XX
;
run;
data want;
set have;
if prxmatch('/(\w+)-\w\w\s*$/', str)
then want = substr(str, 1, length(str)-3);
else want=str;
run;
data have;
input str $40.;
cards;
TUXEDO PARTNERS INC-AT
KEYES HOWARD AUTO DLRHSPS-PX
SPRING HILL FORD INC-CH
MEGASTAR INC
BRANDON CHRY-PLYM INC-TM
;
run;
data want;
set have;
rev_str=(strip(reverse(str)));
new_str=strip(reverse(substr(rev_str,index(rev_str,'-')+1)));
drop rev_str;
run;
data have;
input str $40.;
want=prxchange('s/-\w\w$//',-1,strip(str));
cards;
TUXEDO PARTNERS INC-AT
KEYES HOWARD AUTO DLRHSPS-PX
SPRING HILL FORD INC-CH
MEGASTAR INC
BRANDON CHRY-PLYM INC-TM
;
data have;
input str $40.;
want=prxchange('s/-\w\w\s*$//',1,str);
cards;
TUXEDO PARTNERS INC-AT
KEYES HOWARD AUTO DLRHSPS-PX
SPRING HILL FORD INC-CH
MEGASTAR INC
BRANDON CHRY-PLYM INC-TM
;
April 27 – 30 | Gaylord Texan | Grapevine, Texas
Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—just $495!
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.
Ready to level-up your skills? Choose your own adventure.