Sandra Guerrero
Sandra Guerrero

Reputation: 323

Macro variable contains another substrings in either order SAS

I'm trying validate if a char macro variable contains another substrings in either order.

%let variable = Coop Fin TDC Real Telco;

options mlogic mprint symbolgen;
%Macro Test/minoperator;
    %if Coop Fin in &variable %then %put i = 1;
    %else %put i = 0;
%mend;
%Test;

Coop Fin in &variable resolves to TRUE, but Coop TDC resolves to FALSE. Are there anything form to do it, without import order?

Upvotes: 0

Views: 730

Answers (2)

momo1644
momo1644

Reputation: 1804

You can do a regular expression matching, the logic below ignores the order:

Solution:

%let variable = Coop Fin TDC Real Telco;
options mlogic mprint symbolgen;
%Macro Test/minoperator;
    %if %sysfunc(prxmatch('Coop',"&variable.")) & %sysfunc(prxmatch('TDC',"&variable."))  %then %put i = 1;
    %else %put i = 0;
%mend;
%Test;

Output:

MLOGIC(TEST):  Beginning execution.
SYMBOLGEN:  Macro variable VARIABLE resolves to Coop Fin TDC Real Telco
SYMBOLGEN:  Macro variable VARIABLE resolves to Coop Fin TDC Real Telco
MLOGIC(TEST):  %IF condition %sysfunc(prxmatch('Coop',"&variable.")) & %sysfunc(prxmatch('TDC',"&variable.")) is TRUE
MLOGIC(TEST):  %PUT i = 1
i = 1
MLOGIC(TEST):  Ending execution.

Upvotes: 1

DomPazz
DomPazz

Reputation: 12465

If you want to check if ANY of the words exist then you need to parse in string and run for each word:

%let variable = Coop Fin TDC Real Telco;

options mlogic mprint symbolgen;
%Macro Test(input) /minoperator;
    %local j n str;
    %let n=%sysfunc(countw(&input));
    %let i=0;
    %do j=1 %to &n;
        %let str = %scan(&input,&j);
        %if &str in &variable %then %let i = 1;
        %else %put i = 0;
        ;
    %end;
    %put i = &i;
%mend;
%Test(Coop Fin);
%Test(Coop TDC);

If you want all words then you need count the number of times it resolves to true and only output if that is equal to the count.

%let variable = Coop Fin TDC Real Telco;

options mlogic mprint symbolgen;
%Macro Test(input) /minoperator;
    %local j n str;
    %let n=%sysfunc(countw(&input));
    %let i=0;
    %do j=1 %to &n;
        %let str = %scan(&input,&j);
        %if &str in &variable %then %let i = %eval(&i+1);
        ;
    %end;
    %if &i=&n %then 
       %put i = &i;
    %else %put i = 0;
    ;
%mend;
%Test(Coop Fin);
%Test(Coop TDC x);

Upvotes: 1

Related Questions