首页 > 解决方案 > 创建与另一个部分匹配的新字符串变量

问题描述

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

考虑以下玩具变量:

clear

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

我知道我可以使用该regexm()函数来提取所有出现的ab和:dg

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   |

标签: regexstata

解决方案


您可以使用该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 |
     +-----------------+

推荐阅读