创建新的字符串变量,并与另一个变量部分匹配

时间:2019-08-09 12:18:31

标签: regex stata

我正在使用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   |

1 个答案:

答案 0 :(得分: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 |
     +-----------------+