BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
Sas48
Calcite | Level 5
Hi,
I am looking for a way to replace only the last ‘,’ with ‘and’ , if there are multiple instances of ‘,’

Tranwd replaces all instances of ‘,’ with ‘and’

Input:
Alpha beta , for a , for b , for c
Expected output:
Alpha beta , for a , for b and for c

Thank you.




1 ACCEPTED SOLUTION

Accepted Solutions
Patrick
Opal | Level 21

And just for fun here a RegEx option.

data sample;
  infile datalines truncover;
  input have_string $50.;

  /* define want_string with a length long enough to ensure there is never string truncation */
  if 0 then want_string=have_string||'and';

  want_string=prxchange('s/ *, *([^,]+)$/ and $1/oi',1,strip(have_string));

  datalines;
Alpha beta , for a , for b , for c
Alpha beta , for a , for b, for c
Alpha beta , for a , for b,for c
;

proc print data=sample;
run;

Patrick_0-1632535386557.png

 

View solution in original post

2 REPLIES 2
Shmuel
Garnet | Level 18

You can use next code:

ix = index(varname,',',-1);   * -1 scans right to left;
if ix > 0 then   /* 0 means no comma found */
varname = substr(varname,1,ix-1) || ' and ' || substr(varname, ix+1);

You may nead assign new length to the varnamre as length('and") > lenght(',').

Patrick
Opal | Level 21

And just for fun here a RegEx option.

data sample;
  infile datalines truncover;
  input have_string $50.;

  /* define want_string with a length long enough to ensure there is never string truncation */
  if 0 then want_string=have_string||'and';

  want_string=prxchange('s/ *, *([^,]+)$/ and $1/oi',1,strip(have_string));

  datalines;
Alpha beta , for a , for b , for c
Alpha beta , for a , for b, for c
Alpha beta , for a , for b,for c
;

proc print data=sample;
run;

Patrick_0-1632535386557.png

 

hackathon24-white-horiz.png

2025 SAS Hackathon: There is still time!

Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!

Register Now

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 2 replies
  • 994 views
  • 8 likes
  • 3 in conversation