BookmarkSubscribeRSS Feed
stevhill
Calcite | Level 5

I have a string for a number of hours, minutes and seconds, but not all three will necessarily be present. E.g. it might be "1h2m34s" or just "2m34s" or just "34s".

 

I want to extract the numbers from the string and assign them to appropriate variables called hour, min and sec (or similar). I'm trying to use regex and lookahead but I'm getting stuck.

 

data have;
    infile datalines;
    input hms:$100.;
datalines;
7s
52s
2m9s
3m43s
10m43s
1h2m13s
;;;;
run;

I've tried:

data get_nums_re;
    retain re_hour re_min;
    if _n_ = 1 then do;
        re_hour = prxparse("/.*\d+(?=h).*/");
        re_min = prxparse("/.*\d+(?=m).*/");
        end;
    set have;
    hour_pos = prxposn(re_hour, 1, hms);
    min_pos = prxposn(re_min, 1, hms);
run;

to try and get the positions of just the hours and minutes (for example) but it's not populating the hour_pos and min_pos.

 

How do I assign (where applicable) the relevant numbers to the relevant variables.

 

2 REPLIES 2
Kurt_Bremser
Super User

Make it easy and use the simpler string functions:

data have;
    infile datalines;
    input hms:$100.;
datalines;
7s
52s
2m9s
3m43s
10m43s
1h2m13s
;

data want;
set have;
help = hms;
if indexc('h',help)
then do;
  hours = input(scan(help,1,'h'),2.);
  help = scan(help,2,'h');
end;
if indexc('m',help)
then do;
  minutes = input(scan(help,1,'m'),2.);
  help = scan(help,2,'m');
end;
seconds = input(scan(help,1,'s'),2.);
drop help;
run;

proc print data=want noobs;
run;

Result:

hms        hours    minutes    seconds

7s           .          .          7  
52s          .          .         52  
2m9s         .          2          9  
3m43s        .          3         43  
10m43s       .         10         43  
1h2m13s      1          2         13  
Ksharp
Super User

Very interesting question.

 

data have;
    infile datalines;
    input hms:$100.;
datalines;
7s
52s
2m9s
3m43s
10m43s
1h2m13s
;;;;
run;
data temp;
 set have;
 n+1;
 do i=1 to countw(hms,,'kd');
  vname=scan(hms,i,,'d');
  value=scan(hms,i,,'kd');
  output;
 end;
run;
proc transpose data=temp out=want;
by n;
id vname;
var value;
run;

Ready to join fellow brilliant minds for the SAS Hackathon?

Build your skills. Make connections. Enjoy creative freedom. Maybe change the world. Registration is now open through August 30th. Visit the SAS Hackathon homepage.

Register today!
How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 2 replies
  • 297 views
  • 3 likes
  • 3 in conversation