Hello experts,
I would like to remove extra comma in different locations of the text. Sometimes, front, back, and in the middle. In addition, there might be a double at the front or in the end. Is there a way to do that? Thank you.
data Have;
infile datalines delimiter='#';
input Comments : $200. ;
datalines;
, , FAILURE TO THRIVE #
CHOLESTASIS, , ANEMIA#
UGESTAGE=33.4 WKS , ROP #
ASD, , #
, NON VERBAL,
;
run;
data want;
infile datalines delimiter='#';
input Comments : $200. ;
datalines;
FAILURE TO THRIVE #
CHOLESTASIS, ANEMIA#
UGESTAGE=33.4 WKS , ROP #
ASD#
NON VERBAL
;
run;
data Have;
infile datalines delimiter='#';
input Comments : $200. ;
datalines;
, , FAILURE TO THRIVE #
CHOLESTASIS, , ANEMIA#
UGESTAGE=33.4 WKS , ROP #
ASD, , #
, NON VERBAL,
;
run;
data want;
set have;
temp=prxchange('s/,\s*,/,/',-1,Comments);
want=prxchange('s/^\s*,\s*|\s*,\s*$//',-1,temp);
drop temp;
run;
Always comma-space-comma? Use the TRANWRD function.
Comma at the end: Use the STRIP() function to remove leading and trailing blanks, then find the last character and remove it using
IF SUBSTR(REVERSE(string),1,1)=',' THEN STRING=SUBSTR(STRING,1,LENGTH(STRING)-1);
Comma at the beginning: obvious modification of the code to remove comma at the end
data Have;
infile datalines delimiter='#';
input Comments : $200. ;
datalines;
, , FAILURE TO THRIVE #
CHOLESTASIS, , ANEMIA#
UGESTAGE=33.4 WKS , ROP #
ASD, , #
, NON VERBAL,
;
run;
data want;
set have;
temp=prxchange('s/,\s*,/,/',-1,Comments);
want=prxchange('s/^\s*,\s*|\s*,\s*$//',-1,temp);
drop temp;
run;
One of these days, I need to learn regular expressions. You have quite a mastery of them!
Which kind of brings up a question: I am pretty good at parsing strings using built in SAS functions such as SUBSTR() and ANYDIGIT() and dozens of other ones., what is the benefit of regular expressions over and above what SAS provides?
Thanks, @Ksharp , regular expressions are definitely on my list of things to learn, along with 27 bazillion other things (some of them having nothing to do with SAS).
It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.
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.