DATA Step, Macro, Functions and more

How to find a string prior to a special character

Reply
Contributor
Posts: 26

How to find a string prior to a special character

Hi Team,

 

I just wanted to retrieve the Word prior to the "=" sign. The below code I tried.

DATA T1;
LENGTH string _string str1 str2 $500;
string="Set Medicine; HEADACHE=24-JAN-2013; SEVERE=04-FEB-2013; MODERATE=04-DEC-2013";
_string=string;
Pos=0;
Curr=0;
prev=0;
 
DO WHILE (INDEX(_string,"=")>0);
Prev=prev+pos;
Pos=INDEX(_string,"=");
_string=SUBSTR(_string,pos+1,LENGTH(_string)-pos);
Curr=curr+pos;
END;
str1=SUBSTR(string, 1,prev-1);
str2=SCAN(string,-2,"="); 
 PUT str1 "," str2;
y=substr(string,(index(string,"=")),10);
 x=scan(substr(string,index(UPCASE(string),"=")),1,';');
/*scan(substr(sas_code2,index(UPCASE(sas_code2),"SELECT")),2,' ');*/
RUN;

  

Please help me to retrieve the HEADACHE SEVERE MODERATE as an output.

 

 

 

Thanks

Rajdeep

 

Super User
Super User
Posts: 9,866

Re: How to find a string prior to a special character

wHYisYoUr coDE l ikE this?  Code formatting is key to anyone understanding your code, standardised casing, indentation and such like.

Now from your logic, you can do (and note the code formatting and use of code window which is {i} above post area):

data want;
  string="Set Medicine; HEADACHE=24-JAN-2013; SEVERE=04-FEB-2013; MODERATE=04-DEC-2013";
  length param result $200;
  do i=2 to countw(string,";");
    param=scan(scan(string,i,";"),1,"=");
    result=scan(scan(string,i,";"),2,"=");
    output;
  end;
run;

Also note, you have not shown what you want to see output, so I have just guessed.

Super User
Posts: 10,860

Re: How to find a string prior to a special character

data want;
  string="Set Medicine; HEADACHE=24-JAN-2013; SEVERE=04-FEB-2013; MODERATE=04-DEC-2013";
pid=prxparse('/\w+(?==)/');
s=1;e=length(string);
call prxnext(pid,s,e,string,p,l);
do while(p>0);
 want=substr(string,p,l);
 output;
 call prxnext(pid,s,e,string,p,l);
end;
drop pid p l s e;
run;
Ask a Question
Discussion stats
  • 2 replies
  • 112 views
  • 2 likes
  • 3 in conversation