我在字符串变量中有7位数字,但每条记录的列数不同。下面是我的数据的例子
ser string
101 purchase items id: 1013456
102 entry no: 2017685
103 id: 1897654 item
.....
.....
我的要求是只使用string
变量中的数字创建一个新变量。输出应该如下所示
ser number
101 1013456
102 2017685
103 1897654
我有可以创建为宏变量的数字列表
%let num=1013456,2017685,1897654
我使用了scan
和substr
函数,但没有获得所需的结果
我很感激任何解决方案。感谢
答案 0 :(得分:3)
尝试使用compress()
功能删除不需要的字符,并使用input()
功能转换为数字。
data want;
set have;
number = input(compress(string,':','as'),7.);
drop string;
run;
压缩的第二个参数显式删除:
个字符。 as
修饰符会删除字母字符(a
)和空格字符(s
)。
答案 1 :(得分:2)
您可以使用正则表达式提取数字。查看SAS中的PRX功能。
以下是如何使用正则表达式实现目标的示例:
data inData;
length ser 8 string $100;
ser = 101;
string = 'purchase items id: 1013456';
output;
ser = 102;
string = 'entry no: 2017685';
output;
ser = 103;
string = 'id: 1897654 item';
output;
run;
data outData;
length ser 8 number $7;
retain re;
set inData;
if _n_ = 1 then do;
re = prxparse("/.*(\d{7}).*/");
end;
if prxmatch(re, string) then do;
number = prxposn(re, 1, string);
end;
keep ser number;
run;
答案 2 :(得分:0)
仅使用prxmatch
的简单正则表达式方法:
data have;
input ser string $50.;
cards;
101 purchase items id: 1013456
102 entry no: 2017685
103 id: 1897654 item
;
run;
data want;
set have;
num = input(substr(string,prxmatch('/\d{7}/',string),7),8.);
run;
这只会匹配string
中的第一个7位数字。相比之下,如果它包含任何其他数字,则compress
方法将连接所有这些数字。