Subtitute with pearl function

Super Contributor
Posts: 319

Subtitute with pearl function

Dear all,

How can prxchange function ne used to substitute variable a in table have A with 1 , B with 2, C with 3, D with 4.

I have been only able to group ([ABCD]) the searched characters , but not able to determine the substitute pattern as described above.

I know I can do it by using transtrn function but I am interested in using pearl functions.

data have;
a='2A345';output;
a='2B134';output;
a='3C124';output;
a='4D123';output;
run;

data want;
set have;
b=prxchange('s/[ABCD]/1234/i',1,a);
run;

10x

Super User
Posts: 10,770

Re: Subtitute with pearl function

No. You can't do that with prxchange() .use translate() instead.

```data have;
a='2A345';output;
a='2B134';output;
a='3C124';output;
a='4D123';output;
run;
data want;
set have;
b=translate(a,'1234','ABCD');
run;
```

Xia Keshan

Super Contributor
Posts: 319

ok, 10x.

Posts: 1,318

Re: Subtitute with pearl function

If you really wanted to accomplish this with regular expressions (say your real data is much more complex than this data) then an approach to use could be similar to the following:

data have;

a='2A345';output;

a='2B134';output;

a='3C124';output;

a='4D123';output;

run;

data want;

array r[4] \$1 _temporary_ ('1' '2' '3' '4');

prxid = prxparse('/(A)|(B)|(C)|(D)/io');

do until(done);

set have end=done;

pos = prxmatch(prxid, a);

if pos then do;

idx = prxparen(prxid);

substr(a, pos, 1) = r[idx];

end;

output;

end;

run;

PROC Star
Posts: 8,163

Re: Subtitute with pearl function

And, if you only need to change the 2nd character and its always an uppercase letter, then you could use:

data want;

set have;

substr(a,2,1)=rank(substr(a,2,1))-64;

run;

Discussion stats
• 4 replies
• 260 views
• 3 likes
• 4 in conversation