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

 

sas-innovate-2026-white.png



April 27 – 30 | Gaylord Texan | Grapevine, Texas

Registration is open

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!

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
  • 1129 views
  • 8 likes
  • 3 in conversation