【问题标题】:Pattern matching of character variables using SAS使用 SAS 对字符变量进行模式匹配
【发布时间】:2017-01-12 18:30:10
【问题描述】:

我的数据集的字符变量为“PANCARD”,观察结果如下:- FGHIU9635F 东风HI6953G ZXCVB6325F XCVBN9658G DVHIGF963F LPMJI44444 现在我想使用 SAS 使用模式匹配从 10,000 条记录中提取数据。所以我只会得到 FGHIU9635F 东风HI6953G ZXCVB6325F XCVBN9658G 条件是:- 1) 前 5 个字符应该是字母 2)接下来的 4 个字符应该是数字 3) 最后一个是字母。

【问题讨论】:

  • 这个问题(我该如何做一些事情?)在 SO 中是题外话。请为我们提供一些代码。你试过什么了?你挂在哪里?

标签: sas


【解决方案1】:
data have;
   input x $15.;
   if prxmatch('/^[a-z]{5}[0-9]{4}\w[a-z]{1}$/i',strip(x))>0 then output;
   cards;
   FGHIU9635F 
   5DFGHI69530D 
   $XCV66325F
   XCVBN96950R
   DVHITGF963
   LPMJI44444
   ;
run;

【讨论】:

    【解决方案2】:

    在 SAS 中使用 perl 正则表达式是我发现的最有效的方法。这是一个很好的教程

    An Introduction to Perl Regular Expressions in SAS 9

    详细说明...

         data match_values;
           input pancard $15.;
    
           /*------
             Parse pattern once while processing row 1 and not at every row
             ------*/
           retain p_1 p_2 p_3 p_all;
           if _n_=1 then 
           do;
             rule_pttrn_1 = "^[a-zA-Z]{5}";      /*first 5 characters should be alphabets*/
             rule_pttrn_2 = "^[a-zA-Z]{5}\d{4}"; /*first 5 alpha, next 4 charcters should be numeric */ 
             rule_pttrn_3 = ".*[a-zA-Z]$";       /* no matter what is at the begining, last one is alphabet*/
    
             /* parse all rules */
             p_1   = PRXPARSE("/" || rule_pttrn_1 || "/");
             p_2   = PRXPARSE("/" || rule_pttrn_2 || "/");
             p_3   = PRXPARSE("/" || rule_pttrn_3 || "/");
             p_all = prxparse("/^[a-zA-Z]{5}\d{4}.*[a-zA-Z]$/");
           end;
    
           /*-----
             test which patterns match 
             -----*/    
           match1   =prxmatch(p_1  ,strip(pancard));
           match2   =prxmatch(p_2  ,strip(pancard));
           match3   =prxmatch(p_3  ,strip(pancard));
           match_all=prxmatch(p_all,strip(pancard));
    
           /* keep only rows that match all rules */
           if match_all then output;
           keep pancard match:;
    
           cards;
           FGHIU9635F
           5DFGHI69530D
           $XCV66325F
           XCVBN96950R
           DVHITGF963
           LPMJI44444
           ;
        run;
    

    【讨论】:

    • @cpburnz 感谢您的评论,我是新来的,只是详细说明了我的答案。
    猜你喜欢
    • 1970-01-01
    • 2021-11-09
    • 1970-01-01
    • 2013-09-08
    • 1970-01-01
    • 1970-01-01
    • 2020-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多