提取与变量匹配的字符串中的术语

Extract term within a string that matches a variable

我有一个包含两个字符串变量的大型数据集:people_attendingspecial_attendee:

*Example generated by -dataex-. To install: ssc install dataex
clear
input str148 people_attending str16 special_attendee
"; steve_jobs-apple_CEO; kevin_james-comedian; michael_crabtree-football_player; sharon_stone-actor; bill_gates-microsoft_CEO; kevin_nunes-politician" "michael_crabtree"
"; rob_lowe-actor; ted_cruz-politician; niki_minaj-music_artist; lindsey_whalen-basketball_coach"                                                      "niki_minaj"      
end

第一个变量的长度各不相同,包含每个参加活动的人的列表以及他们的头衔。姓名和头衔用破折号分隔,与会者用分号和 space 分隔。第二个变量与第一个变量中包含的其中一个名称完全匹配。

我想创建第三个变量来提取第二个变量中列出的任何人的头衔。在上面的示例中,我希望新变量是 "football_player" 用于观察 1 和 "music_artist" 用于观察 2.

下面是使用简单的正则表达式执行此操作的方法:

generate wanted = subinstr(people_attending, special_attendee, ">", .)
replace wanted = ustrregexs(0) if ustrregexm(wanted, ">(.*?);")
replace wanted = substr(wanted, 3, strpos(wanted, ";")-3)

list wanted

     +-----------------+
     |          wanted |
     |-----------------|
  1. | football_player |
  2. |    music_artist |
     +-----------------+

在第一步中,您将名称替换为标记 >。然后使用正则表达式提取相关的子字符串。在最后一步,你清理。


编辑:

如果稍微修改一下代码,第三步可以省略:

generate wanted = subinstr(people_attending, special_attendee, ">", .)
replace wanted = ustrregexs(1) if ustrregexm(wanted, ">-(.*?);")