Solved
New Contributor
Posts: 2

# How do I perform a conditional substitution using PRXCHANGE?

I'm trying to write to conditionally substitute portions of a text string. For example, if I have:

A123

AX345

B456

BY789

I want the values in my data set to be:

AX123

AX345

BY456

BY789

Is there a way to accomplish this in one prxchange statement?

(Using SAS 9.4.)

Accepted Solutions
Solution
‎08-13-2016 12:27 AM
Super User
Posts: 10,784

## Re: How do I perform a conditional substitution using PRXCHANGE?

```data have;
input x \$ y \$;
length want pid \$ 40;
pid=cats('s/^([a-z])[a-z]*(\d+)/\$1',y,'\$2/i');
want=prxchange(pid,1,x);
cards;
A123 X
AX345 X
B456 Y
BY789 Y
;
run;

```

All Replies
Super User
Posts: 10,784

## Re: How do I perform a conditional substitution using PRXCHANGE?

```Assuming the data is just like what you posted:

data have;
input x \$20.;
cards;
A123
AX345
B456
BY789
;
run;
data have;
set have;
group=first(x);
n=length(x);
run;
proc sort data=have;
by group n;
run;
data want;
do until(last.group);
set have;
by group;
end;
_x=x;
do until(last.group);
set have;
by group;
x=scan(_x,1,,'d')||scan(x,-1,,'kd');
output;
end;
drop _x group n;
run;

```
Super User
Posts: 9,599

## Re: How do I perform a conditional substitution using PRXCHANGE?

Depends on several factors, is it just two, then:

```data have;
input x \$20.;
cards;
A123
AX345
B456
BY789
;
run;
data want;
set have;
x=ifc(substr(x,1,1)="A",cats("AX",compress(x," ","kd")),cats("BY",compress(x," ","kd")));
run;```

If its more, but you know them up front then:

```data want;
set have;
select(substr(x,1,1));
when ("A") x=cats("AX",compress(x," ","kd"));
when ("B") x=cats("BY",compress(x," ","kd"));
otherwise;
end;
run;
```

If you don't know them up front then you will need to provide the logic to populate them, I.e. you could have AX and AY?

New Contributor
Posts: 2

## Re: How do I perform a conditional substitution using PRXCHANGE?

The second alpha character is always known.

Is there a way to do this using PRXCHANGE?

Solution
‎08-13-2016 12:27 AM
Super User
Posts: 10,784

## Re: How do I perform a conditional substitution using PRXCHANGE?

```data have;
input x \$ y \$;
length want pid \$ 40;
pid=cats('s/^([a-z])[a-z]*(\d+)/\$1',y,'\$2/i');
want=prxchange(pid,1,x);
cards;
A123 X
AX345 X
B456 Y
BY789 Y
;
run;

```
☑ This topic is solved.