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.
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
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;
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
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.