I want to find if a variable exisits in a string (&fixed) and if so, which word number.
%LET fixed = %STR(variable1 region1 variable3);
%IF %INDEX(&fixed, regio) %THEN
%DO;
%LET regioxc = %SCAN(&fixed, %SYSFUNC(FIND(&fixed, regio)));
%END;
I want to create a macro variable called regioxc, which could be equal to either region1 one time, and the next time the macro is run it could be equal to regiodc, or something else (always with the beginning string 'regio'), if that is the region variable specified within the &fixed string. This only works if the regio variable is specified first within the &fixed string, but in this case it is the second variable, so this does not work. I cannot find a robust method of creating the variable (word) count value from the &fixed string to be able to use the scan function. I know it should be 2, in this case. Any help here would be much appreciaited.
A bit easier to see this using data step functions. What you want to do is use the index
result to inform substring
, then use scan
on that substring. That way it's always the first word. scan
looks for which # of word, remember, not which position. If you were find
ing a whole word you could use findw
or indexw
, but since you're finding only a part of a word but want the whole thing returned, you can't really do that.
data want;
fixed="variable1 region1 variable3";
if index(fixed,"regio") then do;
regioxc = scan(substr(fixed,index(fixed,"regio")),1);
end;
put _all_;
run;
In macro variables you can still do this:
%LET fixed = %STR(variable1 region1 variable3);
%LET regioxc = %SCAN(%substr(&fixed,%index(&fixed,regio)),1);
%put &=regioxc;
(I leave out the %if
to make it easier to see it work, of course in production code put it back in.)