创建与另一个字符串变量部分匹配的新字符串变量 [英] Create new string variable with partial matching of another

查看:14
本文介绍了创建与另一个字符串变量部分匹配的新字符串变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是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   |

推荐答案

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

这篇关于创建与另一个字符串变量部分匹配的新字符串变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆