DATA Step, Macro, Functions and more

string function

Reply
Super Contributor
Posts: 702

string function

How to achieve this?

if a varaible has values
finance_data_scores_income.rpt
finace_scores.rpt


the desired output is (to remove _scores_income.rpt and _scores.rpt)
finance_data
finance

Super User
Posts: 22,857

Re: string function

Are those the only ones or does this need to be generalized?

If only those words, look at TRANWRD() function to replace/remove the text. 

Trusted Advisor
Posts: 1,826

Re: string function

There are more than one way to achieve it, assuming that TEXT_IN is the variable which contains the string to check:

 

1) result = substr(text_in, 1, find(text_in,'_scores'));

 

2) if text_in = 'finance_data_scores_income.rpt' then result = 'finance_data'; else

    if text_in = 'finace_scores.rpt'                         then result = 'finance';

 

3) text1 = 'finance_data_scores_income.rpt';

    text2 = 'finace_scores.rpt';

    length1 = length(text1);

    length2 = length(text2);

    

   lengthx = length(text_in);

   select (lengthx);

      when (length1) result = 'finance_data';

      when (length2) result =  'finance';;

   end;

 

PROC Star
Posts: 1,340

Re: string function

data have;

input var $50.;

datalines;

finance_data_scores_income.rpt

finance_scores.rpt

;

 

data want;

set have;

k= index(var,'_scores.rpt');

if k>0 then substr(var,k)=' ';

else do;

k=index(var,'_scores_income.rpt');

if k>0 then substr(var,k)=' ';

end;

drop k;

run;

Super Contributor
Posts: 702

Re: string function

Posted in reply to novinosrin

the files will have many variations not just limited to scores.rpt or _scores_income.rpt. 

Super User
Posts: 22,857

Re: string function

Then you need to provide a better sample data set that reflects your actual situation.
Super User
Posts: 10,618

Re: string function


data have;
input x $40.;
want=prxchange('s/_scores[_a-z]*\.rpt//i',-1,x);
cards;
finance_data_scores_income.rpt
finace_scores.rpt
;
run;


Super Contributor
Posts: 702

Re: string function

Thanks KSharp, I tried to improvise the code by passing a macro variable in place of _scores instead and it failed:

 

want=prxchange("s/_&name.[_a-z]*\.rpt//i",-1,x);

 

ERROR message:

 

8  !  array charvar
ERROR 200-322: The symbol is not recognized and will be ignored.

Super User
Posts: 10,618

Re: string function

You could try this one.

 

%let name=scores;
data have;
input x $40.;
pid=cats('s/_',"&name",'[_a-z]*\.rpt//i');
want=prxchange(pid,-1,x);
cards;
finance_data_scores_income.rpt
finace_scores.rpt
;
run;
Ask a Question
Discussion stats
  • 8 replies
  • 206 views
  • 3 likes
  • 5 in conversation