温馨提示:本文翻译自stackoverflow.com,查看原文请点击:sas - how to replace string
sas sas-macro

sas - 如何替换字符串

发布于 2020-04-14 16:35:27

如果“ all”列包含“ sch”列中的字符串,则该字符串将被“ rep”中的字符串替换。列“ new_all”是我所期望的。

data a0;
input sch $9. rep $14. ;
cards;
map_clm  map_claim
xyz_ttt  xyz    
drug_clm drug_clm_test 
fee_sch  fee_sch_test
;
run;

data a1;
input all $26. new_all $30.;
cards;
from abc.xyz_ttt d2 left from abc.xyz d2 left
D1.Xwlk,abc.xyz_TTT left D1.xwlk,abc.xyz left
d1.x,abc.map_clms,d2.dos d1.x,abc.map_clms,d2.dos
ABC.XYZ_Ttt left join d1 ABC.xyz left join d1
,tt.drug_CLM, tt.Xyz_ttt ,tt.drug_clm_test, tt.xyz
d3.DOS,t2.fee_SCH,tt.day fd3.DOS,t2.fee_sch_test,tt.day
;
run;

查看更多

提问者
Jeff
被浏览
130
Chris Long 2020-02-04 18:10

我假设您想将column all转换为column new_all,使用a0数据集中的值来描述/控制转换。

%macro do_it;

* Set up some macro variable arrays to hold the from/to pairs;
data _null_;
  set a0 end=end;
  call symput("sch" || _n_, sch);
  call symput("rep" || _n_, rep);
  if end then call symput("max", _n_);
run;

* Process the data;
data want;
  length new_all_new $ 200;
  set a1;

  * Copy the incoming value to the output;
  new_all_new = all;

  * Apply each of the transformations in turn;
  %do i = 1 %to &max;
    new_all_new = tranwrd(new_all_new, "&&sch&i", "&&rep&i");
  %end;

  * Did we get the expected value?;
  if new_all_new ne new_all then do;
    put "ERROR: Did not get expected value: " all= new_all= new_all_new=;
  end;

run;

%mend;

%do_it;

上面的代码应该非常接近,尽管我目前无法对其进行测试。该代码区分大小写;您的预期数据表明您希望不区分大小写地应用转换,同时还要保留其余字符串的大小写。实施起来有点棘手;如果确实需要,则正则表达式搜索和replace(prxparse("s/&&sch&i/&&rep&i/");)可能是最好的方法。

还有一个问题是您要替换“ map_clm”而不是“ map_clms”,这也表明正则表达式可能是最干净的解决方案。

无论如何,我认为这段代码为您提供了一个合理的起点。内置期望值可用于测试是非常棒的。

您是否真的以编程方式修改SQL代码?