【问题标题】:Create new string variable with partial matching of another创建与另一个部分匹配的新字符串变量
【发布时间】:2019-08-09 12:18:31
【问题描述】:

我正在使用 Stata 15,我想根据另一个字符串变量的内容创建一个新的字符串变量。

考虑以下玩具变量:

clear

input str18 string
"a b c"        
"d e f"
"g h i"    
end

我知道我可以使用regexm() 函数提取所有出现的abdg

generate new = regexm(string, "a|c|d|g")

list

|string    new |
|--------------|
|  a b c     1 |
|  d e f     1 |
|  g h i     1 |

但是,我怎样才能获得以下信息?

|string    new   |
|----------------|
|  a b c     a c |
|  d e f     d   |
|  g h i     g   |

【问题讨论】:

    标签: regex stata


    【解决方案1】:

    您可以使用ustrregexra() 函数来消除任何匹配字符的出现:

    clear
    
    input str5 string
    "a b c"        
    "d e f"
    "g h i"    
    end
    
    generate wanted = ustrregexra(string, "[^a|c|d|g]", " ")
    
    list
    
         +-----------------+
         | string   wanted |
         |-----------------|
      1. |  a b c    a   c |
      2. |  d e f    d     |
      3. |  g h i    g     |
         +-----------------+
    

    如果要消除剩余空格:

    replace wanted = strtrim(stritrim(wanted))
    
         +-----------------+
         | string   wanted |
         |-----------------|
      1. |  a b c      a c |
      2. |  d e f        d |
      3. |  g h i        g |
         +-----------------+
    

    【讨论】:

      猜你喜欢
      • 2022-11-24
      • 1970-01-01
      • 2014-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-12
      • 1970-01-01
      • 2021-03-28
      相关资源
      最近更新 更多